Compare commits
72 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 |
@@ -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 값을 믿는다.
|
||||
|
||||
@@ -47,7 +47,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` | (모듈 CLAUDE.md) | `live.*` |
|
||||
| `[라이브커머스]` `[라이브]` | `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` | — |
|
||||
@@ -66,8 +66,8 @@
|
||||
- `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
|
||||
|
||||
@@ -68,6 +68,8 @@ MODULE_LABELS: dict[str, str] = {
|
||||
"inout": "입출고 관리",
|
||||
"outreach": "안내문 발송",
|
||||
"live": "라이브 커머스",
|
||||
"live_host": "라이브 호스트 등록",
|
||||
"live_host_edit": "라이브 호스트 수정",
|
||||
"expense_approver": "개인경비",
|
||||
"vacation_approver": "휴가",
|
||||
}
|
||||
|
||||
@@ -3,28 +3,35 @@
|
||||
> 이 모듈만 고칠 때 읽는 요약. 상세는 `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>` 안에서 커서 바로 뒤가 `.jpg`/`.gif`/`.png` 일 때 Ctrl+↑/↓ 로 파일명 번호 변경(없음 → `_2` → `_3` …, 내리면 `_2` 다음은 원래 이름, `_2`~`_99` 만 번호로 인식).
|
||||
- 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`). 저장되는 값은 추가금액뿐.
|
||||
- 옵션/품목 팝업 옵션값 이름·자체 품목코드·추가금액·판매 가격 칸: 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")
|
||||
@@ -482,19 +482,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 +500,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 +533,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")
|
||||
@@ -658,6 +636,7 @@ def variants_update(
|
||||
"failed": {code: 사유}, "unknown": {code: 사유}}
|
||||
100건 묶음 중 일부가 실패해도 성공한 행은 성공으로 기록·표시한다(화면이 그 행을
|
||||
다시 보내지 않게). 하나도 반영되지 않았으면 502.
|
||||
진열·판매는 `CAFE24_SHOP_NOS` 의 다른 쇼핑몰에도 같은 값으로 보낸다 — 실패는 "shop_failed".
|
||||
"""
|
||||
st, user = require_store(request)
|
||||
actor = str(user.get("email") or "")
|
||||
@@ -695,9 +674,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 +714,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, 읽기 전용)."""
|
||||
|
||||
+20
-21
@@ -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}
|
||||
|
||||
@@ -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())
|
||||
@@ -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,23 +370,38 @@
|
||||
applyEdit(from, to, "", lineFrom + col, lineFrom + col);
|
||||
}
|
||||
|
||||
/* Ctrl+↑/↓ — <img> 안에서 커서 바로 뒤가 .jpg/.gif/.png 이면 파일명 번호를 바꾼다.
|
||||
a.jpg → a_2.jpg → a_3.jpg …, 내릴 때는 _2 다음이 원래 이름. 커서는 확장자 앞에 그대로 둔다.
|
||||
_2~_99 만 번호로 본다(product_2024.jpg 의 2024 는 번호가 아니다).
|
||||
/* 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 || !/^\.(jpg|gif|png)/i.test(value.slice(at, at + 4))) return false;
|
||||
var head = value.slice(value.lastIndexOf("<", at - 1), at);
|
||||
if (!/^<img\s[^>]*$/i.test(head)) return false;
|
||||
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 m = head.match(/_([2-9]|[1-9]\d)$/);
|
||||
var n = m ? Number(m[1]) : 1;
|
||||
if (up ? n >= 99 : !m) return true; // 더 갈 곳이 없다
|
||||
var next = up ? n + 1 : n - 1;
|
||||
var text = next < 2 ? "" : "_" + next;
|
||||
var from = at - (m ? m[0].length : 0);
|
||||
applyEdit(from, at, text, from + text.length, from + text.length);
|
||||
// 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;
|
||||
}
|
||||
|
||||
@@ -546,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");
|
||||
@@ -561,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();
|
||||
@@ -940,6 +969,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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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` 도 잠근 뒤 거절. 입고 기록을 지우면 다시 열림.
|
||||
@@ -106,8 +109,8 @@
|
||||
|
||||
## 오른쪽 달력 (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글자까지 다 보임, 더 길면 … + 말풍선에 전체 이름).
|
||||
@@ -119,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`).
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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>
|
||||
@@ -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=20261104c" />{% 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=20261104c" 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=20261104c" />{% 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=20261104c" 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=20261104c" />{% 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>
|
||||
|
||||
@@ -102,4 +102,4 @@
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261104c" 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=20261104c" />{% 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=20261104c" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261105a" defer></script>{% endblock %}
|
||||
|
||||
@@ -2,20 +2,36 @@
|
||||
|
||||
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 코드가 기준.
|
||||
> 정적 파일: `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/modules/asset/media.py prepare_photo` 재사용(바꾸면 양쪽 확인). 쇼핑몰 로고 = 말레이시아 배송 모듈 `app/static/dispatch/courier/tiktok.png`·`shopee.png`(지우거나 이름을 바꾸면 호스트 설정 로고도 깨짐).
|
||||
|
||||
- 말레이시아 라이브 커머스 방송의 호스트 정보·방송 스케줄. 권한키 `live`, DB `LIVE_DB_URL`(없으면 "설정 필요" 안내).
|
||||
- **호스트 설정** `/live/settings` — Full Name (as per IC)(필수)·Phone Number·Email·Address·Bank Name·Bank Account Number·Tiktok Handle(`@`·주소를 붙여 넣어도 계정명만 저장).
|
||||
**계좌 등 개인정보라 ERP 관리자만**(`is_admin`) — 화면·저장·지우기 모두. 스케줄 화면에는 `db.host_choices`(이름·틱톡·사용 여부)만 넘긴다.
|
||||
- **호스트 설정** `/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` 권한자 모두) — 호스트·날짜·시작/끝 시간·방송 장소·판매금액·커미션·호스트 비용·결과 이미지. 호스트·날짜·시작·끝 시간 필수(판매금액은 방송 후 입력).
|
||||
시간은 입력한 말레이시아 시간 그대로(시간대 변환 없음, DATE·TIME). 판매금액 단위 RM(`NUMERIC(14,2)`, `store.parse_money`). 끝 시간이 시작보다 이르면 자정을 넘긴 방송.
|
||||
- **호스트 비용**(`store.session_pay`, 저장 안 함 — 화면마다 계산) = 시간 × RM 25(`HOURLY_RATE`) + 판매금액 × 10%(`COMMISSION_PERCENT`). 요율이 코드 상수라 바꾸면 지난 방송 금액도 바뀐다.
|
||||
- **달력 보기** `/live/calendar?month=`(`store.build_calendar`, 사용자가 준 화면 참고, 글자도 영어 그대로) — 줄 = 2시간 칸(06:00~24:00 늘 보임, 그보다 이른 칸은 방송이 있을 때만, 칸은 시작 시간으로 정함), 열 = 날짜, 주말 노랑, Jump to Date, 위 달 합계, 맨 아래 날짜별 TOTAL SALES·AD SPEND·HOST FEE·ROAS.
|
||||
카드 머리 = **Tiktok Handle**(없으면 이름, 색 = 호스트 id 순 `HOST_COLORS`), SALES·COM·Fee. 카드 머리를 끌어 빈 칸으로 = 옮기기(`move`, 방송 길이 유지) · 다른 카드 위 = 맞바꾸기(`swap_with`, 날짜·시간 교환). 다시 그린 뒤 가로 위치 유지(sessionStorage). 빈 칸 + = 그 날짜·시간이 채워진 추가 창.
|
||||
**AD SPEND** = 날짜별 광고비 `live_daily_ad_spend`(마이그레이션 002, `POST /live/ad-spend`, 빈칸 = 지우기), ROAS = 판매금액 ÷ 광고비(광고비 없으면 `-`). 002 미적용이면 0 으로 보이고 저장만 안내.
|
||||
- **스케줄표** `/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 공용 사이드바는 번역하지 않는다.
|
||||
|
||||
+39
-38
@@ -8,17 +8,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, time
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from psycopg.errors import ForeignKeyViolation, UndefinedTable
|
||||
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 = ("full_name", "phone", "email", "address", "bank_name", "bank_account", "tiktok_handle")
|
||||
_HOST_COLUMNS = ("platform", "display_name", "full_name", "phone", "email", "address", "bank_name", "bank_account")
|
||||
|
||||
|
||||
class LiveDBStore:
|
||||
@@ -39,26 +38,42 @@ class LiveDBStore:
|
||||
def host_choices(self) -> list[dict[str, Any]]:
|
||||
"""스케줄 화면 호스트 고르기 — 개인정보·계좌는 뺀다."""
|
||||
with self._pool.connection() as conn:
|
||||
return conn.execute("SELECT id, full_name, tiktok_handle, is_active FROM live_hosts "
|
||||
"ORDER BY full_name, id").fetchall()
|
||||
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 (full_name, phone, email, address, bank_name, bank_account, tiktok_handle, "
|
||||
"is_active, created_by, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id",
|
||||
"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 full_name=%s, phone=%s, email=%s, address=%s, bank_name=%s, bank_account=%s, "
|
||||
"tiktok_handle=%s, is_active=%s, updated_by=%s WHERE id=%s RETURNING id",
|
||||
"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:
|
||||
@@ -73,7 +88,7 @@ class LiveDBStore:
|
||||
"""start 이상 end 미만, 날짜·시간 순. 줄마다 images = [{id, filename}](내용 제외)."""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT b.*, h.full_name AS host_name, h.tiktok_handle FROM live_broadcasts b JOIN live_hosts h ON h.id = b.host_id "
|
||||
"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(
|
||||
@@ -83,6 +98,13 @@ class LiveDBStore:
|
||||
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():
|
||||
@@ -97,15 +119,16 @@ class LiveDBStore:
|
||||
raise LiveError("호스트를 찾을 수 없습니다.")
|
||||
if not host["is_active"] and values["host_id"] != current:
|
||||
raise LiveError("사용 안 함으로 바뀐 호스트입니다 — 다른 호스트를 고르세요.")
|
||||
args = (values["host_id"], values["broadcast_date"], values["start_time"], values["end_time"], values["venue"],
|
||||
values["sales_amount"], by)
|
||||
# 방송 장소(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, venue, sales_amount, updated_by, created_by) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id", (*args, by)).fetchone()["id"])
|
||||
"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, venue=%s, "
|
||||
"sales_amount=%s, updated_by=%s WHERE id=%s", (*args, broadcast_id))
|
||||
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)
|
||||
@@ -142,28 +165,6 @@ class LiveDBStore:
|
||||
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"]))
|
||||
|
||||
# ── 날짜별 광고비(002) ───────────────────────────────────
|
||||
def ad_spends(self, start: date, end: date) -> dict[date, Decimal]:
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute("SELECT ad_date, ad_spend FROM live_daily_ad_spend WHERE ad_date >= %s AND ad_date < %s", (start, end)).fetchall()
|
||||
except UndefinedTable:
|
||||
return {}
|
||||
return {r["ad_date"]: r["ad_spend"] for r in rows}
|
||||
|
||||
def save_ad_spend(self, day: date, amount: Decimal | None, *, by: str) -> None:
|
||||
"""빈칸(None) = 지우기."""
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
if amount is None:
|
||||
conn.execute("DELETE FROM live_daily_ad_spend WHERE ad_date=%s", (day,))
|
||||
else:
|
||||
conn.execute("INSERT INTO live_daily_ad_spend (ad_date, ad_spend, updated_by) VALUES (%s,%s,%s) "
|
||||
"ON CONFLICT (ad_date) DO UPDATE SET ad_spend=EXCLUDED.ad_spend, updated_by=EXCLUDED.updated_by, updated_at=now()",
|
||||
(day, amount, by))
|
||||
except UndefinedTable:
|
||||
raise LiveError("DB 마이그레이션 live_db 002(광고비)가 아직 적용되지 않았습니다.") from None
|
||||
|
||||
# ── 결과 이미지 ─────────────────────────────────────────
|
||||
def get_image(self, image_id: int) -> dict[str, Any] | None:
|
||||
with self._pool.connection() as conn:
|
||||
|
||||
@@ -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
|
||||
+25
-12
@@ -18,49 +18,62 @@ EN: dict[str, str] = {
|
||||
# 방송 창
|
||||
"방송 추가": "Add Broadcast", "방송 고치기": "Edit Broadcast", "호스트": "Host", "호스트를 고르세요": "Select a host",
|
||||
"사용 안 함": "Inactive", "방송 날짜": "Broadcast Date", "시작 시간": "Start Time", "끝 시간": "End Time",
|
||||
"시간은 말레이시아 시간으로 입력합니다.": "Enter times in Malaysia time.", "방송 장소": "Venue", "판매금액 (RM)": "Sales (RM)",
|
||||
"시간은 말레이시아 시간으로 입력합니다.": "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 {base} + 커미션 RM {commission}": "Base RM {base} + commission RM {commission}",
|
||||
"시간 요금(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", "날짜로 이동": "Jump to Date",
|
||||
"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}",
|
||||
"{date} 광고비 고치기": "Edit ad spend for {date}", "방송 결과 이미지": "Result images", "이미지 {n}": "IMG {n}",
|
||||
"방송 결과 이미지": "Result images", "이미지 {n}": "IMG {n}",
|
||||
# 호스트 설정
|
||||
"◀ 스케줄표": "◀ Schedule", "+ 호스트 등록": "+ Add Host", "호스트 등록": "Add Host", "호스트 고치기": "Edit Host",
|
||||
"이름 (IC 기준)": "Full Name (as per IC)", "전화번호": "Phone Number", "이메일": "Email", "주소": "Address", "은행명": "Bank Name",
|
||||
"간단한 이름": "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}?", "{day} 광고비 (RM) — 비우면 지웁니다": "{day} ad spend (RM) — leave empty to clear",
|
||||
"이 이미지": "this image", "{name} 를 지울까요?": "Delete {name}?",
|
||||
# 저장 결과·입력 오류
|
||||
"저장했습니다.": "Saved.", "옮겼습니다.": "Moved.", "광고비를 저장했습니다.": "Ad spend saved.", "방송을 지웠습니다.": "Broadcast deleted.",
|
||||
"저장했습니다.": "Saved.", "옮겼습니다.": "Moved.","방송을 지웠습니다.": "Broadcast deleted.",
|
||||
"이미지를 지웠습니다.": "Image deleted.", "호스트를 저장했습니다.": "Host saved.", "호스트를 지웠습니다.": "Host deleted.",
|
||||
"잘못된 요청입니다.": "Invalid request.",
|
||||
"이름 (IC 기준)을 입력하세요.": "Enter the Full Name (as per IC).", "{label} 이(가) 너무 깁니다({limit}자까지).": "{label} is too long (up to {limit} characters).",
|
||||
"간단한 이름을 입력하세요.": "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.",
|
||||
"판매금액은 숫자로 입력하세요.": "Sales must be a number.", "판매금액은 0 이상 숫자로 입력하세요.": "Sales must be a number of 0 or more.", "판매금액이 너무 큽니다.": "Sales is too large.",
|
||||
"{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.", "방송 장소가 너무 깁니다(200자까지).": "Venue is too long (up to 200 characters).",
|
||||
"호스트를 고르세요.": "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.",
|
||||
"DB 마이그레이션 live_db 002(광고비)가 아직 적용되지 않았습니다.": "DB migration live_db 002 (ad spend) has not been applied yet.", "이미지를 찾을 수 없습니다.": "Image not found.",
|
||||
"이미지를 찾을 수 없습니다.": "Image not found.",
|
||||
"{name}: {detail}": "{name}: {detail}",
|
||||
# 권한·설정
|
||||
"로그인이 필요합니다.": "Please sign in.", "라이브 커머스 모듈 권한이 없습니다.": "You don't have access to the Live Commerce module.",
|
||||
@@ -76,7 +89,7 @@ EN: dict[str, str] = {
|
||||
|
||||
# 화면 스크립트에 넘기는 문구(window.LV_T)
|
||||
JS_KEYS = ("확인", "취소", "지우기", "서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.", "이 이미지", "{name} 를 지울까요?",
|
||||
"{day} 광고비 (RM) — 비우면 지웁니다")
|
||||
"이미지에서 매출을 읽는 중…")
|
||||
|
||||
_MONTH_NAMES = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
|
||||
|
||||
|
||||
@@ -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))
|
||||
+80
-31
@@ -6,14 +6,16 @@
|
||||
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 관리자만, 계좌 등 개인정보)
|
||||
GET /live/settings 설정 — 호스트 정보(ERP 관리자만, 계좌 등 개인정보. `live_host` 칩은 이름·틱톡·상태만)
|
||||
POST /live/settings/hosts 호스트 추가·고치기 · POST /live/settings/hosts/{id}/delete
|
||||
권한: 모듈 권한키 `live`(스케줄), 설정은 ERP 관리자. DB: LIVE_DB_URL(live_db) — 없으면 "설정 필요" 안내.
|
||||
권한: 모듈 권한키 `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
|
||||
|
||||
@@ -23,7 +25,7 @@ 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 i18n, store
|
||||
from . import holidays, i18n, ocr, store
|
||||
|
||||
router = APIRouter(prefix="/live", tags=["live"])
|
||||
|
||||
@@ -61,6 +63,18 @@ def _admin(request: Request) -> dict[str, Any]:
|
||||
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:
|
||||
@@ -93,8 +107,10 @@ def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, An
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
lang = _lang(request)
|
||||
return render_template(request, name, {"user": user, "is_admin": is_admin(user), "lang": lang,
|
||||
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})
|
||||
|
||||
|
||||
@@ -133,7 +149,7 @@ def index(request: Request, month: str = "") -> Any:
|
||||
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(),
|
||||
"max_images": store.MAX_IMAGES})
|
||||
"accounts": st.account_choices(), "max_images": store.MAX_IMAGES})
|
||||
|
||||
|
||||
@router.get("/calendar", response_class=HTMLResponse)
|
||||
@@ -144,9 +160,12 @@ def calendar(request: Request, month: str = "") -> Any:
|
||||
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"]), st.ad_spends(span["start"], span["end"]), 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(),
|
||||
"max_images": store.MAX_IMAGES})
|
||||
"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")
|
||||
@@ -166,18 +185,6 @@ def broadcast_move(request: Request, broadcast_id: int, broadcast_date: str = Fo
|
||||
return _ok(request, "옮겼습니다.")
|
||||
|
||||
|
||||
@router.post("/ad-spend")
|
||||
def ad_spend_save(request: Request, day: str = Form(""), amount: str = Form("")) -> JSONResponse:
|
||||
user = _user(request)
|
||||
st = _db(request)
|
||||
try:
|
||||
when, _ = store.parse_move(day, "00:00")
|
||||
st.save_ad_spend(when, store.parse_money(amount), 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]
|
||||
@@ -196,20 +203,36 @@ def _read_images(files: list[UploadFile]) -> list[dict[str, Any]]:
|
||||
|
||||
@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(""), venue: str = Form(""), sales_amount: 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, "venue": venue, "sales_amount": sales_amount})
|
||||
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)
|
||||
@@ -242,7 +265,7 @@ def image_delete(request: Request, image_id: int) -> JSONResponse:
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# 설정 — 호스트 정보(ERP 관리자만: 계좌 등 개인정보)
|
||||
# 설정 — 호스트 정보(ERP 관리자만: 계좌 등 개인정보). `live_host` 칩 = 새 호스트 등록만.
|
||||
# ────────────────────────────────────────────────────────────
|
||||
@router.get("/settings", response_class=HTMLResponse)
|
||||
def settings(request: Request) -> Any:
|
||||
@@ -253,27 +276,53 @@ def settings(request: Request) -> Any:
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
if not is_admin(user):
|
||||
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)
|
||||
return _render(request, "live/settings.html", user, {"hosts": st.list_hosts()})
|
||||
# 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(""), full_name: str = Form(""), phone: str = Form(""), email: str = Form(""),
|
||||
address: str = Form(""), bank_name: str = Form(""), bank_account: str = Form(""), tiktok_handle: str = Form(""),
|
||||
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:
|
||||
user = _admin(request)
|
||||
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({"full_name": full_name, "phone": phone, "email": email, "address": address, "bank_name": bank_name,
|
||||
"bank_account": bank_account, "tiktok_handle": tiktok_handle})
|
||||
st.save_host(_opt_id(id), values, is_active=bool(is_active), by=user.get("email", ""))
|
||||
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)
|
||||
|
||||
+75
-37
@@ -18,16 +18,19 @@ THUMB_SIZE = 160
|
||||
# shortcut: 요율이 코드 상수라 바꾸면 지난 방송 금액도 다시 계산된다 — 요율이 바뀌는 일이 생기면 방송마다 저장하도록 바꿀 것
|
||||
HOURLY_RATE = Decimal("25") # 호스트 시간당 요금(RM)
|
||||
COMMISSION_PERCENT = Decimal("10") # 판매금액의 %
|
||||
SLOT_HOURS = 2 # 달력 한 칸
|
||||
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 = {"full_name": 200, "phone": 40, "email": 254, "address": 500, "bank_name": 100, "bank_account": 40, "tiktok_handle": 64}
|
||||
_LABELS = {"full_name": "이름 (IC 기준)", "phone": "전화번호", "email": "이메일", "address": "주소", "bank_name": "은행명",
|
||||
"bank_account": "계좌번호", "tiktok_handle": "틱톡 핸들"}
|
||||
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]+$")
|
||||
@@ -44,9 +47,13 @@ def clean_handle(raw: Any) -> str:
|
||||
|
||||
|
||||
def clean_host(values: dict[str, Any]) -> dict[str, str]:
|
||||
"""호스트 입력 검사 — 이름만 필수, 나머지는 있으면 형식 확인. 틀리면 ValueError."""
|
||||
"""호스트 입력 검사 — 쇼핑몰·간단한 이름·이름만 필수, 나머지는 있으면 형식 확인. 틀리면 ValueError."""
|
||||
out = {k: str(values.get(k) or "").strip() for k in HOST_LIMITS}
|
||||
out["tiktok_handle"] = clean_handle(values.get("tiktok_handle"))
|
||||
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():
|
||||
@@ -58,24 +65,22 @@ def clean_host(values: dict[str, Any]) -> dict[str, str]:
|
||||
raise LiveError("전화번호는 숫자·+·-·괄호만 입력하세요.")
|
||||
if out["bank_account"] and not _ACCOUNT_RE.match(out["bank_account"]):
|
||||
raise LiveError("계좌번호는 숫자·-만 입력하세요.")
|
||||
if out["tiktok_handle"] and not _HANDLE_RE.match(out["tiktok_handle"]):
|
||||
raise LiveError("틱톡 핸들은 영문·숫자·밑줄·점만 입력하세요.")
|
||||
return out
|
||||
|
||||
|
||||
def parse_money(raw: Any) -> Decimal | None:
|
||||
"""판매금액(RM) — 빈칸은 None(아직 입력 안 함), 0 이상, 소수 둘째 자리까지. 쉼표·RM 허용."""
|
||||
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("판매금액은 숫자로 입력하세요.") from None
|
||||
raise LiveError("{label}은(는) 숫자로 입력하세요.", label=label) from None
|
||||
if not n.is_finite() or n < 0:
|
||||
raise LiveError("판매금액은 0 이상 숫자로 입력하세요.")
|
||||
raise LiveError("{label}은(는) 0 이상 숫자로 입력하세요.", label=label)
|
||||
if n > MAX_SALES:
|
||||
raise LiveError("판매금액이 너무 큽니다.")
|
||||
raise LiveError("{label}이(가) 너무 큽니다.", label=label)
|
||||
return n.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||
|
||||
|
||||
@@ -100,15 +105,18 @@ def clean_broadcast(values: dict[str, Any]) -> dict[str, Any]:
|
||||
day = date.fromisoformat(str(values.get("broadcast_date") or "").strip())
|
||||
except ValueError:
|
||||
raise LiveError("방송 날짜를 입력하세요.") from None
|
||||
venue = str(values.get("venue") or "").strip()
|
||||
if len(venue) > 200:
|
||||
raise LiveError("방송 장소가 너무 깁니다(200자까지).")
|
||||
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("끝 시간이 시작 시간과 같습니다.")
|
||||
return {"host_id": int(host), "broadcast_date": day, "start_time": start, "end_time": end,
|
||||
"venue": venue, "sales_amount": parse_money(values.get("sales_amount"))}
|
||||
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]:
|
||||
@@ -133,11 +141,12 @@ def _duration(start: time, end: time) -> timedelta:
|
||||
|
||||
|
||||
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, "fee": base + commission}
|
||||
return {"hours": hours, "base": base, "commission": commission}
|
||||
|
||||
|
||||
def fmt_short(n: Decimal) -> str:
|
||||
@@ -151,14 +160,17 @@ def broadcast_view(b: dict[str, Any], lang: str = "ko") -> dict[str, Any]:
|
||||
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"],
|
||||
"sales": fmt_money(b["sales_amount"]), "commission": fmt_money(pay["commission"]), "fee": fmt_money(pay["fee"]),
|
||||
"images": b["images"], "pay": pay, "id": b["id"],
|
||||
"label": b["tiktok_handle"] or b["host_name"], "color": HOST_COLORS[b["host_id"] % len(HOST_COLORS)],
|
||||
"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(pay["fee"]),
|
||||
"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 "",
|
||||
"venue": b["venue"], "sales_amount": f"{b['sales_amount']:.2f}" if b["sales_amount"] is not None 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"]]},
|
||||
}
|
||||
|
||||
@@ -167,31 +179,57 @@ def _roas(sales: Decimal, ad_spend: Decimal) -> str:
|
||||
return f"{sales / ad_spend:.2f}" if ad_spend else "-"
|
||||
|
||||
|
||||
def build_calendar(span: dict[str, Any], broadcasts: list[dict[str, Any]], ad_spend: dict[date, Decimal], today: date, lang: str = "ko") -> dict[str, Any]:
|
||||
"""달력 보기 값 — 날짜(열)·2시간 칸(줄)·날짜별 합계·달 합계. 칸은 시작 시간으로 정한다."""
|
||||
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 = {b["start_time"].hour // SLOT_HOURS * SLOT_HOURS for b, _ in views}
|
||||
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 = sum((b["sales_amount"] or Decimal(0) for b, _ in mine), Decimal(0))
|
||||
fee = sum((v["pay"]["fee"] for _, v in mine), Decimal(0))
|
||||
spend = ad_spend.get(day, Decimal(0))
|
||||
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 hour in sorted(set(range(FIRST_SLOT_HOUR, 24, SLOT_HOURS)) | used):
|
||||
for k, hour in enumerate(hours):
|
||||
end_hour = (hour + SLOT_HOURS) % 24
|
||||
cells = [{"iso": d["iso"], "is_weekend": d["is_weekend"],
|
||||
"cards": [v for b, v in views if b["broadcast_date"] == d["date"] and b["start_time"].hour // SLOT_HOURS * SLOT_HOURS == hour]}
|
||||
for d in days]
|
||||
slots.append({"start": f"{hour:02d}:00", "end": f"{end_hour:02d}:00", "label": f"{hour:02d}:00 - {end_hour:02d}:00", "cells": cells})
|
||||
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} Hours (RM{fmt_short(HOURLY_RATE * SLOT_HOURS)} Base)" if lang == "en" else f"{SLOT_HOURS}시간 (기본 RM{fmt_short(HOURLY_RATE * SLOT_HOURS)})",
|
||||
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)}}
|
||||
|
||||
|
||||
@@ -11,9 +11,9 @@
|
||||
</nav>
|
||||
<span class="lv-gap"></span>
|
||||
{% include "live/_lang.html" %}
|
||||
{% if is_admin %}<a class="erp-btn erp-btn-outline" href="/live/settings">{{ t('호스트 설정') }}</a>{% endif %}
|
||||
{% 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 is_admin %}<a href="/live/settings">{{ t('호스트 설정') }}</a>{% else %}{{ t('ERP 관리자에게 등록을 요청하세요.') }}{% endif %}</p>
|
||||
<p class="lv-note">{{ t('방송을 추가하려면 먼저 호스트를 등록해야 합니다.') }} {% if can_add_host %}<a href="/live/settings">{{ t('호스트 설정') }}</a>{% else %}{{ t('ERP 관리자에게 등록을 요청하세요.') }}{% endif %}</p>
|
||||
{% endif %}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{#- 방송 추가·고치기 창 — 스케줄표·달력 공통(live.js). 호스트 고르기엔 이름·틱톡만(계좌 등은 설정 화면). -#}
|
||||
{#- 방송 추가·고치기 창 — 스케줄표·달력 공통(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>
|
||||
@@ -6,17 +6,29 @@
|
||||
<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.full_name }}{% if h.tiktok_handle %} (@{{ h.tiktok_handle }}){% endif %}{% if not h.is_active %} — {{ t('사용 안 함') }}{% endif %}</option>{% endfor %}
|
||||
{% 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('방송 장소') }} <input class="erp-input" type="text" name="venue" maxlength="200" /></label>
|
||||
<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>
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
<script>window.LV_T = {{ js_text | tojson }};</script>
|
||||
<script src="/static/live.js?v=20261104c" defer></script>
|
||||
<script src="/static/live.js?v=20261106f" defer></script>
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{#- 라이브 커머스 달력 보기(2026-11-04) — 줄 = 2시간 칸, 열 = 날짜, 맨 아래 = 날짜별 합계. 카드 머리 = Tiktok Handle(없으면 이름).
|
||||
{#- 라이브 커머스 달력 보기(2026-11-04) — 줄 = 2시간 칸, 열 = 날짜, 맨 아래 = 날짜별 합계. 카드 머리 = 호스트 간단한 이름 + 그 방송의 틱톡 계정.
|
||||
카드 머리를 끌어 빈 칸으로 옮기거나 다른 카드 위에 놓아 맞바꾼다(live.js). 문구 = t()(i18n.py), 영문은 CSS 로 대문자(받은 화면과 같게). -#}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261104c" />{% endblock %}
|
||||
{% 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" %}
|
||||
|
||||
@@ -14,10 +17,6 @@
|
||||
<div class="lv-kpi"><span>ROAS</span><b>{{ cal.totals.roas }}</b></div>
|
||||
</div>
|
||||
|
||||
<nav class="lv-jump" aria-label="{{ t('날짜로 이동') }}">
|
||||
<span class="lv-jump-label">{{ t('날짜로 이동') }}:</span>
|
||||
{% for d in cal.days %}<button type="button" class="lv-jump-day{% if d.is_weekend %} is-weekend{% endif %}{% if d.is_today %} is-today{% endif %}" data-jump="{{ d.iso }}">{{ d.day }}</button>{% endfor %}
|
||||
</nav>
|
||||
<p class="lv-tip">{{ t('팁: 카드 머리를 끌어 옮기거나 맞바꿀 수 있습니다. 오른쪽으로 스크롤하면 이달 {n}일을 모두 볼 수 있습니다.').format(n=cal.days | length) }}</p>
|
||||
|
||||
<div class="lv-cal-wrap" id="lv-cal-wrap">
|
||||
@@ -37,27 +36,29 @@
|
||||
{% 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 %}
|
||||
<td class="lv-cell{% if cell.is_weekend %} is-weekend{% endif %}" data-drop data-day="{{ cell.iso }}" data-start="{{ slot.start }}">
|
||||
{% 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 %}">
|
||||
<span class="lv-card-grip" aria-hidden="true">✥</span>
|
||||
<span class="lv-card-name">{{ c.label }}</span>
|
||||
{% 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('방송 결과 이미지') }}">{{ t('이미지 {n}').format(n=c.images | length) }}</a>{% endif %}</footer>
|
||||
<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>
|
||||
{% endfor %}
|
||||
{% endif %}{% endfor %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
@@ -68,7 +69,7 @@
|
||||
<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 }} <button type="button" class="lv-total-edit" data-spend="{{ d.iso }}" data-value="{{ d.spend if d.spend else '' }}" aria-label="{{ t('{date} 광고비 고치기').format(date=d.iso) }}">✎</button></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>
|
||||
@@ -79,8 +80,32 @@
|
||||
</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 %}{% include "live/_scripts.html" %}{% 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 %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% 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=20261104c" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261106h" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="lv" lang="{{ lang }}">
|
||||
@@ -8,18 +8,21 @@
|
||||
|
||||
<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('호스트') }}</th><th>{{ t('방송 장소') }}</th><th class="lv-r">{{ t('판매금액(RM)') }}</th><th class="lv-r">{{ t('커미션 10%(RM)') }}</th><th class="lv-r">{{ t('호스트 비용(RM)') }}</th><th>{{ t('방송 결과') }}</th><th></th></tr></thead>
|
||||
{% 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 data-label="{{ t('방송 장소') }}">{{ r.venue }}</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)') }}" title="{{ t('기본 요금 RM {base} + 커미션 RM {commission}').format(base=r.pay.base, commission=r.pay.commission) }}">{{ r.fee }}</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>
|
||||
@@ -27,7 +30,7 @@
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="9" class="erp-empty">{{ t('이 달에 등록한 방송이 없습니다.') }}</td></tr>
|
||||
<tr><td colspan="11" class="erp-empty">{{ t('이 달에 등록한 방송이 없습니다.') }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -1,39 +1,55 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{#- 라이브 커머스 설정(2026-11-04) — 호스트 정보. 계좌 등 개인정보라 ERP 관리자만(router.settings). 추가·고치기는 같은 창(live.js). 문구 = t()(i18n.py). -#}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261104c" />{% endblock %}
|
||||
{#- 라이브 커머스 설정(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" %}
|
||||
<button type="button" class="erp-btn erp-btn-primary" id="lv-add">{{ t('+ 호스트 등록') }}</button>
|
||||
{% 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('이름 (IC 기준)') }}</th><th>{{ t('전화번호') }}</th><th>{{ t('이메일') }}</th><th>{{ t('주소') }}</th><th>{{ t('은행명') }}</th><th>{{ t('계좌번호') }}</th><th>{{ t('틱톡 핸들') }}</th><th>{{ t('상태') }}</th><th></th></tr></thead>
|
||||
<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>
|
||||
<td data-label="{{ t('틱톡 핸들') }}">{% if h.tiktok_handle %}@{{ h.tiktok_handle }}{% endif %}</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">
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-edit='{{ {"id": h.id, "full_name": h.full_name, "phone": h.phone, "email": h.email, "address": h.address, "bank_name": h.bank_name, "bank_account": h.bank_account, "tiktok_handle": h.tiktok_handle, "is_active": h.is_active} | tojson }}'>{{ t('고치기') }}</button>
|
||||
{% 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="9" class="erp-empty">{{ t('등록한 호스트가 없습니다.') }}</td></tr>
|
||||
<tr><td colspan="{{ 10 if is_admin else 5 if can_edit_host else 4 }}" class="erp-empty">{{ t('등록한 호스트가 없습니다.') }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -45,7 +61,15 @@
|
||||
<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>
|
||||
@@ -53,8 +77,7 @@
|
||||
<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>
|
||||
<label class="lv-field">{{ t('틱톡 핸들') }} <input class="erp-input" type="text" name="tiktok_handle" maxlength="200" placeholder="@handle" /></label>
|
||||
<label class="lv-check"><input type="checkbox" name="is_active" value="1" checked /> {{ t('사용 (끄면 새 방송에서 고를 수 없습니다)') }}</label>
|
||||
{% 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>
|
||||
|
||||
@@ -88,6 +88,11 @@
|
||||
(마지막 업데이트 옆 안내), 탭이 안 보이면 안 묻고 다시 보이면 바로. 보는 사람이 직접 누른 업데이트는 진행 창이 새로 그린다. `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` 수수료 차감 매출 기준, 보기 기준에 따라 하나만). 광고비 표 없으면 줄 없음.
|
||||
- **열 접기**(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`)에 계속 유지,
|
||||
@@ -106,9 +111,17 @@
|
||||
- **표 몸통 칸에는 풍선 도움말(title) 없음**(2026-10-22 사용자 요청) — 입력 칸·날짜 칸(공휴일은 칸 안 글자)·광고비 줄 모두. 열 머리글 말풍선은 그대로.
|
||||
새 칸 기능에 title 을 다시 달지 말 것(설명은 표 아래 안내 문구에).
|
||||
|
||||
## 틱톡 (`/performance/tiktok`, 2026-11-05, 마이그레이션 없음)
|
||||
|
||||
- 광고비 탭 틀(기간 이동·KPI·표·그래프·연 누적), 표 열 = ROAS·광고비·매출. 값은 광고 API 만(읽기 전용, 칸 입력·메모 없음). 화면 데이터 `ad_spend.build_tiktok_dashboard`.
|
||||
- **틱톡 탭에서만 보임** — 채널 코드 `tiktok` 은 `ad_sources` 에는 있지만 `ad_spend.CHANNELS` 에는 넣지 않는다(넣으면 광고비 탭 합계에 들어감). 쇼핑몰 표(`perf_marketplaces`)에도 없어 매출 실적 합계·열과 무관. 저장은 다른 광고 API 처럼 `perf_ad_spend`(`source='api'`), 매출 = `metrics["매출"]`.
|
||||
- 설정 = 실적 설정 **광고 API 연동** 카드 → 틱톡 — 광고 계정 ID·장기 액세스 토큰·틱톡샵 ID(선택). [광고비 업데이트]·광고비 자동 업데이트에 함께 돈다.
|
||||
- `ad_sources/tiktok_ads.py` — `report/integrated/get`(30일씩), 매출 = 웹 구매금액 + 틱톡샵 매출, 틱톡샵 ID 가 있으면 `gmv_max/report/get` 비용·매출도 더함(항목별 값은 metrics 에 따로 저장). 외화 계정은 그날 환율로 원화(`fx`). ROAS = 매출 ÷ 광고비.
|
||||
**실제 토큰 대조 전**(2026-11-05) — 공식 문서를 읽지 못해 지표 이름은 이차 자료로 확인. 일반 보고서에 GMV Max 가 이미 들어 있으면 틱톡샵 ID 를 넣었을 때 중복되므로, 처음 쓸 때 광고 관리자 화면과 대조할 것.
|
||||
|
||||
## 광고비 (`/performance/ads`)
|
||||
|
||||
- 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니.
|
||||
- 탭은 [매출 실적]·[광고비]·[틱톡] + 맨 오른쪽 설정 톱니.
|
||||
- **표 모양(2026-10-22)** — 매출 실적 표와 같은 `perf-autofit`(열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정).
|
||||
- **기타광고비** 열(`etc`, 애터미아자몰 오른쪽, 2026-10-22) — 쇼핑몰에 딸리지 않은 광고비 직접 입력. 매출 쇼핑몰이 없어(`ad_spend.NO_SALES`) ROAS 없음·매출 탭 광고비 줄에 안 나옴, 광고비 합계·매출 대비 광고비에는 들어감.
|
||||
- `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`. 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로.
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다)."""
|
||||
"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다 —
|
||||
틱톡만 예외: 광고비 탭에 안 나오게 CHANNELS 에 넣지 않고 틱톡 탭이 따로 읽는다)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .base import AdSource
|
||||
from .google_ads import GoogleAdsSource
|
||||
from .meta_ads import MetaAdsSource
|
||||
from .tiktok_ads import TiktokAdsSource
|
||||
|
||||
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource())
|
||||
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource(), TiktokAdsSource())
|
||||
_BY_CODE = {s.code: s for s in _SOURCES}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
"""틱톡 광고(TikTok API for Business v1.3) — 날짜별 광고비·매출·ROAS. 화면은 틱톡 탭(광고비 탭·매출 실적에는 안 나옴).
|
||||
|
||||
인증(2026-11-05): 광고 계정(advertiser) ID 하나 + 장기 액세스 토큰(머리글 Access-Token). 토큰 앱에 보고서·광고 계정 읽기 권한이 있어야 한다.
|
||||
|
||||
조회
|
||||
GET /report/integrated/get/ — report_type=BASIC · data_level=AUCTION_ADVERTISER · 차원 advertiser_id·stat_time_day.
|
||||
매출 = 웹 구매금액(total_complete_payment_rate — 이름과 달리 금액) + 틱톡샵 매출(total_onsite_shopping_value).
|
||||
GET /gmv_max/report/get/ — 틱톡샵 ID 를 넣었을 때만. 비용(cost)·매출(gross_revenue)을 더한다.
|
||||
- 하루 단위 조회는 기간 제한이 있어 30일씩 나눠 묻는다.
|
||||
- 금액은 광고 계정 통화 → 그날 환율로 원화(fx.krw_rates, 메타와 같음).
|
||||
- ROAS(%) = 매출 ÷ 광고비 × 100(합친 값으로 계산 — 틱톡의 ROAS 칸은 더할 수 없다).
|
||||
공식 문서가 스크립트 화면이라 지표 이름을 이차 자료로 확인했다 — 연결 테스트가 어제 하루를 실제로 물어 지표 이름 오류까지 잡는다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from datetime import date, timedelta
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from app.timezone import today_kst
|
||||
|
||||
from .. import fx
|
||||
from ..adapters.base import AdapterContext, ApiError, AuthFailed, CredentialField, TokenExpired
|
||||
from .base import AdDay, AdSource
|
||||
from .meta_ads import _num, _won
|
||||
|
||||
API_BASE = "https://business-api.tiktok.com/open_api/v1.3"
|
||||
MAX_DAYS = 366
|
||||
SPAN_DAYS = 30
|
||||
PAGE_SIZE = 100 # 계정 하나·30일 = 많아야 30줄이라 한 쪽이면 된다
|
||||
RATE_LIMIT = 40100
|
||||
|
||||
REPORT_METRICS = ("spend", "impressions", "clicks", "complete_payment", "total_complete_payment_rate",
|
||||
"onsite_shopping", "total_onsite_shopping_value")
|
||||
GMV_METRICS = ("cost", "gross_revenue", "orders")
|
||||
|
||||
# metrics 키 — 화면 이름 그대로 저장. 틱톡 탭은 M_REVENUE 를 매출로 읽는다(ad_spend.build_tiktok_dashboard).
|
||||
M_SPEND, M_REVENUE, M_ROAS = "광고비", "매출", "ROAS(%)"
|
||||
M_IMPR, M_CLICKS, M_ORDERS = "노출수", "클릭수", "구매수"
|
||||
M_WEB, M_SHOP, M_GMV_COST, M_GMV_REVENUE = "웹 구매금액", "틱톡샵 매출", "GMV Max 비용", "GMV Max 매출"
|
||||
|
||||
|
||||
def _http(ctx: AdapterContext) -> httpx.Client:
|
||||
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
|
||||
return httpx.Client(timeout=ctx.timeout_sec)
|
||||
|
||||
|
||||
def _spans(start: date, end: date) -> list[tuple[date, date]]:
|
||||
"""기간을 SPAN_DAYS 일씩 나눈다."""
|
||||
out = []
|
||||
while start <= end:
|
||||
stop = min(start + timedelta(days=SPAN_DAYS - 1), end)
|
||||
out.append((start, stop))
|
||||
start = stop + timedelta(days=1)
|
||||
return out
|
||||
|
||||
|
||||
class TiktokAdsSource(AdSource):
|
||||
code = "tiktok"
|
||||
name = "틱톡"
|
||||
docs_url = "https://business-api.tiktok.com/portal/docs"
|
||||
note = ("TikTok API for Business 로 날짜별 광고비·매출·ROAS 를 가져와 틱톡 탭에 보여 줍니다(매출 실적·광고비 탭 합계에는 들어가지 않음). "
|
||||
"준비: 개발자 앱에서 광고 계정을 승인해 장기 액세스 토큰 발급(보고서·광고 계정 읽기 권한). 외화 계정은 그날 환율로 원화로 바꿉니다.")
|
||||
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
return [
|
||||
CredentialField("advertiser_id", "광고 계정 ID", placeholder="7123456789012345678",
|
||||
help="틱톡 광고 관리자 주소의 aadvid= 뒤 숫자."),
|
||||
CredentialField("access_token", "액세스 토큰", secret=True,
|
||||
help="광고 계정을 승인할 때 받은 장기 액세스 토큰. 저장 후에는 화면에 다시 보이지 않습니다."),
|
||||
CredentialField("shop_id", "틱톡샵 ID", required=False, placeholder="GMV Max 캠페인을 쓸 때만",
|
||||
help="GMV Max 캠페인은 일반 보고서와 따로 조회합니다 — 넣으면 그 비용·매출도 더합니다. 안 쓰면 비워 둡니다."),
|
||||
]
|
||||
|
||||
def validate_credentials(self, values: dict[str, str]) -> list[str]:
|
||||
errors = super().validate_credentials(values)
|
||||
advertiser = (values.get("advertiser_id") or "").strip()
|
||||
if advertiser and advertiser != "__stored__" and not re.fullmatch(r"\d{5,30}", advertiser):
|
||||
errors.append("광고 계정 ID 는 숫자여야 합니다.")
|
||||
shop = (values.get("shop_id") or "").strip()
|
||||
if shop and shop != "__stored__" and not re.fullmatch(r"\d{5,30}", shop):
|
||||
errors.append("틱톡샵 ID 는 숫자여야 합니다.")
|
||||
token = (values.get("access_token") or "").strip()
|
||||
if token and token != "__stored__" and (len(token) < 20 or re.search(r"\s", token)):
|
||||
errors.append("액세스 토큰 형식이 아닙니다(공백 없이 통째로 붙여 넣으세요).")
|
||||
return errors
|
||||
|
||||
def _get(self, ctx: AdapterContext, client: httpx.Client, path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||
"""틱톡은 오류도 HTTP 200 + code 로 준다. 토큰은 머리글로만 보내 주소·오류 문구에 들어가지 않는다."""
|
||||
ctx.progress.check()
|
||||
token = (ctx.credentials.get("access_token") or "").strip()
|
||||
try:
|
||||
resp = client.get(API_BASE + path, params=params, headers={"Access-Token": token})
|
||||
except httpx.HTTPError as exc:
|
||||
raise ApiError(f"틱톡 API 에 연결하지 못했습니다({type(exc).__name__}).") from None
|
||||
try:
|
||||
body = resp.json()
|
||||
except ValueError:
|
||||
raise ApiError(f"틱톡 API 응답을 읽을 수 없습니다(HTTP {resp.status_code}).") from None
|
||||
code = body.get("code") if isinstance(body, dict) else None
|
||||
if resp.status_code == 200 and code == 0:
|
||||
return body.get("data") or {}
|
||||
text = f"틱톡 API 오류({code if code is not None else resp.status_code}): {str((body or {}).get('message') or '')[:200]}"
|
||||
if code == 40102:
|
||||
raise TokenExpired(text + " — 액세스 토큰을 다시 발급해 넣으세요.")
|
||||
if code == RATE_LIMIT:
|
||||
raise ApiError(text + " — 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.")
|
||||
if resp.status_code in (401, 403) or (isinstance(code, int) and 40100 < code < 40200):
|
||||
raise AuthFailed(text + " — 토큰과 광고 계정 ID, 앱 권한을 확인하세요.")
|
||||
raise ApiError(text)
|
||||
|
||||
def _info(self, ctx: AdapterContext, client: httpx.Client) -> dict[str, Any]:
|
||||
advertiser = (ctx.credentials.get("advertiser_id") or "").strip()
|
||||
rows = self._get(ctx, client, "/advertiser/info/", {
|
||||
"advertiser_ids": json.dumps([advertiser]), "fields": json.dumps(["name", "currency", "timezone"])}).get("list") or []
|
||||
if not rows:
|
||||
raise AuthFailed("이 토큰으로 볼 수 없는 광고 계정입니다 — 광고 계정 ID 와 승인 여부를 확인하세요.")
|
||||
return rows[0]
|
||||
|
||||
def _rows(self, ctx: AdapterContext, client: httpx.Client, path: str, metrics: tuple[str, ...], start: date, end: date,
|
||||
**extra: Any) -> list[tuple[date, dict[str, Any]]]:
|
||||
"""보고서 하나를 30일씩 물어 (날짜, 지표) 목록으로."""
|
||||
advertiser = (ctx.credentials.get("advertiser_id") or "").strip()
|
||||
out = []
|
||||
for s, e in _spans(start, end):
|
||||
data = self._get(ctx, client, path, {
|
||||
"advertiser_id": advertiser, "dimensions": json.dumps(["advertiser_id", "stat_time_day"]), "metrics": json.dumps(metrics),
|
||||
"start_date": s.isoformat(), "end_date": e.isoformat(), "page": 1, "page_size": PAGE_SIZE, **extra})
|
||||
for r in data.get("list") or []:
|
||||
try:
|
||||
day = date.fromisoformat(str((r.get("dimensions") or {}).get("stat_time_day"))[:10])
|
||||
except ValueError:
|
||||
continue
|
||||
out.append((day, r.get("metrics") or {}))
|
||||
return out
|
||||
|
||||
def _collect(self, ctx: AdapterContext, client: httpx.Client, start: date, end: date) -> dict[date, dict[str, Decimal]]:
|
||||
"""날짜 → 항목 합(계정 통화)."""
|
||||
sums: dict[date, dict[str, Decimal]] = {}
|
||||
|
||||
def day_of(d: date) -> dict[str, Decimal]:
|
||||
return sums.setdefault(d, {k: Decimal(0) for k in ("spend", "impr", "clicks", "orders", "web", "shop", "gmv_cost", "gmv")})
|
||||
|
||||
for d, m in self._rows(ctx, client, "/report/integrated/get/", REPORT_METRICS, start, end,
|
||||
report_type="BASIC", data_level="AUCTION_ADVERTISER"):
|
||||
one = day_of(d)
|
||||
one["spend"] += _num(m.get("spend"))
|
||||
one["impr"] += _num(m.get("impressions"))
|
||||
one["clicks"] += _num(m.get("clicks"))
|
||||
one["orders"] += _num(m.get("complete_payment")) + _num(m.get("onsite_shopping"))
|
||||
one["web"] += _num(m.get("total_complete_payment_rate"))
|
||||
one["shop"] += _num(m.get("total_onsite_shopping_value"))
|
||||
shop_id = (ctx.credentials.get("shop_id") or "").strip()
|
||||
if shop_id:
|
||||
for d, m in self._rows(ctx, client, "/gmv_max/report/get/", GMV_METRICS, start, end, store_ids=json.dumps([shop_id])):
|
||||
one = day_of(d)
|
||||
one["orders"] += _num(m.get("orders"))
|
||||
one["gmv_cost"] += _num(m.get("cost"))
|
||||
one["gmv"] += _num(m.get("gross_revenue"))
|
||||
return sums
|
||||
|
||||
def test_connection(self, ctx: AdapterContext) -> str:
|
||||
self.require_configured(ctx)
|
||||
yesterday = today_kst() - timedelta(days=1)
|
||||
with _http(ctx) as client:
|
||||
info = self._info(ctx, client)
|
||||
self._collect(ctx, client, yesterday, yesterday) # 지표 이름·GMV Max 권한까지 실제로 확인
|
||||
return f"연결됨 — {info.get('name') or '광고 계정'}({info.get('currency') or '?'}·{info.get('timezone') or '?'})"
|
||||
|
||||
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
|
||||
if end < start:
|
||||
start, end = end, start
|
||||
if (end - start).days + 1 > MAX_DAYS:
|
||||
raise ApiError(f"한 번에 {MAX_DAYS}일까지 가져올 수 있습니다.")
|
||||
self.require_configured(ctx)
|
||||
with _http(ctx) as client:
|
||||
currency = str(self._info(ctx, client).get("currency") or "").upper()
|
||||
if not re.fullmatch(r"[A-Z]{3}", currency):
|
||||
raise ApiError(f"광고 계정 통화({currency[:10] or '없음'})를 알 수 없습니다.")
|
||||
sums = self._collect(ctx, client, start, end)
|
||||
try:
|
||||
rates = fx.krw_rates(client, currency, start, end) if sums else {}
|
||||
except fx.FxError as exc:
|
||||
raise ApiError(f"{currency} 광고 계정을 원화로 바꿀 환율을 가져오지 못했습니다 — {exc}") from None
|
||||
return [_day(d, sums[d], rates[d]) for d in sorted(sums)]
|
||||
|
||||
|
||||
def _day(day: date, a: dict[str, Decimal], rate: Decimal) -> AdDay:
|
||||
"""합친 값(계정 통화) → 하루치(원화). ROAS 는 비율이라 반올림 전 값으로."""
|
||||
spend = (a["spend"] + a["gmv_cost"]) * rate
|
||||
revenue = (a["web"] + a["shop"] + a["gmv"]) * rate
|
||||
roas = (revenue / spend * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if spend > 0 else None
|
||||
return AdDay(day=day, amount=_won(spend), roas=roas, metrics={
|
||||
M_SPEND: _won(spend), M_REVENUE: _won(revenue), M_ROAS: float(roas) if roas is not None else None,
|
||||
M_WEB: _won(a["web"] * rate), M_SHOP: _won(a["shop"] * rate), M_GMV_COST: _won(a["gmv_cost"] * rate), M_GMV_REVENUE: _won(a["gmv"] * rate),
|
||||
M_IMPR: int(a["impr"]), M_CLICKS: int(a["clicks"]), M_ORDERS: int(a["orders"]),
|
||||
})
|
||||
@@ -22,12 +22,13 @@ 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 .ad_sources.base import ACCOUNTS_KEY
|
||||
from .ad_sources.tiktok_ads import M_REVENUE as TIKTOK_REVENUE_KEY
|
||||
from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date
|
||||
|
||||
# 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang).
|
||||
@@ -57,6 +58,7 @@ NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널)
|
||||
NO_SALES = frozenset({"etc"}) # 매출 쇼핑몰이 없는 채널 — ROAS 를 계산하지 않고 매출 탭 광고비 줄에도 안 나온다
|
||||
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"
|
||||
TIKTOK = "tiktok" # 광고 API 채널이지만 CHANNELS 에 없다 — 틱톡 탭(build_tiktok_dashboard)에서만 보인다
|
||||
|
||||
|
||||
def roas(sales: int, spend: int) -> int | None:
|
||||
@@ -476,6 +478,85 @@ def detail_tabs(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 화면 데이터
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _period_word(period: Any, today: date) -> str:
|
||||
"""KPI 이름 앞 말 — 이번달·해당 월 등."""
|
||||
return {"day": "오늘" if period.start == today else "해당일",
|
||||
"week": "이번주" if period.start <= today <= period.end else "해당 주",
|
||||
"month": "이번달" if period.start <= today <= period.end else "해당 월",
|
||||
"year": "올해" if period.start <= today <= period.end else "해당 연도",
|
||||
"custom": "선택 기간"}[period.kind]
|
||||
|
||||
|
||||
def _period_nav(period: Any, today: date) -> dict[str, Any]:
|
||||
"""기간 이동 화살표·빠른 선택(이번달·올해만 — 2026-10-26 오늘·이번주 버튼 삭제, 매출 실적과 같게)."""
|
||||
def url(k: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
|
||||
if k == "custom":
|
||||
return f"?period=custom&from={start.isoformat()}&to={end.isoformat()}"
|
||||
return f"?period={k}&d={anchor_d.isoformat()}"
|
||||
|
||||
if period.kind == "custom":
|
||||
length = timedelta(days=period.days)
|
||||
prev_url = url("custom", start=period.start - length, end=period.start - timedelta(days=1))
|
||||
next_url = url("custom", start=period.end + timedelta(days=1), end=period.end + length)
|
||||
else:
|
||||
prev_url, next_url = url(period.kind, period.prev_anchor), url(period.kind, period.next_anchor)
|
||||
return {"prev": prev_url, "next": next_url, "quick": [
|
||||
{"label": "이번달", "url": url("month", today), "active": period.kind == "month" and period.start <= today <= period.end},
|
||||
{"label": "올해", "url": url("year", today), "active": period.kind == "year" and period.start <= today <= period.end},
|
||||
]}
|
||||
|
||||
|
||||
def build_tiktok_dashboard(store: Any, *, kind: str, anchor: date, today: date, custom_from: date | None = None,
|
||||
custom_to: date | None = None, holidays: Mapping[str, str] | None = None) -> dict[str, Any]:
|
||||
"""틱톡 탭(2026-11-05) — 광고비 탭과 같은 기간 이동·표·그래프, 열 = ROAS·광고비·매출. 광고 API 가 저장한 perf_ad_spend 만 읽는다.
|
||||
CHANNELS 에 없어 광고비 탭·매출 실적 합계에는 들어가지 않는다."""
|
||||
period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to)
|
||||
cmp_start, cmp_end, cmp_label = period.compare_range(today)
|
||||
ref = period.end if period.end < today else today if period.start <= today else period.start
|
||||
year_period = calc.resolve_period("year", ref)
|
||||
migration_needed = False
|
||||
try:
|
||||
rows = store.ad_details(TIKTOK, min(period.start, cmp_start, year_period.start), max(period.end, year_period.end))
|
||||
except AdMigrationNeeded:
|
||||
rows, migration_needed = [], True
|
||||
cells: dict[tuple[date, str], calc.Money] = {}
|
||||
for r in rows:
|
||||
d = date.fromisoformat(r["date"])
|
||||
cells[(d, "spend")] = calc.Money(gross=int(r["amount"] or 0))
|
||||
cells[(d, "sales")] = calc.Money(gross=int((r["metrics"] or {}).get(TIKTOK_REVENUE_KEY) or 0))
|
||||
|
||||
table = calc.main_table(period, ("spend", "sales"), cells, today=today, holidays=holidays)
|
||||
for row in table:
|
||||
row["roas"] = roas(row["cells"]["sales"]["gross"], row["cells"]["spend"]["gross"])
|
||||
cur = {c: calc.sum_range(cells, [c], period.start, period.end).gross for c in ("spend", "sales")}
|
||||
prev = {c: calc.sum_range(cells, [c], cmp_start, cmp_end).gross for c in ("spend", "sales")}
|
||||
word = _period_word(period, today)
|
||||
spend_y = calc.year_months(year_period.start.year, ["spend"], cells, today=today)
|
||||
sales_y = calc.year_months(year_period.start.year, ["sales"], cells, today=today)
|
||||
year_rows = [{"label": a["label"], "future": a["future"], "spend": a["gross"], "sales": b["gross"],
|
||||
"roas": None if a["future"] else roas(b["gross"], a["gross"])}
|
||||
for a, b in zip(spend_y["rows"], sales_y["rows"])]
|
||||
return {
|
||||
"nav": _period_nav(period, today),
|
||||
"period": period,
|
||||
"period_kind": period.kind,
|
||||
"today": today.isoformat(),
|
||||
"kpis": [
|
||||
{"key": "spend", "label": f"{word} 광고비", "value": cur["spend"], "primary": True,
|
||||
"delta": calc.pct_change(cur["spend"], prev["spend"]), "cmp": cmp_label, "invert": True},
|
||||
{"key": "sales", "label": f"{word} 매출", "value": cur["sales"],
|
||||
"delta": calc.pct_change(cur["sales"], prev["sales"]), "cmp": cmp_label},
|
||||
{"key": "roas", "label": f"{word} ROAS", "pct": roas(cur["sales"], cur["spend"])},
|
||||
],
|
||||
"table": table,
|
||||
"chart_sales": calc.daily_series(period, ["sales"], cells),
|
||||
"chart_spend": calc.daily_series(period, ["spend"], cells),
|
||||
"year": {"year": year_period.start.year, "rows": year_rows, "spend": spend_y["total"]["gross"], "sales": sales_y["total"]["gross"],
|
||||
"roas": roas(sales_y["total"]["gross"], spend_y["total"]["gross"])},
|
||||
"migration_needed": migration_needed,
|
||||
}
|
||||
|
||||
|
||||
def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
custom_from: date | None = None, custom_to: date | None = None,
|
||||
holidays: Mapping[str, str] | None = None,
|
||||
@@ -522,11 +603,7 @@ 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},
|
||||
@@ -536,25 +613,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
"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)
|
||||
|
||||
@@ -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)
|
||||
@@ -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})
|
||||
|
||||
|
||||
@@ -241,8 +243,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 +267,33 @@ 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)
|
||||
|
||||
|
||||
@router.get("/tiktok", response_class=HTMLResponse)
|
||||
def tiktok_page(
|
||||
request: Request,
|
||||
period: str = "month",
|
||||
d: str | None = None,
|
||||
from_: str | None = Query(None, alias="from"),
|
||||
to: str | None = None,
|
||||
):
|
||||
"""틱톡 탭(2026-11-05) — 일자별 ROAS·광고비·매출(광고 API 값, 읽기 전용). 설정 = 실적 설정 → 광고 API 연동."""
|
||||
from app.main import render_template # noqa: WPS433
|
||||
|
||||
g = common.guard(request)
|
||||
if not isinstance(g, tuple):
|
||||
return g
|
||||
store, user = g
|
||||
from .ad_spend import build_tiktok_dashboard # noqa: WPS433
|
||||
|
||||
today = today_kst()
|
||||
ctx = build_tiktok_dashboard(store, kind=period, anchor=_parse_date(d) or today, today=today,
|
||||
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays())
|
||||
_ad_update_ctx(store, user, ctx)
|
||||
ctx["tiktok_configured"] = any(s["code"] == "tiktok" for s in ctx["ad_sync_sources"])
|
||||
_colw_ctx(request, ctx)
|
||||
return render_template(request, "performance/ads.html",
|
||||
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
|
||||
return render_template(request, "performance/tiktok.html",
|
||||
{**common.base_ctx(user, active_tab="tiktok", page_title="틱톡"), **ctx})
|
||||
|
||||
|
||||
@router.get("/settings", response_class=HTMLResponse)
|
||||
@@ -984,6 +1018,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,4 +1,4 @@
|
||||
{# 실적 모듈 탭 — [매출 실적] [광고비] 큰 탭 둘(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
|
||||
{# 실적 모듈 탭 — [매출 실적] [광고비] [틱톡] 큰 탭(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
|
||||
설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<nav class="perf-tabs" aria-label="실적 메뉴">
|
||||
@@ -9,6 +9,9 @@
|
||||
<a class="perf-tab perf-tab-ads{% if active_tab == 'ads' %} is-active{% endif %}" href="/performance/ads"
|
||||
role="tab" aria-selected="{{ 'true' if active_tab == 'ads' else 'false' }}">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>광고비</a>
|
||||
<a class="perf-tab perf-tab-tiktok{% if active_tab == 'tiktok' %} is-active{% endif %}" href="/performance/tiktok"
|
||||
role="tab" aria-selected="{{ 'true' if active_tab == 'tiktok' else 'false' }}">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">music_note</span>틱톡</a>
|
||||
</div>
|
||||
<a class="perf-tab-gear{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings"
|
||||
title="{{ '실적 설정' if is_admin else '수수료 설정' }}" aria-label="{{ '실적 설정' if is_admin else '수수료 설정' }}">
|
||||
|
||||
@@ -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=20261105a" />{% endblock %}
|
||||
|
||||
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
|
||||
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
@@ -237,4 +223,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261105a" 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=20261105a" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
@@ -134,7 +134,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>
|
||||
@@ -294,4 +294,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261105a" 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=20261105a" />{% endblock %}
|
||||
|
||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||
|
||||
@@ -255,7 +255,7 @@
|
||||
<div class="erp-card perf-card" id="perf-ad-sources">
|
||||
<div class="perf-card-head">
|
||||
<h2 class="perf-h">광고 API 연동</h2>
|
||||
<span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
|
||||
<span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 틱톡은 틱톡 탭에서만 보입니다(매출 실적·광고비 탭 합계 제외). 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
|
||||
설정이 끝나면 광고비 탭 [광고비 업데이트]와 광고비 자동 업데이트(위 "자동 업데이트" 일정) 때 가져옵니다.</span>
|
||||
</div>
|
||||
{% if not ad_api_ready %}
|
||||
@@ -347,4 +347,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261105a" defer></script>{% endblock %}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
{%- elif v == 0 -%}<span class="perf-zero">–</span>
|
||||
{%- else -%}{{ "{:,}".format(v) }}{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
{%- macro pct(p) -%}{%- if p is none -%}<span class="perf-zero">–</span>{%- else -%}{{ "{:,}".format(p) }}%{%- endif -%}{%- endmacro -%}
|
||||
|
||||
{% block content %}
|
||||
{#- 틱톡(2026-11-05) — 광고비 탭과 같은 기간 이동·표·그래프. 값은 광고 API 만(읽기 전용, 직접 입력 없음). 매출 실적·광고비 탭 합계에는 안 들어간다. -#}
|
||||
<section class="perf perf-ads perf-tiktok" id="perf-dash" data-metric="gross" data-fixed-metric="gross">
|
||||
{% include "performance/_tabs.html" %}
|
||||
|
||||
<div class="perf-toolbar">
|
||||
<div class="perf-quick" role="group" aria-label="기간 선택">
|
||||
{% for q in nav.quick %}
|
||||
<a class="perf-seg{% if q.active %} is-active{% endif %}" href="{{ q.url }}">{{ q.label }}</a>
|
||||
{% endfor %}
|
||||
<button type="button" class="perf-seg{% if period_kind == 'custom' %} is-active{% endif %}" id="perf-custom-btn">직접선택</button>
|
||||
</div>
|
||||
|
||||
{% include "performance/_period_nav.html" %}
|
||||
|
||||
<form class="perf-custom" id="perf-custom" method="get" action="/performance/tiktok"{% if period_kind != 'custom' %} hidden{% endif %}>
|
||||
<input type="hidden" name="period" value="custom" />
|
||||
<input class="erp-input perf-date" type="date" name="from" value="{{ period.start.isoformat() }}" required />
|
||||
<span class="perf-muted">~</span>
|
||||
<input class="erp-input perf-date" type="date" name="to" value="{{ period.end.isoformat() }}" required />
|
||||
<button class="erp-btn erp-btn-outline" type="submit">조회</button>
|
||||
</form>
|
||||
|
||||
{% include "performance/_ad_update.html" %}
|
||||
</div>
|
||||
<div class="perf-notice" id="perf-sync-result" hidden></div>
|
||||
|
||||
{% if migration_needed %}
|
||||
<div class="perf-notice is-warn">광고비 저장 표가 아직 없습니다. 관리자가 performance_db 마이그레이션 005·006 을 적용해야 합니다.</div>
|
||||
{% endif %}
|
||||
{% if not tiktok_configured %}
|
||||
<div class="perf-notice is-warn">틱톡 API 가 아직 설정되지 않았습니다. {% if is_admin %}<a href="/performance/settings#perf-ad-sources">실적 설정 → 광고 API 연동</a>에서{% else %}관리자가 실적 설정 → 광고 API 연동에서{% endif %} 틱톡 [설정]을 입력하면 데이터가 들어옵니다.</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="perf-kpi-line">
|
||||
{% for k in kpis %}
|
||||
<span class="perf-kpi-item">
|
||||
<span class="perf-muted">{{ k.label }}</span>
|
||||
{% if k.key == 'roas' %}
|
||||
<b class="perf-kpi-line-value is-sub">{{ pct(k.pct) }}</b>
|
||||
{% else %}
|
||||
<b class="perf-kpi-line-value{% if not k.primary %} is-sub{% endif %}">₩{{ "{:,}".format(k.value) }}</b>
|
||||
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
|
||||
{% else %}
|
||||
{% set up = k.delta > 0 %}
|
||||
<span class="perf-delta {% if k.delta == 0 %}is-flat{% elif up != (k.invert or false) %}is-up{% else %}is-down{% endif %}">
|
||||
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
|
||||
<span class="perf-muted">{{ k.cmp }} 대비</span>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</span>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head">
|
||||
<h2 class="perf-h">{% if period_kind == 'year' %}월별 틱톡 실적{% else %}일자별 틱톡 실적{% endif %}</h2>
|
||||
</div>
|
||||
<div class="erp-table-wrap perf-table-wrap perf-main-wrap">
|
||||
<table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="tiktok">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||
<th data-col="roas">ROAS</th>
|
||||
<th data-col="spend">광고비</th>
|
||||
<th data-col="sales">매출</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for r in table %}
|
||||
<tr class="perf-row-{{ r.kind }}{% if r.weekday == 5 %} is-sat{% endif %}{% if r.weekday == 6 or r.holiday %} is-sun{% endif %}{% if r.today %} is-today{% endif %}{% if r.future %} is-future{% endif %}">
|
||||
<th class="perf-td-label" scope="row">
|
||||
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
|
||||
</th>
|
||||
<td class="perf-num">{{ pct(r.roas) }}</td>
|
||||
<td class="perf-num"><span class="v v-gross">{{ won(r.cells.spend.gross) }}</span></td>
|
||||
<td class="perf-num"><span class="v v-gross">{{ won(r.cells.sales.gross) }}</span></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="perf-grid2">
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 매출 추이</h2></div>
|
||||
<div class="perf-chart" id="perf-chart-daily"></div>
|
||||
</div>
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 광고비 추이</h2></div>
|
||||
<div class="perf-chart" id="perf-chart-daily2"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적</h2></div>
|
||||
<div class="erp-table-wrap">
|
||||
<table class="perf-table perf-year">
|
||||
<thead><tr><th class="perf-th-label">월</th><th>ROAS</th><th>광고비</th><th>매출</th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in year.rows %}
|
||||
<tr class="{% if r.future %}is-future{% endif %}">
|
||||
<th class="perf-td-label" scope="row">{{ r.label }}</th>
|
||||
<td class="perf-num">{% if not r.future %}{{ pct(r.roas) }}{% endif %}</td>
|
||||
<td class="perf-num">{{ won(r.spend) }}</td>
|
||||
<td class="perf-num">{{ won(r.sales) }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr class="perf-row-total">
|
||||
<th class="perf-td-label" scope="row">합계</th>
|
||||
<td class="perf-num">{{ pct(year.roas) }}</td>
|
||||
<td class="perf-num">{{ won(year.spend) }}</td>
|
||||
<td class="perf-num">{{ won(year.sales) }}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="perf-foot perf-muted">
|
||||
틱톡 광고 API 값입니다. 매출 = 광고에 귀속된 구매금액(웹 구매 + 틱톡샵, 틱톡샵 ID 를 넣으면 GMV Max 포함)이며 틱톡샵 전체 판매액과는 다를 수 있습니다.
|
||||
ROAS = 매출 ÷ 광고비 × 100, 외화 계정은 그날 환율로 원화로 바꿉니다. 이 값은 매출 실적·광고비 탭 합계에 들어가지 않습니다.
|
||||
[광고비 업데이트]는 설정된 광고 API 전부를 함께 가져옵니다.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<script type="application/json" id="perf-data">{{ {
|
||||
"period_kind": period_kind,
|
||||
"today": today,
|
||||
"period_start": period.start.isoformat(),
|
||||
"period_end": period.end.isoformat(),
|
||||
"period_label": period.label,
|
||||
"daily": chart_sales,
|
||||
"daily2": chart_spend,
|
||||
"empty_text": "기간 내 틱톡 데이터가 없습니다.",
|
||||
"auto_sync": auto_sync,
|
||||
"update_watch": update_watch
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261105a" defer></script>{% endblock %}
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
"""틱톡 탭(2026-11-05) — 입력 검사·요청 매개변수·30일 나누기·매출 합산·환율·오류 안내·화면 데이터·다른 탭과 분리.
|
||||
틱톡 서버는 가짜(httpx MockTransport)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app.modules.performance import ad_spend, fx
|
||||
from app.modules.performance.ad_sources import tiktok_ads as tt
|
||||
from app.modules.performance.ad_sources.registry import get_source
|
||||
from app.modules.performance.adapters.base import AdapterContext, ApiError, AuthFailed, TokenExpired
|
||||
|
||||
TOKEN = "tiktoktoken0123456789abcdefSECRET"
|
||||
|
||||
|
||||
class Creds:
|
||||
def __init__(self, values):
|
||||
self.values = values
|
||||
|
||||
def get(self, key):
|
||||
return self.values.get(key, "")
|
||||
|
||||
def has(self, key):
|
||||
return bool(self.values.get(key))
|
||||
|
||||
|
||||
def ctx(**extra):
|
||||
return AdapterContext(code="tiktok", credentials=Creds({"advertiser_id": "71234567", "access_token": TOKEN, **extra}), timeout_sec=5.0)
|
||||
|
||||
|
||||
def server(monkeypatch, *, currency="KRW", report=None, gmv=None, seen=None):
|
||||
"""가짜 틱톡 + 환율 서버. seen 에 (경로, 쿼리, 머리글)을 쌓는다."""
|
||||
def handler(req: httpx.Request) -> httpx.Response:
|
||||
url = urlparse(str(req.url))
|
||||
q = {k: v[0] for k, v in parse_qs(url.query).items()}
|
||||
if seen is not None:
|
||||
seen.append((url.path, q, req.headers.get("access-token")))
|
||||
if "business-api.tiktok.com" not in str(req.url):
|
||||
return httpx.Response(200, json=[{"date": "2026-10-05", "base": "MYR", "quote": "KRW", "rate": 300}])
|
||||
if url.path.endswith("/advertiser/info/"):
|
||||
return httpx.Response(200, json={"code": 0, "data": {"list": [{"name": "DBX", "currency": currency, "timezone": "Asia/Seoul"}]}})
|
||||
rows = gmv if url.path.endswith("/gmv_max/report/get/") else report
|
||||
if isinstance(rows, httpx.Response):
|
||||
return rows
|
||||
return httpx.Response(200, json={"code": 0, "data": {"list": [
|
||||
{"dimensions": {"stat_time_day": f"{d} 00:00:00"}, "metrics": m} for d, m in (rows or {}).items()]}})
|
||||
monkeypatch.setattr(tt, "_http", lambda c: httpx.Client(transport=httpx.MockTransport(handler)))
|
||||
|
||||
|
||||
def test_registered_but_not_a_channel():
|
||||
"""틱톡은 광고 연동에는 있지만 광고비 탭 채널이 아니다(틱톡 탭에서만 보임)."""
|
||||
assert get_source("tiktok").name == "틱톡"
|
||||
assert "tiktok" not in ad_spend.CHANNEL_CODES
|
||||
|
||||
|
||||
@pytest.mark.parametrize("values,word", [
|
||||
({"advertiser_id": "abc", "access_token": TOKEN}, "광고 계정 ID"),
|
||||
({"advertiser_id": "71234567", "access_token": "short"}, "액세스 토큰"),
|
||||
({"advertiser_id": "71234567", "access_token": TOKEN, "shop_id": "x1"}, "틱톡샵 ID"),
|
||||
])
|
||||
def test_validation(values, word):
|
||||
assert any(word in e for e in tt.TiktokAdsSource().validate_credentials(values))
|
||||
|
||||
|
||||
def test_stored_values_pass_validation():
|
||||
assert tt.TiktokAdsSource().validate_credentials({"advertiser_id": "71234567", "access_token": "__stored__"}) == []
|
||||
|
||||
|
||||
def test_fetch_sums_revenue_and_splits_30_days(monkeypatch):
|
||||
seen = []
|
||||
server(monkeypatch, seen=seen, report={"2026-10-05": {
|
||||
"spend": "1000", "impressions": "50", "clicks": "5", "complete_payment": "1", "onsite_shopping": "2",
|
||||
"total_complete_payment_rate": "2000", "total_onsite_shopping_value": "1000.4"}})
|
||||
days = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 9, 1), date(2026, 11, 3))
|
||||
reports = [q for path, q, _ in seen if path.endswith("/report/integrated/get/")]
|
||||
assert [(q["start_date"], q["end_date"]) for q in reports] == [
|
||||
("2026-09-01", "2026-09-30"), ("2026-10-01", "2026-10-30"), ("2026-10-31", "2026-11-03")]
|
||||
assert reports[0]["data_level"] == "AUCTION_ADVERTISER" and "stat_time_day" in json.loads(reports[0]["dimensions"])
|
||||
assert not [p for p, _, _ in seen if p.endswith("/gmv_max/report/get/")] # 틱톡샵 ID 없으면 안 물음
|
||||
assert all(h == TOKEN for _, _, h in seen) and not any(TOKEN in json.dumps(q) for _, q, _ in seen) # 토큰은 머리글로만
|
||||
# 같은 날 응답이 쪽마다 오므로 3번 더해진다 — 가짜 서버가 기간과 무관하게 같은 줄을 주는 탓, 합산 동작 자체를 확인
|
||||
d = days[0]
|
||||
assert d.day == date(2026, 10, 5) and d.amount == 3000 and d.metrics[tt.M_REVENUE] == 9001
|
||||
assert d.roas == Decimal("300.04") and d.metrics[tt.M_ORDERS] == 9
|
||||
|
||||
|
||||
def test_gmv_max_added_only_with_shop_id(monkeypatch):
|
||||
seen = []
|
||||
server(monkeypatch, seen=seen, report={"2026-10-05": {"spend": "100", "total_onsite_shopping_value": "100"}},
|
||||
gmv={"2026-10-05": {"cost": "100", "gross_revenue": "500", "orders": "3"}})
|
||||
d = tt.TiktokAdsSource().fetch_days(ctx(shop_id="7555"), date(2026, 10, 5), date(2026, 10, 5))[0]
|
||||
assert d.amount == 200 and d.metrics[tt.M_REVENUE] == 600 and d.roas == Decimal("300.00")
|
||||
assert d.metrics[tt.M_GMV_REVENUE] == 500 and d.metrics[tt.M_GMV_COST] == 100 # 대조용으로 따로 남김
|
||||
gmv_q = next(q for p, q, _ in seen if p.endswith("/gmv_max/report/get/"))
|
||||
assert json.loads(gmv_q["store_ids"]) == ["7555"]
|
||||
|
||||
|
||||
def test_foreign_currency_uses_that_day_rate(monkeypatch):
|
||||
fx.clear_cache()
|
||||
server(monkeypatch, currency="MYR", report={"2026-10-05": {"spend": "10", "total_onsite_shopping_value": "40"}})
|
||||
d = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))[0]
|
||||
assert d.amount == 3000 and d.metrics[tt.M_REVENUE] == 12000 and d.roas == Decimal("400.00")
|
||||
fx.clear_cache()
|
||||
|
||||
|
||||
def test_no_spend_means_no_roas(monkeypatch):
|
||||
server(monkeypatch, report={"2026-10-05": {"spend": "0", "total_onsite_shopping_value": "40"}})
|
||||
d = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))[0]
|
||||
assert d.roas is None and d.metrics[tt.M_ROAS] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code,exc", [(40102, TokenExpired), (40105, AuthFailed), (40100, ApiError), (40002, ApiError)])
|
||||
def test_error_codes(monkeypatch, code, exc):
|
||||
server(monkeypatch, report=httpx.Response(200, json={"code": code, "message": "bad"}))
|
||||
with pytest.raises(exc) as got:
|
||||
tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))
|
||||
assert str(code) in str(got.value) and TOKEN not in str(got.value)
|
||||
|
||||
|
||||
def test_connection_also_asks_report(monkeypatch):
|
||||
"""연결 테스트가 보고서까지 물어야 지표 이름 오류를 저장 전에 잡는다."""
|
||||
seen = []
|
||||
server(monkeypatch, seen=seen)
|
||||
msg = tt.TiktokAdsSource().test_connection(ctx())
|
||||
assert "DBX" in msg and "KRW" in msg
|
||||
assert any(p.endswith("/report/integrated/get/") for p, _, _ in seen)
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, rows=None, missing=False):
|
||||
self.rows, self.missing = rows or [], missing
|
||||
|
||||
def ad_details(self, code, start, end):
|
||||
assert code == "tiktok"
|
||||
if self.missing:
|
||||
raise ad_spend.AdMigrationNeeded("005")
|
||||
return [r for r in self.rows if start.isoformat() <= r["date"] <= end.isoformat()]
|
||||
|
||||
|
||||
def row(day, spend, sales):
|
||||
return {"date": day, "amount": spend, "roas": None, "metrics": {tt.M_REVENUE: sales}, "source": "api"}
|
||||
|
||||
|
||||
def test_dashboard_table_and_kpis():
|
||||
store = Store([row("2026-10-05", 1000, 3000), row("2026-10-06", 1000, 1000), row("2026-09-05", 500, 500)])
|
||||
ctx_ = ad_spend.build_tiktok_dashboard(store, kind="month", anchor=date(2026, 10, 15), today=date(2026, 10, 31),
|
||||
holidays={"2026-10-09": "한글날"})
|
||||
total = ctx_["table"][0]
|
||||
assert total["kind"] == "total" and total["cells"]["spend"]["gross"] == 2000 and total["cells"]["sales"]["gross"] == 4000 and total["roas"] == 200
|
||||
day = next(r for r in ctx_["table"] if r.get("date") == "2026-10-05")
|
||||
assert day["roas"] == 300
|
||||
assert next(r for r in ctx_["table"] if r.get("date") == "2026-10-09")["holiday"] == "한글날"
|
||||
kpi = {k["key"]: k for k in ctx_["kpis"]}
|
||||
assert kpi["spend"]["value"] == 2000 and kpi["sales"]["value"] == 4000 and kpi["roas"]["pct"] == 200
|
||||
assert kpi["spend"]["delta"] == 300.0 and kpi["sales"]["delta"] == 700.0
|
||||
assert ctx_["year"]["spend"] == 2500 and ctx_["year"]["sales"] == 4500 and ctx_["year"]["rows"][9]["roas"] == 200
|
||||
assert ctx_["year"]["rows"][10]["future"] is True and ctx_["year"]["rows"][10]["roas"] is None
|
||||
assert sum(p["gross"] for p in ctx_["chart_sales"]) == 4000 and sum(p["gross"] for p in ctx_["chart_spend"]) == 2000
|
||||
|
||||
|
||||
def test_dashboard_without_table_or_data():
|
||||
got = ad_spend.build_tiktok_dashboard(Store(missing=True), kind="month", anchor=date(2026, 10, 1), today=date(2026, 10, 31))
|
||||
assert got["migration_needed"] is True and got["table"][0]["roas"] is None
|
||||
assert {k["key"]: k for k in got["kpis"]}["roas"]["pct"] is None
|
||||
|
||||
|
||||
def test_ads_tab_ignores_tiktok_rows():
|
||||
"""perf_ad_spend 에 틱톡 줄이 있어도 광고비 탭 합계에 안 들어간다."""
|
||||
class AdStore:
|
||||
def ad_amounts(self, start, end):
|
||||
return {(date(2026, 10, 5), "google"): 100, (date(2026, 10, 5), "tiktok"): 9000}, {}
|
||||
|
||||
def daily_amounts(self, start, end, codes):
|
||||
return {}
|
||||
|
||||
got = ad_spend.build_ad_dashboard(AdStore(), kind="month", anchor=date(2026, 10, 1), today=date(2026, 10, 31))
|
||||
assert got["table"][0]["total"]["gross"] == 100 and "tiktok" not in got["codes"]
|
||||
assert {k["key"]: k for k in got["kpis"]}["spend"]["value"] == 100
|
||||
|
||||
|
||||
def test_page_renders_after_ads_tab(monkeypatch):
|
||||
"""진짜 라우터·템플릿 — 탭 순서, 열 순서, 값, 미설정 안내, 칸 입력 없음."""
|
||||
import importlib
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.modules.performance import common
|
||||
|
||||
perf_router = importlib.import_module("app.modules.performance.router") # 패키지의 router 는 APIRouter 객체
|
||||
store = Store([row("2026-10-05", 1000, 3000)])
|
||||
user = {"email": "a@x", "name": "A", "role": "user"}
|
||||
|
||||
class Sync:
|
||||
def configured(self):
|
||||
return {"google": True, "tiktok": False}
|
||||
|
||||
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, user))
|
||||
monkeypatch.setattr(perf_router, "_ad_services", lambda st: (None, Sync()))
|
||||
monkeypatch.setattr(perf_router, "_auto_sync_ctx", lambda st, kind: None)
|
||||
monkeypatch.setattr(perf_router, "today_kst", lambda: date(2026, 10, 31))
|
||||
app = FastAPI()
|
||||
app.include_router(perf_router.router)
|
||||
html = TestClient(app).get("/performance/tiktok").text
|
||||
tabs = html.split('class="perf-tabs-main"', 1)[1]
|
||||
assert tabs.index("광고비</a>") < tabs.index("틱톡</a>") and "perf-tab-tiktok is-active" in tabs
|
||||
head = html.split("<thead>", 1)[1].split("</thead>", 1)[0]
|
||||
assert head.index("ROAS") < head.index("광고비") < head.index("매출")
|
||||
assert "3,000" in html and "300%" in html
|
||||
assert "틱톡 API 가 아직 설정되지 않았습니다" in html and "data-manual-code" not in html
|
||||
@@ -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 %}
|
||||
|
||||
@@ -7,9 +7,9 @@
|
||||
옵션이 없는 상품: 행을 자유롭게 추가/삭제해 두고 저장하면 옵션 생성(POST options,
|
||||
카페24가 품목을 자동 생성) → 부여된 품목코드를 받아 → 자체코드/추가금액을 품목에
|
||||
PUT → 썸네일이 있으면 옵션 PUT. 저장 뒤 다시 읽어 품목코드가 바로 보인다.
|
||||
품목 추가: 「+ 행 추가」로 넣은 행은 저장 시 옵션값을 **뒤에 덧붙여** PUT 한다
|
||||
(앞쪽 위치는 그대로라 기존 이름이 밀리지 않는다). 카페24가 품목을 자동 생성하면
|
||||
그 코드로 자체코드/추가금액을 이어서 PUT 한다. 거부하면 오류를 그대로 보여준다.
|
||||
품목 추가: 카페24 PUT options 는 옵션값 추가를 지원하지 않는다(덧붙여 보내면 오류 없이
|
||||
무시되어 저장 후 사라졌다 — 2026-11-06). 「+ 행 추가」·불러오기로 넣은 새 행이 있으면
|
||||
「저장」이 확인창을 거쳐 「옵션 재생성」으로 반영한다(품목코드 새로 부여).
|
||||
품목 삭제: 행의 ✕ → DELETE /variants/{code} (문서에 있는 유일한 제거 수단). 옵션값
|
||||
자체는 남을 수 있어(품목 없는 옵션값) 하단에 따로 보여주고, 정리는 「옵션 재생성」
|
||||
(전체 삭제 → 현재 행으로 다시 생성 → 코드/금액/썸네일 재반영, 품목코드가 바뀜)으로.
|
||||
@@ -246,7 +246,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 +257,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 +309,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')) 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,6 +422,7 @@
|
||||
: '<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>" +
|
||||
'<td class="cf24-u-del">' + (awaiting ? "" : '<button type="button" class="cf24-u-remove" title="' + (isNewRow ? "행 삭제" : "품목 삭제 (카페24에 바로 반영)") + '">✕</button>') + "</td>" +
|
||||
@@ -396,14 +441,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><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 +463,7 @@
|
||||
html += '<p class="cf24-side-note cf24-u-note">' +
|
||||
(isNew
|
||||
? "저장하면 옵션(조합형)을 만들고 카페24가 품목을 자동 생성합니다. 부여된 품목코드를 받아 자체 품목코드·추가금액·썸네일까지 함께 반영합니다."
|
||||
: "「+ 행 추가」한 값은 저장 시 옵션값 끝에 덧붙여 품목을 만듭니다. ✕ 는 품목을 바로 삭제합니다. " +
|
||||
: "「+ 행 추가」한 값은 카페24 API 가 옵션값 추가를 지원하지 않아 저장 시 「옵션 재생성」으로 반영합니다(품목코드 새로 부여). ✕ 는 품목을 바로 삭제합니다. " +
|
||||
(canDrag ? "행을 드래그하면 품목 진열순서로 저장됩니다. " : "") +
|
||||
"썸네일은 표시방식이 「미리보기(이미지)」일 때 쇼핑몰에 보입니다.") +
|
||||
"</p>" +
|
||||
@@ -433,6 +479,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 +493,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 +503,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);
|
||||
@@ -780,6 +826,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 +855,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,7 +865,7 @@
|
||||
if (!optionsChanged && !patches.length) { setMsg(msg, "바뀐 값이 없습니다.", ""); return; }
|
||||
|
||||
var lines = [];
|
||||
if (optionsChanged) lines.push("옵션명·옵션값 이름/썸네일/표시방식" + (newRows.length ? " (+ 옵션값 " + newRows.length + "개 추가 → 품목 생성)" : ""));
|
||||
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;
|
||||
@@ -833,18 +880,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 +888,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 +970,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 +979,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 +1013,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><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,6 +1022,7 @@
|
||||
'<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>" +
|
||||
'<td class="cf24-u-del"><button type="button" class="cf24-u-remove" data-code="' + esc(v.variant_code) + '" title="품목 삭제 (카페24에 바로 반영)">✕</button></td></tr>';
|
||||
});
|
||||
@@ -999,6 +1040,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); });
|
||||
|
||||
+28
-3
@@ -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; }
|
||||
@@ -746,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-*) 폭을
|
||||
@@ -855,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).
|
||||
@@ -865,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;
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
+12
-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; }
|
||||
@@ -346,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 그대로)이라 커지면 글자·칸이 같은 비율로 커진다. */
|
||||
|
||||
@@ -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");
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.7 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.1 KiB |
+105
-33
@@ -1,5 +1,6 @@
|
||||
/* 라이브 커머스(2026-11-04) — 스케줄표·호스트 설정 */
|
||||
.erp-page:has(> .lv) { box-sizing: border-box; } /* 공용 .erp-page 는 폭 100% + 안쪽 여백이라 그대로면 화면보다 넓어진다 */
|
||||
/* 공용 .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; }
|
||||
@@ -13,6 +14,10 @@
|
||||
.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); }
|
||||
@@ -23,7 +28,7 @@
|
||||
/* 공용 .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 { 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; }
|
||||
@@ -35,59 +40,116 @@
|
||||
|
||||
/* ── 달력 보기 ── */
|
||||
.lv-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; }
|
||||
.lv-kpi { display: flex; flex-direction: column; gap: 2px; padding: 10px 14px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 10px; background: #fff; }
|
||||
.lv-kpi span { font-size: 11px; font-weight: 600; letter-spacing: .04em; color: var(--color-midtone-gray, #666); }
|
||||
.lv-kpi b { font-size: 18px; font-variant-numeric: tabular-nums; }
|
||||
.lv-jump { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; padding: 8px 12px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 10px; background: #fff; }
|
||||
.lv-jump-label { margin-right: 4px; font-size: 13px; font-weight: 600; color: #4b5563; }
|
||||
.lv-jump-day { min-width: 28px; height: 28px; padding: 0 4px; border: 1px solid transparent; border-radius: 6px; background: #f1f3f6; color: #1f2937; font-size: 13px; font-weight: 600; cursor: pointer; }
|
||||
.lv-jump-day:hover { background: #e2e6ec; }
|
||||
.lv-jump-day.is-weekend { background: #fff6dc; border-color: #f3e2ae; color: #8a4b08; }
|
||||
.lv-jump-day.is-today { outline: 2px solid #111; outline-offset: -2px; }
|
||||
.lv-tip { margin: 0; padding: 8px 12px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 10px; background: #f6f8fb; font-size: 13px; color: #374151; }
|
||||
.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; padding: 8px 6px; background: #e4e8ee; text-align: center; font-weight: 700; }
|
||||
.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: 13px; letter-spacing: .03em; }
|
||||
.lv-cal-count { display: inline-block; min-width: 18px; padding: 0 4px; margin-left: 2px; border: 1px solid #cfd4dc; border-radius: 4px; background: #fff; color: #374151; font-size: 11px; font-weight: 600; }
|
||||
.lv-cal-date { margin-top: 2px; font-size: 11px; font-weight: 600; color: #6b7280; }
|
||||
.lv-cal .lv-cal-time { position: sticky; left: 0; z-index: 1; width: 132px; min-width: 132px; padding: 8px; background: #f6f7f9; text-align: center; font-size: 13px; font-weight: 700; white-space: nowrap; }
|
||||
.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: 2px; font-size: 10.5px; font-weight: 600; color: #6b7280; }
|
||||
.lv-cell { min-height: 100px; padding: 4px; vertical-align: top; background: #fff; }
|
||||
.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%; min-height: 88px; border: 1px dashed #d8dce3; border-radius: 6px; background: transparent; color: #b0b6c0; font-size: 16px; cursor: pointer; }
|
||||
.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; }
|
||||
.lv-card { margin-bottom: 4px; border: 1.5px solid #1f2937; border-radius: 6px; background: #fff; overflow: hidden; }
|
||||
.lv-card-head { display: flex; align-items: center; gap: 4px; padding: 3px 6px; border-bottom: 1px solid #1f2937; cursor: grab; }
|
||||
/* 카드 = 합친 칸 높이 전체(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-grip { font-size: 12px; color: #374151; }
|
||||
.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: 13px; font-weight: 800; letter-spacing: .03em; color: #111; }
|
||||
.lv-card-edit { padding: 0 2px; border: 0; background: none; color: #374151; font-size: 13px; cursor: pointer; }
|
||||
.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; flex-direction: column; text-align: center; }
|
||||
.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 { padding: 2px 0; background: #f6f7f9; font-size: 10px; font-weight: 600; color: #4b5563; }
|
||||
.lv-card-nums b { padding: 3px 0; font-size: 14px; font-variant-numeric: tabular-nums; }
|
||||
.lv-card-foot { display: flex; justify-content: space-between; gap: 4px; padding: 2px 6px; border-top: 1px solid #e3e6eb; background: #f6f7f9; font-size: 10.5px; font-weight: 600; color: #4b5563; }
|
||||
.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; padding: 8px; background: #101a33; color: #fff; border-color: #2a3550; }
|
||||
.lv-cal tfoot .lv-cal-time { z-index: 3; background: #101a33; font-size: 12px; }
|
||||
.lv-total { display: flex; flex-direction: column; gap: 2px; margin: 0; font-size: 11px; font-weight: 600; }
|
||||
.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-total-edit { padding: 0 2px; border: 0; background: none; color: #cbd5e1; font-size: 11px; cursor: pointer; }
|
||||
.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; }
|
||||
@@ -96,8 +158,18 @@
|
||||
.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; }
|
||||
|
||||
+161
-23
@@ -1,9 +1,10 @@
|
||||
/* 라이브 커머스(2026-11-04) — 스케줄표·달력·호스트 설정 공용: 추가·고치기 창, 저장·지우기(fetch → JSON {ok, message}, 틀려도 입력한 값이 창에 남음).
|
||||
달력: Jump to Date, 카드 끌어 옮기기·맞바꾸기, 날짜별 광고비. 다시 그린 뒤에도 보던 가로 위치 유지. */
|
||||
달력: 오른쪽 달력으로 날짜 이동, 카드 끌어 옮기기·맞바꾸기. 다시 그린 뒤에도 보던 가로 위치 유지. */
|
||||
(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() {
|
||||
@@ -26,16 +27,17 @@
|
||||
const hostSelect = form.querySelector('select[name="host_id"]');
|
||||
const fileInput = form.querySelector('input[type="file"]');
|
||||
|
||||
function say(text) {
|
||||
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 };
|
||||
return { ok: res.ok && data.ok !== false, message: data.message || data.detail || "HTTP " + res.status, data: data };
|
||||
} catch (_) {
|
||||
return { ok: false, message: tr("서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.") };
|
||||
}
|
||||
@@ -78,18 +80,39 @@
|
||||
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) {
|
||||
@@ -109,6 +132,42 @@
|
||||
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"]');
|
||||
@@ -130,30 +189,109 @@
|
||||
const time = calWrap.querySelector("thead .lv-cal-time");
|
||||
if (col && time) calWrap.scrollLeft += col.getBoundingClientRect().left - time.getBoundingClientRect().right;
|
||||
}
|
||||
document.addEventListener("click", function (e) {
|
||||
const b = e.target.closest("[data-jump]");
|
||||
if (b) jumpTo(b.dataset.jump);
|
||||
});
|
||||
// 마지막 날들도 맨 왼쪽까지 오도록 표 끝에 여백(표 상자 너비 − 시간 열 − 날짜 열 하나)
|
||||
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 (left !== null) calWrap.scrollLeft = Number(left);
|
||||
else {
|
||||
const today = calWrap.querySelector("thead th[data-today]");
|
||||
if (today) jumpTo(today.dataset.day);
|
||||
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; });
|
||||
}
|
||||
|
||||
// ── 달력: 날짜별 광고비 ──
|
||||
document.addEventListener("click", async function (e) {
|
||||
const b = e.target.closest("button[data-spend]");
|
||||
if (!b) return;
|
||||
const value = await window.erpPrompt(tr("{day} 광고비 (RM) — 비우면 지웁니다").replace("{day}", b.dataset.spend), b.dataset.value || "", dialogText());
|
||||
if (value === null || value === undefined) return;
|
||||
const body = new FormData();
|
||||
body.set("day", b.dataset.spend);
|
||||
body.set("amount", value);
|
||||
const r = await post("/live/ad-spend", body);
|
||||
if (r.ok) reload(); else window.erpAlert(r.message, dialogText());
|
||||
});
|
||||
// ── 달력: 이미지 링크를 누르면 화면 가운데 보기 창 — 원본 크기, 회전(보기만, 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;
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
.perf-tab.is-active { color: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, .18); }
|
||||
.perf-tab-sales.is-active, .perf-tab-sales.is-active:hover { background: var(--color-deep-black, #1e1f21); }
|
||||
.perf-tab-ads.is-active, .perf-tab-ads.is-active:hover { background: var(--perf-ad, #d9480f); }
|
||||
.perf-tab-tiktok.is-active, .perf-tab-tiktok.is-active:hover { background: var(--perf-tiktok, #e11d48); }
|
||||
a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
|
||||
.perf-tab-gear {
|
||||
margin-left: auto; display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px;
|
||||
@@ -59,6 +60,10 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
|
||||
.perf-ads td.is-upload .v-gross { color: var(--perf-ad); }
|
||||
/* 광고 API(구글 광고 등)로 가져온 칸 — 초록 숫자 */
|
||||
.perf-ads td.is-api .v-gross { color: #1e8e3e; }
|
||||
/* 틱톡 화면 — 광고비 화면 틀에 색만 바꿈 */
|
||||
.perf, .perf-modal { --perf-tiktok: #e11d48; }
|
||||
.perf-tiktok .perf-quick .perf-seg.is-active { background: var(--perf-tiktok); }
|
||||
.perf-tiktok .perf-chart .bar { fill: var(--perf-tiktok); }
|
||||
.perf-ad-actions { margin-left: auto; display: inline-flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
/* 광고 API 설정 창 — 서비스 계정 JSON 같은 여러 줄 항목 */
|
||||
.perf-cred-multi { width: 100%; font-family: ui-monospace, Consolas, monospace; font-size: 12px; resize: vertical; }
|
||||
@@ -518,3 +523,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); }
|
||||
|
||||
@@ -257,6 +257,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 +272,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 +293,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,6 +347,63 @@
|
||||
};
|
||||
}
|
||||
|
||||
// 열 접기(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", "/performance/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: "수수료 차감 매출" };
|
||||
@@ -358,7 +420,8 @@
|
||||
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);
|
||||
drawDaily(m, "perf-chart-daily2", data.daily2); // 틱톡 탭 — 매출·광고비 두 그래프
|
||||
drawShare(m);
|
||||
root.querySelectorAll(".perf-metric-name").forEach(function (n) { n.textContent = METRIC_NAMES[m]; });
|
||||
}
|
||||
@@ -422,6 +485,7 @@
|
||||
if (fold) collapsed.push(code);
|
||||
try { localStorage.setItem(GROUP_KEY, JSON.stringify(collapsed)); } catch (_) { /* 기억만 못 함 */ }
|
||||
});
|
||||
initColFold(root, colw);
|
||||
|
||||
// 수동 입력 엑셀 업로드 — 1열 날짜, 2열부터 쇼핑몰 이름 머리글. 값이 있는 칸만 반영(빈 칸은 기존 값 그대로).
|
||||
// 잘못된 칸이 있으면 서버가 아무것도 저장하지 않고 칸 위치 목록을 돌려준다.
|
||||
@@ -1045,10 +1109,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>";
|
||||
@@ -1332,7 +1396,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);
|
||||
});
|
||||
|
||||
@@ -40,6 +40,8 @@ MODULE_KEYS: tuple[str, ...] = (
|
||||
"inout",
|
||||
"outreach",
|
||||
"live",
|
||||
"live_host",
|
||||
"live_host_edit",
|
||||
"expense_approver",
|
||||
"vacation_approver",
|
||||
)
|
||||
|
||||
+25
-7
@@ -67,7 +67,7 @@ app/modules/cafe24/ ← 상품관리 모듈
|
||||
| `POST /cafe24/products/{product_no}/image` | 대표 이미지 교체 (multipart `file`) — `POST /admin/products/{no}/images`(base64 data URI, `image_upload_type=A`). 감사로그 `set_main_image` | `cafe24` |
|
||||
| `GET /cafe24/products/{product_no}/options` | 옵션 + 품목 조회 (JSON, 읽기 지연 보정 포함) | `cafe24` |
|
||||
| `POST /cafe24/products/{product_no}/options` | 옵션 생성 (`{option_name, values, display_type}`) — 조합형, 품목 자동 생성 | `cafe24` |
|
||||
| `PUT /cafe24/products/{product_no}/options` | 옵션명·옵션값 이름/썸네일/표시방식 수정 + 옵션값 끝에 덧붙이기 (`{options:[...], option_list_type}` → 덧붙였으면 `added` 와 새 품목 포함) | `cafe24` |
|
||||
| `PUT /cafe24/products/{product_no}/options` | 옵션명·옵션값 이름/썸네일/표시방식 수정 (`{options:[...], option_list_type}`; 옵션값 개수 변경은 400 — 추가는 재생성) | `cafe24` |
|
||||
| `DELETE /cafe24/products/{product_no}/options` | 옵션 삭제 — **품목도 함께 삭제**(화면 확인창) | `cafe24` |
|
||||
| `POST /cafe24/products/{product_no}/options/image` | 옵션값 썸네일 업로드만 (multipart → `{path}`) | `cafe24` |
|
||||
| `PUT /cafe24/products/{product_no}/variants` | 품목 자체코드·추가금액·진열·판매·진열순서 일괄 수정 (`{rows:[...]}`, 바뀐 행만) | `cafe24` |
|
||||
@@ -243,10 +243,20 @@ Admin API(OAuth)로는 스킨 파일을 읽거나 쓸 방법이 없다(`config.p
|
||||
|
||||
| 항목 | 값 |
|
||||
| --- | --- |
|
||||
| 대표 이미지(썸네일) | 파일을 고르면 그 시각에 교체 / 안 고르면 변경 없음 (마이그레이션 006) |
|
||||
| 상세페이지 HTML | 편집기 내용을 적용 / 적용 안 함 |
|
||||
| 진열 | 진열 · 미진열 · 변경 없음 |
|
||||
| 판매 | 판매 · 중지 · 변경 없음 |
|
||||
|
||||
- **대표 이미지 예약**(2026-11-09): 예약 폼의 파일 칸(`name="image"`, 폼은 multipart). 검증은 즉시
|
||||
교체와 같은 `_read_image`(JPG·PNG·GIF·WEBP, 10MB). 파일은 `cafe24_schedule_images`(BYTEA,
|
||||
예약 삭제 시 CASCADE)에, 형식·파일명은 `cafe24_product_schedules.image_type/image_name` 에 둔다 —
|
||||
worker 는 web 과 다른 컨테이너라 로컬 파일을 공유하지 않기 때문. worker 는 **이미지를 먼저**
|
||||
`products.set_main_image`(즉시 교체와 같은 A 타입) 로 올리고 스냅샷을 남긴 뒤 상세페이지·진열/판매를
|
||||
쓴다 — 뒤 단계 실패로 재시도되면 같은 이미지를 한 번 더 올릴 뿐이라 안전하다. 예약 목록에
|
||||
`GET /cafe24/schedules/{id}/image` 미리보기 썸네일. 이미지 없는 예약 INSERT 는 006 컬럼을 쓰지
|
||||
않아 마이그레이션 전에도 기존 예약 등록은 깨지지 않는다.
|
||||
|
||||
- **등록**은 편집기 아래 「예약 적용」에서 한다. HTML 을 적용하는 예약이면 그 시점의
|
||||
편집기 내용을 **DRAFT revision 으로 저장해 고정**한다 — 이후 편집기를 더 고쳐도
|
||||
예약된 내용은 바뀌지 않는다(예약해둔 것이 조용히 달라지면 안 된다).
|
||||
@@ -277,7 +287,7 @@ Admin API(OAuth)로는 스킨 파일을 읽거나 쓸 방법이 없다(`config.p
|
||||
서버(`store.parse_schedule_at`)는 예전과 같은 형식을 받으므로 백엔드는 그대로다.
|
||||
- **시각은 KST 로 해석**한다. 과거 시각은 거부하되
|
||||
폼을 채우는 동안 시간이 흐른 경우를 위해 1분 여유를 둔다.
|
||||
- **실행은 `app/modules/cafe24/worker.py`** — compose 서비스 `dbx-cafe24-worker` 가
|
||||
- **실행은 `app/modules/cafe24/worker.py`** — compose 서비스 `cafe24-worker`(컨테이너 `dbx-cafe24-worker`)가
|
||||
`--loop 60` 으로 돈다. 웹 요청 안에서 기다리는 방식은 프록시 타임아웃·재기동에
|
||||
무너지므로 별도 프로세스여야 한다.
|
||||
- worker 는 `claim_due_schedule` 로 **한 건씩 `FOR UPDATE SKIP LOCKED`** 로 잠그고
|
||||
@@ -472,6 +482,13 @@ cafe24_oauth_tokens 저장
|
||||
`quantity`, `image`…). `PUT /admin/products/{no}/variants` body `{"shop_no":1,
|
||||
"requests":[{variant_code, custom_variant_code, additional_amount, display, selling…}]}`
|
||||
1회 100건(초과 시 나눠 보냄). 재고(`quantity`)는 이 화면에서 건드리지 않는다.
|
||||
- **멀티쇼핑몰 진열·판매**(2026-11-10): 품목 진열·판매는 쇼핑몰(`shop_no`)마다 따로다. 화면은
|
||||
기본몰(1) 값을 보여 주고, 저장하면 기본몰에 반영된 행의 **진열·판매만** `CAFE24_SHOP_NOS`
|
||||
(예 `1,2,3`)의 다른 쇼핑몰에도 같은 값으로 PUT 한다. 추가금액(통화가 다름)·자체코드·순서는
|
||||
기본몰만. 다른 쇼핑몰 실패는 응답 `shop_failed`·감사 기록에 남기고 화면에 경고(기본몰 반영은 유지).
|
||||
쇼핑몰 목록 API(`/admin/shops`)는 `mall.read_store` 권한이 필요해 쓰지 않고 번호를 환경변수로 받는다.
|
||||
기존 상품 일괄 맞춤(일회성): `docker exec dbx-main python -m app.modules.cafe24.sync_variant_flags
|
||||
--shops 3,4 [--apply]` — 없으면 미리보기, 출력 `BEFORE` 줄 = 원래 값(되돌리기용), 감사 actor `SYNC_SHOPS`.
|
||||
- "옵션별 상품 이름" 은 옵션값(`option_text`)이고, "옵션별 썸네일" 은 `option_image_file`
|
||||
(+ `option_link_image` 에도 같은 경로) 이며,
|
||||
화면의 옵션값 썸네일은 **`option_image_file` → `option_link_image` → 그 옵션값을 가진
|
||||
@@ -494,11 +511,11 @@ cafe24_oauth_tokens 저장
|
||||
- **옵션값 불러오기**: 텍스트(탭 또는 두 칸 이상 공백 구분 — 이름 · 판매가 · 추가금액 ·
|
||||
자체코드, 판매가는 무시, 추가금액 「-」는 0)를 붙여넣어 행에 채운다. 옵션이 있는 상품은
|
||||
이름(공백 무시)으로 짝을 찾아 자체코드/추가금액만 채우고, 없는 이름은 새 행으로 추가한다.
|
||||
- **품목 추가**(「+ 행 추가」): 저장 시 옵션값을 **끝에 덧붙여** PUT options 한다
|
||||
(`build_update_options_request(allow_append=True)`). 앞쪽 위치는 그대로라 기존 이름이
|
||||
밀리지 않는다. 카페24가 받아들이면 품목을 자동 생성하므로 `wait_for_variants` 로 새
|
||||
코드를 받아 자체코드·추가금액·진열/판매를 이어서 PUT 한다. 거부하면 그 오류가 화면에 뜬다
|
||||
(문서상 "옵션 항목 추가/삭제 불가" 문구가 있어 실물 확인 필요 — 안 되면 아래 재생성).
|
||||
- **품목 추가**(「+ 행 추가」·불러오기의 새 행): 카페24 PUT options 는 옵션값 추가를
|
||||
지원하지 않는다(문서 "옵션 항목 추가/삭제 불가"). 실물에서 끝에 덧붙여 PUT 하면 **오류 없이
|
||||
무시**되어 "저장했는데 사라짐" 버그가 났다(2026-11-06). 그래서 새 행이 있으면 「저장」이
|
||||
확인창을 거쳐 **아래 옵션 재생성**으로 반영한다(품목코드 새로 부여). 서버
|
||||
`build_update_options_request` 도 개수 증가를 400 으로 거부한다.
|
||||
- **품목 삭제**(행의 ✕): `DELETE /admin/products/{no}/variants/{code}`(문서에 있는 유일한
|
||||
제거 수단). 옵션값 이름은 남을 수 있다 → 화면 하단 "품목이 없는 옵션값" 안내. 카페24 GET
|
||||
이 한동안 삭제된 품목을 계속 돌려주므로 스냅샷에 `{"_deleted": true}` 를 남겨 걸러낸다.
|
||||
@@ -559,6 +576,7 @@ CAFE24_REDIRECT_URI=https://dbx.no1king.freeddns.org/cafe24/oauth/callback
|
||||
CAFE24_API_VERSION=2026-03-01
|
||||
CAFE24_TOKEN_SECRET=<openssl rand -hex 32>
|
||||
CAFE24_SHOP_URL=https://www.miras.co.kr # 선택 — 다이렉트 주소용 커스텀 도메인
|
||||
CAFE24_SHOP_NOS=1,2,3 # 선택 — 품목 진열·판매를 같이 맞출 멀티쇼핑몰 번호(기본 1)
|
||||
|
||||
# 디자인 보관함 FTP (OAuth 와 별개 계정) — 모바일 스와이프 / PC·모바일 상품상세
|
||||
CAFE24_FTP_HOST=miraskitchen.ftp.cafe24.com # 선택 — 미설정 시 {mall_id}.ftp.cafe24.com
|
||||
|
||||
+6
-5
@@ -312,10 +312,10 @@ DDL: `scripts/sql/live_db_init.sql` (멱등). DB·역할(`live_app`)·테이블
|
||||
|
||||
| 테이블 | 용도 |
|
||||
| --- | --- |
|
||||
| `live_hosts` | 호스트 — Full Name (as per IC)·Phone Number·Email·Address·Bank Name·Bank Account Number·Tiktok Handle(@ 없이), `is_active` |
|
||||
| `live_broadcasts` | 방송 스케줄 — `host_id`(FK RESTRICT)·`broadcast_date`·`start_time`·`end_time`(말레이시아 시간 그대로)·`venue`·`sales_amount`(RM, NULL = 미입력) |
|
||||
| `live_hosts` | 호스트 — `platform`(쇼핑몰 `tiktok`·`shopee`, `''` = 예전 호스트, 마이그레이션 `live_db_005_host_platform.sql`)·`display_name`(간단한 이름, 마이그레이션 `live_db_004_host_display_name.sql`)·Full Name (as per IC)·Phone Number·Email·Address·Bank Name·Bank Account Number, `is_active`. `tiktok_handle` 열은 값만 남아 있고 쓰지 않음(003) |
|
||||
| `live_broadcasts` | 방송 스케줄 — `host_id`(FK RESTRICT)·`broadcast_date`·`start_time`·`end_time`(말레이시아 시간 그대로)·`venue`(2026-11-06 부터 입력 안 받음, 예전 값만)·`tiktok_handle`(그 방송의 계정, @ 없이, 마이그레이션 `live_db_003_broadcast_account.sql`)·`sales_amount`(RM, NULL = 미입력)·`ad_spend`(방송별 광고비)·`host_fee`(호스트 비용, 수기 입력) — 둘 다 RM·NULL = 미입력, 마이그레이션 `live_db_006_broadcast_fees.sql` |
|
||||
| `live_broadcast_images` | 방송 결과 이미지(메타데이터 제거 후 BYTEA, 방송을 지우면 CASCADE) — 방송당 최대 10장(앱에서 확인) |
|
||||
| `live_daily_ad_spend` | 날짜별 광고비(RM) — 달력 보기 AD SPEND·ROAS. 마이그레이션 `live_db_002_ad_spend.sql`(init 에도 포함) |
|
||||
| `live_daily_ad_spend` | 날짜별 광고비(RM) — 마이그레이션 `live_db_002_ad_spend.sql`(init 에도 포함). **006 부터 안 씀**(달력 AD SPEND = 그날 방송 `ad_spend` 합), 값만 남김 |
|
||||
|
||||
## malaysia_stock_db 스키마 / 초기화
|
||||
|
||||
@@ -361,7 +361,8 @@ DDL: `scripts/sql/cafe24_db_init.sql` (멱등). DB·역할(`cafe24_app`)·테이
|
||||
| `cafe24_oauth_tokens` | 쇼핑몰별 OAuth 토큰(`mall_id` UNIQUE). access/refresh 는 **Fernet 암호문**으로 저장. 상품관리 + 향후 주문관리가 공유 |
|
||||
| `cafe24_products` | 상품 캐시(`product_no` UNIQUE). 목록/검색 속도용이며 source of truth 는 언제나 카페24. `last_write_snapshot`(JSONB, 마이그레이션 004) 에 카페24 PUT 응답을 섹션별(`product`/`options`/`variants`)로 남겨 **읽기 지연**(PUT 뒤 GET 이 한동안 예전 값을 돌려줌) 동안 화면 기준으로 쓴다 |
|
||||
| `cafe24_product_revisions` | 상세페이지 HTML 버전(append-only). `revision_type` SYNC/DRAFT/**BACKUP**/MANUAL/SCHEDULED/ROLLBACK |
|
||||
| `cafe24_product_schedules` | 예약 작업. `status` PENDING/PROCESSING/SUCCESS/FAILED/CANCELLED, 재시도·자동종료·복원 대상 포함 |
|
||||
| `cafe24_product_schedules` | 예약 작업. `status` PENDING/PROCESSING/SUCCESS/FAILED/CANCELLED, 재시도·자동종료·복원 대상 포함. `image_type`/`image_name`(006) = 대표 이미지 교체 예약 |
|
||||
| `cafe24_schedule_images` | 대표 이미지 예약 파일(BYTEA, 10MB 이하, 예약 삭제 시 CASCADE) — 마이그레이션 006 |
|
||||
| `cafe24_audit_logs` | 누가 무엇을 바꿨나. worker 수행분은 `actor='SCHEDULER'` |
|
||||
| `cafe24_api_logs` | 카페24 API 호출 기록. **토큰/Authorization/client_secret 미기록** |
|
||||
|
||||
@@ -371,7 +372,7 @@ DDL: `scripts/sql/cafe24_db_init.sql` (멱등). DB·역할(`cafe24_app`)·테이
|
||||
- 예약의 `restore_revision_id` 는 **예약 실행 순간** 만든 BACKUP 을 가리킨다(예약 생성 시점 값이 아님).
|
||||
- 일괄 예약은 상품 1건당 1행 + 공통 `parent_job_id` — 한 상품 실패가 나머지를 막지 않는다.
|
||||
- 토큰 암호화 키는 `.env` 의 `CAFE24_TOKEN_SECRET`. **값을 바꾸면 기존 토큰을 복호화할 수 없어 카페24 재연결이 필요하다.**
|
||||
- 기존 운영 DB 에는 마이그레이션 002·003·004 를 순서대로 적용한다(전부 멱등):
|
||||
- 기존 운영 DB 에는 마이그레이션 002·003·004·005·006 을 순서대로 적용한다(전부 멱등):
|
||||
`docker exec -i postgres-db psql -U postgres -d cafe24_db < scripts/sql/cafe24_db_004_write_snapshot.sql`
|
||||
|
||||
### 운영 서버 초기화 (1회, 사용자 승인 후)
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
-- =====================================================================
|
||||
-- cafe24_db 006 — 예약에 대표 이미지 교체 추가 (2026-11-09)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent): 여러 번 실행해도 안전. DROP TABLE/TRUNCATE 없음.
|
||||
--
|
||||
-- 실행:
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d cafe24_db \
|
||||
-- < scripts/sql/cafe24_db_006_schedule_image.sql
|
||||
--
|
||||
-- 배경:
|
||||
-- 지정 시각에 상품 대표 이미지(썸네일)를 교체하는 예약. 등록 때 올린 파일을
|
||||
-- 그 시각까지 보관해야 하므로 바이트를 DB 에 둔다(worker 는 web 과 다른
|
||||
-- 컨테이너라 로컬 파일을 공유하지 않는다). 예약 목록(s.*)이 무거워지지 않게
|
||||
-- 바이트는 별도 테이블에 둔다.
|
||||
-- cafe24_product_schedules.image_type = '' → 이미지 교체 없음
|
||||
-- 'image/png' 등 → 그 시각에 교체
|
||||
--
|
||||
-- 롤백(이미지 예약을 쓰지 않을 때만):
|
||||
-- ALTER TABLE cafe24_product_schedules DROP CONSTRAINT chk_cafe24_schedule_has_action;
|
||||
-- ALTER TABLE cafe24_product_schedules ADD CONSTRAINT chk_cafe24_schedule_has_action CHECK (
|
||||
-- revision_id IS NOT NULL OR set_display IS NOT NULL OR set_selling IS NOT NULL);
|
||||
-- DROP TABLE cafe24_schedule_images;
|
||||
-- ALTER TABLE cafe24_product_schedules DROP COLUMN image_type, DROP COLUMN image_name;
|
||||
-- =====================================================================
|
||||
|
||||
\set ON_ERROR_STOP on
|
||||
|
||||
ALTER TABLE cafe24_product_schedules
|
||||
ADD COLUMN IF NOT EXISTS image_type TEXT NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS image_name TEXT NOT NULL DEFAULT '';
|
||||
|
||||
COMMENT ON COLUMN cafe24_product_schedules.image_type IS
|
||||
'예약 시각에 교체할 대표 이미지의 형식(image/png 등). 빈 값이면 이미지 교체 없음';
|
||||
COMMENT ON COLUMN cafe24_product_schedules.image_name IS
|
||||
'등록 때 올린 대표 이미지 파일명(표시용)';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS cafe24_schedule_images (
|
||||
schedule_id BIGINT PRIMARY KEY REFERENCES cafe24_product_schedules(id) ON DELETE CASCADE,
|
||||
data BYTEA NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE cafe24_schedule_images IS '예약 대표 이미지 파일(10MB 이하)';
|
||||
|
||||
-- 아무것도 하지 않는 예약은 만들 수 없게 한다 — 이미지 교체도 "할 일"로 센다.
|
||||
ALTER TABLE cafe24_product_schedules
|
||||
DROP CONSTRAINT IF EXISTS chk_cafe24_schedule_has_action;
|
||||
ALTER TABLE cafe24_product_schedules
|
||||
ADD CONSTRAINT chk_cafe24_schedule_has_action CHECK (
|
||||
revision_id IS NOT NULL OR set_display IS NOT NULL OR set_selling IS NOT NULL OR image_type <> ''
|
||||
);
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON cafe24_schedule_images TO cafe24_app;
|
||||
|
||||
SELECT 'cafe24_db 006 applied' AS status;
|
||||
@@ -0,0 +1,26 @@
|
||||
-- =====================================================================
|
||||
-- live_db 마이그레이션 003 — 틱톡 계정을 호스트가 아니라 방송마다(2026-11-05)
|
||||
-- =====================================================================
|
||||
-- 왜: 호스트는 메인 계정에서만 방송하지 않고 다른 계정에서도 방송한다(말레이시아 직원 요청).
|
||||
-- 멱등(idempotent). 열 하나 추가 + 처음 추가할 때만 기존 방송에 그 호스트의 지금 계정을 복사한다.
|
||||
-- live_hosts.tiktok_handle 은 지우지 않는다(값 보존 — 앱이 더는 읽거나 쓰지 않음).
|
||||
-- 운영: /opt/www/main 에서 기존 live_db 에 앱 배포 전에 적용(백업 먼저).
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d live_db < scripts/sql/live_db_003_broadcast_account.sql
|
||||
-- 되돌리기: ALTER TABLE live_broadcasts DROP COLUMN tiktok_handle; (방송별 계정만 사라짐 — 실행 전 백업)
|
||||
-- =====================================================================
|
||||
\set ON_ERROR_STOP on
|
||||
BEGIN;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name = 'live_broadcasts' AND column_name = 'tiktok_handle') THEN
|
||||
ALTER TABLE live_broadcasts ADD COLUMN tiktok_handle TEXT NOT NULL DEFAULT '';
|
||||
UPDATE live_broadcasts b SET tiktok_handle = h.tiktok_handle FROM live_hosts h WHERE h.id = b.host_id;
|
||||
END IF;
|
||||
END $$;
|
||||
COMMENT ON COLUMN live_broadcasts.tiktok_handle IS '그 방송을 한 틱톡 계정(@ 없이)';
|
||||
|
||||
COMMIT;
|
||||
SELECT 'live_db 003 broadcast account ready' AS status,
|
||||
count(*) AS broadcasts, count(*) FILTER (WHERE tiktok_handle <> '') AS with_account FROM live_broadcasts;
|
||||
@@ -0,0 +1,17 @@
|
||||
-- =====================================================================
|
||||
-- live_db 마이그레이션 004 — 호스트 간단한 이름(달력 카드·방송 창·스케줄표 표시용)(2026-11-05)
|
||||
-- =====================================================================
|
||||
-- 왜: Full Name (as per IC)은 길고, 말레이 이름은 끝이 아버지 이름이라 자동으로 줄일 수 없다. 사람이 직접 입력한다.
|
||||
-- 멱등(idempotent). 열 하나만 추가(기존 값 변경 없음). 비어 있는 호스트는 화면에 Full Name 이 그대로 보인다.
|
||||
-- 운영: /opt/www/main 에서 기존 live_db 에 앱 배포 전에 적용(백업 먼저, 003 다음).
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d live_db < scripts/sql/live_db_004_host_display_name.sql
|
||||
-- 되돌리기: ALTER TABLE live_hosts DROP COLUMN display_name; (간단한 이름만 사라짐 — 실행 전 백업)
|
||||
-- =====================================================================
|
||||
\set ON_ERROR_STOP on
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE live_hosts ADD COLUMN IF NOT EXISTS display_name TEXT NOT NULL DEFAULT '';
|
||||
COMMENT ON COLUMN live_hosts.display_name IS '간단한 이름 — 비어 있으면 화면은 full_name';
|
||||
|
||||
COMMIT;
|
||||
SELECT 'live_db 004 host display name ready' AS status, count(*) AS hosts, count(*) FILTER (WHERE display_name <> '') AS named FROM live_hosts;
|
||||
@@ -0,0 +1,18 @@
|
||||
-- =====================================================================
|
||||
-- live_db 마이그레이션 005 — 호스트 쇼핑몰(틱톡·쇼피)(2026-11-06)
|
||||
-- =====================================================================
|
||||
-- 왜: 호스트가 틱톡 호스트인지 쇼피 호스트인지 설정 화면에서 고르고 목록 첫 열에 로고로 보인다.
|
||||
-- 멱등(idempotent). 열 하나만 추가(기존 값 변경 없음). 예전 호스트는 '' (고치기에서 고르면 저장).
|
||||
-- 운영: /opt/www/main 에서 기존 live_db 에 앱 배포 전에 적용(백업 먼저, 004 다음).
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d live_db < scripts/sql/live_db_005_host_platform.sql
|
||||
-- 되돌리기: ALTER TABLE live_hosts DROP COLUMN platform; (쇼핑몰 값만 사라짐 — 실행 전 백업)
|
||||
-- =====================================================================
|
||||
\set ON_ERROR_STOP on
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE live_hosts ADD COLUMN IF NOT EXISTS platform TEXT NOT NULL DEFAULT ''
|
||||
CHECK (platform IN ('', 'tiktok', 'shopee'));
|
||||
COMMENT ON COLUMN live_hosts.platform IS '쇼핑몰 — tiktok·shopee, 빈 값 = 예전 호스트(아직 안 고름)';
|
||||
|
||||
COMMIT;
|
||||
SELECT 'live_db 005 host platform ready' AS status, count(*) AS hosts, count(*) FILTER (WHERE platform <> '') AS chosen FROM live_hosts;
|
||||
@@ -0,0 +1,21 @@
|
||||
-- =====================================================================
|
||||
-- live_db 마이그레이션 006 — 방송별 광고비·호스트 비용(2026-11-06)
|
||||
-- =====================================================================
|
||||
-- 왜: 방송 창에서 Ad Spend(방송별 광고비)와 Host fee(호스트 비용, 수기 입력)를 받는다.
|
||||
-- 달력 날짜별 광고비 = 그날 방송 Ad Spend 합계(live_daily_ad_spend 는 더 안 씀 — 값은 남김).
|
||||
-- Fee(시간 × RM25)·Commission(판매금액 × 10%)은 저장 안 함(화면에서 계산).
|
||||
-- 멱등(idempotent). 열 두 개만 추가(기존 값 변경 없음). 예전 방송은 NULL(= 0 으로 보임).
|
||||
-- 운영: /opt/www/main 에서 기존 live_db 에 앱 배포 전에 적용(백업 먼저, 005 다음).
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d live_db < scripts/sql/live_db_006_broadcast_fees.sql
|
||||
-- 되돌리기: ALTER TABLE live_broadcasts DROP COLUMN ad_spend, DROP COLUMN host_fee; (입력한 값만 사라짐 — 실행 전 백업)
|
||||
-- =====================================================================
|
||||
\set ON_ERROR_STOP on
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE live_broadcasts ADD COLUMN IF NOT EXISTS ad_spend NUMERIC(14,2) CHECK (ad_spend IS NULL OR ad_spend >= 0);
|
||||
ALTER TABLE live_broadcasts ADD COLUMN IF NOT EXISTS host_fee NUMERIC(14,2) CHECK (host_fee IS NULL OR host_fee >= 0);
|
||||
COMMENT ON COLUMN live_broadcasts.ad_spend IS '방송별 광고비(RM) — NULL = 입력 안 함';
|
||||
COMMENT ON COLUMN live_broadcasts.host_fee IS '호스트 비용(RM, 수기 입력) — NULL = 입력 안 함';
|
||||
|
||||
COMMIT;
|
||||
SELECT 'live_db 006 broadcast fees ready' AS status, count(*) AS broadcasts FROM live_broadcasts;
|
||||
@@ -52,7 +52,9 @@ CREATE TABLE IF NOT EXISTS live_hosts (
|
||||
address TEXT NOT NULL DEFAULT '',
|
||||
bank_name TEXT NOT NULL DEFAULT '',
|
||||
bank_account TEXT NOT NULL DEFAULT '',
|
||||
tiktok_handle TEXT NOT NULL DEFAULT '', -- @ 없이
|
||||
display_name TEXT NOT NULL DEFAULT '', -- 간단한 이름(004), 비면 화면은 full_name
|
||||
tiktok_handle TEXT NOT NULL DEFAULT '', -- 쓰지 않음(003 부터 방송별 live_broadcasts.tiktok_handle)
|
||||
platform TEXT NOT NULL DEFAULT '' CHECK (platform IN ('', 'tiktok', 'shopee')), -- 쇼핑몰(005), '' = 아직 안 고름
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE, -- FALSE = 새 방송에서 못 고름
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
@@ -74,8 +76,11 @@ CREATE TABLE IF NOT EXISTS live_broadcasts (
|
||||
start_time TIME NOT NULL,
|
||||
end_time TIME,
|
||||
venue TEXT NOT NULL DEFAULT '',
|
||||
tiktok_handle TEXT NOT NULL DEFAULT '', -- 그 방송을 한 계정(@ 없이), 마이그레이션 003
|
||||
sales_amount NUMERIC(14,2) CHECK (sales_amount IS NULL OR sales_amount >= 0), -- NULL = 아직 입력 안 함
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
ad_spend NUMERIC(14,2) CHECK (ad_spend IS NULL OR ad_spend >= 0), -- 방송별 광고비, 마이그레이션 006
|
||||
host_fee NUMERIC(14,2) CHECK (host_fee IS NULL OR host_fee >= 0), -- 호스트 비용(수기 입력), 마이그레이션 006
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
@@ -105,7 +110,7 @@ COMMENT ON TABLE live_broadcast_images IS '라이브 커머스 — 방송 결과
|
||||
CREATE INDEX IF NOT EXISTS idx_live_images_broadcast ON live_broadcast_images (broadcast_id, id);
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 3-1) 날짜별 광고비 — 마이그레이션 002 와 같음(달력 보기 AD SPEND·ROAS)
|
||||
-- 3-1) 날짜별 광고비 — 마이그레이션 002 와 같음. 006 부터 안 씀(방송별 live_broadcasts.ad_spend 합계로 바뀜, 값은 남김)
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS live_daily_ad_spend (
|
||||
ad_date DATE PRIMARY KEY,
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
// 입출고 날짜 칸 = ERP 공용 달력(2026-11-05) — 실제 브라우저(Chromium).
|
||||
// python tests/js/render_inout.py
|
||||
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/inout_datepop.browser.test.js
|
||||
// 기본 달력 대신 날짜 버튼, 국경일·대체공휴일 빨강·이름·말풍선(title), 고르면 값 전송, 필수 칸은 지우기 없음, 잠긴 칸은 못 누름.
|
||||
const fs = require("fs"), path = require("path");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const fails = [];
|
||||
function check(name, cond, extra) {
|
||||
if (cond) console.log("PASS " + name);
|
||||
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
|
||||
}
|
||||
|
||||
(async function () {
|
||||
const exe = process.env.PJ_TEST_BROWSER;
|
||||
const browser = await chromium.launch(exe ? { executablePath: exe } : {});
|
||||
try {
|
||||
const p = await (await browser.newContext({ viewport: { width: 1400, height: 900 } })).newPage();
|
||||
const errors = [];
|
||||
p.on("pageerror", function (e) { errors.push(String(e)); });
|
||||
await p.route("**/*", function (r) {
|
||||
const url = new URL(r.request().url()).pathname;
|
||||
if (url.startsWith("/static/")) {
|
||||
const f = path.join(ROOT, "app", url);
|
||||
if (!fs.existsSync(f)) return r.fulfill({ status: 404, body: "" });
|
||||
const type = f.endsWith(".css") ? "text/css" : f.endsWith(".js") ? "application/javascript" : "font/woff2";
|
||||
return r.fulfill({ status: 200, contentType: type, body: fs.readFileSync(f) });
|
||||
}
|
||||
if (!url.endsWith(".html")) return r.fulfill({ status: 200, contentType: "application/json", body: "{}" });
|
||||
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fs.readFileSync(path.join(__dirname, ".out", url.slice(1)), "utf8") });
|
||||
});
|
||||
|
||||
await p.goto("http://erp.test/inout_form.html");
|
||||
await p.waitForTimeout(200);
|
||||
const order = p.locator('input[name="order_date"]'), due = p.locator('input[name="due_date"]');
|
||||
check("기본 달력 칸은 숨김", !(await order.isVisible()) && !(await due.isVisible()));
|
||||
const orderBtn = p.locator('input[name="order_date"] + button'), dueBtn = p.locator('input[name="due_date"] + button');
|
||||
check("발주일 버튼 = yyyy.mm.dd(요일)", (await orderBtn.textContent()).includes("2026.10.05(월)"), await orderBtn.textContent());
|
||||
|
||||
await orderBtn.click();
|
||||
const pop = p.locator(".pj-datepop");
|
||||
check("달력이 열림", await pop.isVisible());
|
||||
const hol = pop.locator('[data-iso="2026-10-09"]');
|
||||
check("한글날 = 빨강 칸·이름·말풍선", (await hol.getAttribute("class")).includes("is-sun") && (await hol.getAttribute("title")) === "한글날" && (await hol.textContent()).includes("한글날"), await hol.getAttribute("title"));
|
||||
check("필수 칸은 지우기 없음", (await pop.getByText("지우기").count()) === 0);
|
||||
await p.waitForTimeout(200); // 등장 애니메이션 뒤에 찍는다
|
||||
await p.screenshot({ path: path.join(__dirname, ".out", "inout_datepop.png") });
|
||||
await pop.locator('[data-iso="2026-10-08"]').click();
|
||||
await p.keyboard.press("Escape");
|
||||
check("고른 날짜가 값으로", (await order.inputValue()) === "2026-10-08", await order.inputValue());
|
||||
check("버튼 글자도 바뀜", (await orderBtn.textContent()).includes("2026.10.08(목)"));
|
||||
|
||||
await dueBtn.click();
|
||||
check("선택 칸은 지우기 있음", (await pop.getByText("지우기").count()) === 1);
|
||||
// 대체공휴일 — 2026-03-02 삼일절 대체(달을 넘겨 찾지 않고 표 값으로 확인)
|
||||
const holidays = await p.evaluate(function () { return JSON.parse(document.getElementById("io-holidays").textContent); });
|
||||
check("대체공휴일도 표에 있음", holidays["2026-03-02"] === "삼일절 대체", holidays["2026-03-02"]);
|
||||
await p.keyboard.press("Escape");
|
||||
|
||||
await p.goto("http://erp.test/inout_list.html");
|
||||
await p.waitForTimeout(200);
|
||||
check("목록 필터 시작일 버튼", (await p.locator('input[name="from"] + button').textContent()).includes("2026.10.01(목)"));
|
||||
const box = await p.locator('input[name="from"] + button').boundingBox();
|
||||
const search = await p.locator('input[name="q"]').boundingBox();
|
||||
check("필터 줄 높이가 맞음", Math.abs((box.y + box.height / 2) - (search.y + search.height / 2)) < 4, { box: box, search: search });
|
||||
await p.screenshot({ path: path.join(__dirname, ".out", "inout_list.png") });
|
||||
// 목록 거르기(2026-11-05) — 발주일~찾기 묶음의 오른쪽 끝 = 표 상자 오른쪽 끝(표는 넓으면 상자 안에서 가로 스크롤), 줄이 바뀌어도
|
||||
const rightEdge = async function () {
|
||||
const btn = await p.getByRole("button", { name: "찾기" }).boundingBox();
|
||||
const wrap = await p.locator(".erp-table-wrap").boundingBox();
|
||||
return Math.abs(btn.x + btn.width - (wrap.x + wrap.width));
|
||||
};
|
||||
check("좁은 화면: 찾기가 오른쪽 끝", (await rightEdge()) < 2, await rightEdge());
|
||||
await p.setViewportSize({ width: 2000, height: 900 });
|
||||
await p.waitForTimeout(100);
|
||||
await p.screenshot({ path: path.join(__dirname, ".out", "inout_list_wide.png") });
|
||||
check("넓은 화면: 찾기가 오른쪽 끝", (await rightEdge()) < 2, await rightEdge());
|
||||
await p.setViewportSize({ width: 1400, height: 900 });
|
||||
await p.waitForTimeout(100);
|
||||
|
||||
// 목록 머리글(2026-11-05) — 숫자 열까지 가운데, 굵게, 12px × 1.11, 회색 배경
|
||||
const headStyles = await p.locator(".io-table thead th").evaluateAll(function (els) {
|
||||
return els.map(function (el) { const c = getComputedStyle(el); return [c.textAlign, c.fontWeight, c.fontSize, c.backgroundColor].join("|"); });
|
||||
});
|
||||
check("머리글 모양", headStyles.length > 0 && headStyles.every(function (s) { return /^center\|700\|11\.98\d*px\|rgb\(242, 242, 242\)$/.test(s); }), headStyles);
|
||||
const sizeOf = function (sel) { return p.locator(sel).first().evaluate(function (el) { return getComputedStyle(el).fontSize; }); };
|
||||
check("표 글자 90%", (await sizeOf(".io-table tbody td")) === "11.7px" && (await sizeOf(".io-table .erp-row-sub")) === "10.8px" && (await sizeOf(".io-table .io-progress-pct")) === "10.8px" && (await sizeOf(".io-table .io-badge")) === "10.35px");
|
||||
await p.setViewportSize({ width: 2000, height: 900 });
|
||||
await p.waitForTimeout(100);
|
||||
check("달력 최대 396px(440px × 90%)", Math.round((await p.locator(".io-side").boundingBox()).width) === 396, await p.locator(".io-side").boundingBox());
|
||||
await p.setViewportSize({ width: 1400, height: 900 });
|
||||
await p.waitForTimeout(100);
|
||||
|
||||
// 목록 입고일 열(2026-11-05) — 입고 예정일과 발주 사이, 여러 날은 한 칸에서 줄바꿈, 입고 전 "-"
|
||||
const heads = await p.locator(".io-table thead th").allInnerTexts();
|
||||
check("입고일 열 위치", heads.indexOf("입고일") === heads.indexOf("입고 예정일") + 1 && heads.indexOf("발주") === heads.indexOf("입고일") + 1, heads);
|
||||
const col = heads.indexOf("입고일") + 1;
|
||||
const cell = function (row) { return p.locator(".io-table tbody tr:nth-child(" + row + ") td:nth-child(" + col + ")"); };
|
||||
const lines = await cell(1).locator("div").evaluateAll(function (els) {
|
||||
return els.map(function (el) { return { text: el.textContent, top: el.getBoundingClientRect().top }; });
|
||||
});
|
||||
check("여러 날 = 줄바꿈", lines.length === 2 && lines[0].text === "2026.10.21(수)" && lines[1].text === "2026.10.23(금)" && lines[1].top > lines[0].top, lines);
|
||||
check("하루 입고 = 한 줄", (await cell(2).innerText()).trim() === "2026.10.22(목)");
|
||||
check("입고 전 = -", (await cell(3).innerText()).trim() === "-");
|
||||
|
||||
await p.goto("http://erp.test/inout_locked.html");
|
||||
await p.waitForTimeout(200);
|
||||
check("잠긴 입고일은 못 누름", await p.locator('input[name="receipt_date"] + button').isDisabled());
|
||||
check("스크립트 오류 없음", errors.length === 0, errors);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
if (fails.length) { console.log("\n" + fails.length + " FAILED"); process.exit(1); }
|
||||
console.log("\nALL OK");
|
||||
})();
|
||||
@@ -0,0 +1,244 @@
|
||||
// 라이브 커머스 오른쪽 달력(2026-11-05) — 실제 브라우저(Chromium).
|
||||
// python tests/js/render_live.py
|
||||
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/live_calendar.browser.test.js
|
||||
// 세로 2분할·오른쪽 위 고정·전체 너비, 말레이시아 공휴일·대체휴일 빨강·이름·말풍선, 날짜를 누르면 그 날이 표 맨 왼쪽(마지막 날까지), 다른 달은 그 달 화면으로 가서 맨 왼쪽, 영문 화면은 달력도 영어.
|
||||
const fs = require("fs"), path = require("path");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const fails = [];
|
||||
function check(name, cond, extra) {
|
||||
if (cond) console.log("PASS " + name);
|
||||
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
|
||||
}
|
||||
|
||||
(async function () {
|
||||
const exe = process.env.PJ_TEST_BROWSER;
|
||||
const browser = await chromium.launch(exe ? { executablePath: exe } : {});
|
||||
try {
|
||||
const p = await (await browser.newContext({ viewport: { width: 1600, height: 900 } })).newPage();
|
||||
const errors = [];
|
||||
p.on("pageerror", function (e) { errors.push(String(e)); });
|
||||
await p.route("**/*", function (r) {
|
||||
const u = new URL(r.request().url());
|
||||
if (u.pathname.startsWith("/static/")) {
|
||||
const f = path.join(ROOT, "app", u.pathname);
|
||||
if (!fs.existsSync(f)) return r.fulfill({ status: 404, body: "" });
|
||||
const type = f.endsWith(".css") ? "text/css" : f.endsWith(".js") ? "application/javascript" : f.endsWith(".png") ? "image/png" : "font/woff2";
|
||||
return r.fulfill({ status: 200, contentType: type, body: fs.readFileSync(f) });
|
||||
}
|
||||
if (u.pathname.startsWith("/live/images/")) { // 결과 이미지 미리보기 — 아무 그림이나
|
||||
return r.fulfill({ status: 200, contentType: "image/png", body: fs.readFileSync(path.join(ROOT, "app", "static", "dispatch", "courier", "tiktok.png")) });
|
||||
}
|
||||
const page = u.pathname === "/live/calendar" ? (u.searchParams.get("month") === "2026-12" ? "live_cal_dec.html" : "live_cal_ko.html") : u.pathname.slice(1);
|
||||
if (!page.endsWith(".html")) return r.fulfill({ status: 200, contentType: "application/json", body: "{}" });
|
||||
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fs.readFileSync(path.join(__dirname, ".out", page), "utf8") });
|
||||
});
|
||||
// 맨 왼쪽 = 그 날 열의 왼쪽 끝이 고정된 시간 열 바로 옆
|
||||
const gap = function (iso) {
|
||||
return p.evaluate(function (d) {
|
||||
const col = document.querySelector('thead th[data-day="' + d + '"]').getBoundingClientRect();
|
||||
return Math.abs(col.left - document.querySelector("thead .lv-cal-time").getBoundingClientRect().right);
|
||||
}, iso);
|
||||
};
|
||||
const day = function (iso) { return p.locator('#lv-side-cal [data-iso="' + iso + '"]'); };
|
||||
|
||||
await p.goto("http://erp.test/live/calendar?month=2026-11");
|
||||
await p.waitForTimeout(300);
|
||||
const side = await p.locator("#lv-side-cal").boundingBox(), wrap = await p.locator("#lv-cal-wrap").boundingBox();
|
||||
const bar = await p.locator(".lv-bar").boundingBox();
|
||||
check("달력이 오른쪽 위(왼쪽 내용과 같은 높이에서 시작)", side.x >= wrap.x + wrap.width && Math.abs(side.y - bar.y) < 6, { side: side, bar: bar });
|
||||
check("날짜로 이동 줄 없음", (await p.locator(".lv-jump, [data-jump]").count()) === 0);
|
||||
const edges = await p.evaluate(function () {
|
||||
const page = document.querySelector(".erp-page").getBoundingClientRect();
|
||||
const s = document.getElementById("lv-side-cal").getBoundingClientRect(), l = document.querySelector(".lv").getBoundingClientRect();
|
||||
return { left: l.left - page.left, right: page.right - s.right };
|
||||
});
|
||||
check("좌우 여백 12px", edges.left <= 13 && edges.right <= 13, edges);
|
||||
await p.setViewportSize({ width: 2400, height: 900 });
|
||||
await p.waitForTimeout(100);
|
||||
const wide = await p.evaluate(function () {
|
||||
const page = document.querySelector(".erp-page").getBoundingClientRect();
|
||||
return { pageRight: page.right, shell: document.documentElement.clientWidth };
|
||||
});
|
||||
check("넓은 화면도 전체 너비(최대 폭 해제)", Math.abs(wide.pageRight - wide.shell) < 2, wide);
|
||||
// 풀HD 브라우저 — 페이지 세로 스크롤 없음, 모든 시간 칸에 카드가 있어도 표 안 스크롤도 없음
|
||||
const fit = function () {
|
||||
return p.evaluate(function () {
|
||||
const pg = document.querySelector(".erp-page"), w = document.getElementById("lv-cal-wrap");
|
||||
return { page: pg.scrollHeight - pg.clientHeight, table: w.scrollHeight - w.clientHeight, wrapH: w.clientHeight, row: document.querySelector(".lv-cal tbody tr").getBoundingClientRect().height };
|
||||
});
|
||||
};
|
||||
// 1시간 칸(18줄, 2026-11-06) — 카드가 많은 달은 표 안에서 스크롤, 방송이 적은 달은 표도 한 화면
|
||||
for (const h of [937, 880]) {
|
||||
await p.setViewportSize({ width: 1920, height: h });
|
||||
await p.waitForTimeout(100);
|
||||
const f = await fit();
|
||||
check("1920×" + h + ": 페이지 세로 스크롤 없음", f.page <= 0, f);
|
||||
if (h === 880) await p.screenshot({ path: path.join(__dirname, ".out", "live_fit_880.png") });
|
||||
}
|
||||
await p.goto("http://erp.test/live/calendar?month=2026-12");
|
||||
await p.waitForTimeout(300);
|
||||
const empty = await fit();
|
||||
check("1920×880 방송 없는 달: 18줄이 표 안 스크롤 없이", empty.page <= 0 && empty.table <= 0, empty);
|
||||
await p.screenshot({ path: path.join(__dirname, ".out", "live_fit_880_empty.png") });
|
||||
await p.goto("http://erp.test/live/calendar?month=2026-11");
|
||||
await p.waitForTimeout(300);
|
||||
await p.setViewportSize({ width: 1600, height: 600 });
|
||||
await p.waitForTimeout(100);
|
||||
const small = await fit();
|
||||
check("더 낮은 창: 페이지는 안 움직이고 표 안에서 스크롤", small.page <= 0 && small.table > 0, small);
|
||||
const miniW = (await p.locator("#lv-side-cal").boundingBox()).width;
|
||||
check("오른쪽 달력 = 240px(300px × 80%)", Math.round(miniW) === 240, miniW);
|
||||
const miniDay = await day("2026-11-17").evaluate(function (el) { const c = getComputedStyle(el); return c.height + "|" + c.fontSize; });
|
||||
check("달력 칸·글자도 80%", miniDay === "27px|10.8px", miniDay);
|
||||
await p.setViewportSize({ width: 1600, height: 900 });
|
||||
await p.waitForTimeout(100);
|
||||
check("디파발리 = 빨강·이름·말풍선", (await day("2026-11-08").getAttribute("class")).includes("has-hol") && (await day("2026-11-08").getAttribute("title")) === "디파발리");
|
||||
check("대체휴일 표시", (await day("2026-11-09").innerText()).includes("대체휴일") && (await day("2026-11-09").getAttribute("title")) === "디파발리 대체", await day("2026-11-09").innerText());
|
||||
const marked = await p.locator("#lv-side-cal .has-live").evaluateAll(function (els) { return els.map(function (e) { return e.dataset.iso; }); });
|
||||
// 2026-11 달력은 11/1(일)부터라 10/30 칸은 없음, 12/3 = 다음 달 칸
|
||||
check("방송 있는 날 = 점(다른 달 날짜 포함)", JSON.stringify(marked) === JSON.stringify(["2026-11-05", "2026-11-20", "2026-12-03"]), marked);
|
||||
const dot = await day("2026-11-20").evaluate(function (el) { const c = getComputedStyle(el, "::after"); return c.width + "|" + c.backgroundColor; });
|
||||
check("점 모양", dot === "6px|rgb(22, 163, 74)", dot);
|
||||
const bold = await p.evaluate(function () {
|
||||
return ["#lv-side-cal .pj-dp-title", "#lv-side-cal .pj-dp-wd", '#lv-side-cal [data-iso="2026-11-17"]'].map(function (s) { return getComputedStyle(document.querySelector(s)).fontWeight; });
|
||||
});
|
||||
check("오른쪽 달력 글자 굵게", bold.every(function (w) { return +w >= 700; }), bold);
|
||||
await p.screenshot({ path: path.join(__dirname, ".out", "live_side_cal.png") });
|
||||
|
||||
await day("2026-11-17").click();
|
||||
await p.waitForTimeout(150);
|
||||
check("17일이 맨 왼쪽", (await gap("2026-11-17")) < 2, await gap("2026-11-17"));
|
||||
check("누른 날 선택 표시", (await day("2026-11-17").getAttribute("class")).includes("is-selected"));
|
||||
await day("2026-11-30").click();
|
||||
await p.waitForTimeout(150);
|
||||
check("마지막 날도 맨 왼쪽", (await gap("2026-11-30")) < 2, await gap("2026-11-30"));
|
||||
await p.screenshot({ path: path.join(__dirname, ".out", "live_side_cal_end.png") });
|
||||
await day("2026-11-02").click();
|
||||
await p.waitForTimeout(150);
|
||||
check("앞날로 돌아감", (await gap("2026-11-02")) < 2, await gap("2026-11-02"));
|
||||
// 2시간 방송 = 두 칸 합침(rowspan), 22:00~23:30 = 22·23 칸
|
||||
const merged = await p.evaluate(function () {
|
||||
return Array.from(document.querySelectorAll('td[data-day="2026-11-05"]')).map(function (td) { return td.dataset.start + "/" + (td.rowSpan || 1); });
|
||||
});
|
||||
check("2시간 방송 = 두 칸 합침", merged.slice(0, 3).join(",") === "06:00/2,08:00/2,10:00/2" && merged[merged.length - 1] === "22:00/2", merged);
|
||||
const tall = await p.evaluate(function () {
|
||||
const m = document.querySelector('td[data-day="2026-11-05"][data-start="06:00"]').getBoundingClientRect().height;
|
||||
const one = document.querySelector('td[data-day="2026-11-04"][data-start="06:00"]').getBoundingClientRect().height;
|
||||
const two = document.querySelector('td[data-day="2026-11-04"][data-start="07:00"]').getBoundingClientRect().height;
|
||||
return Math.abs(m - one - two);
|
||||
});
|
||||
check("합친 칸 높이 = 두 줄", tall < 2, tall);
|
||||
const fill = await p.evaluate(function () {
|
||||
const td = document.querySelector('td[data-day="2026-11-05"][data-start="08:00"]'), card = td.querySelector(".lv-card");
|
||||
const pad = parseFloat(getComputedStyle(td).paddingTop) + parseFloat(getComputedStyle(td).paddingBottom);
|
||||
return Math.abs(td.getBoundingClientRect().height - pad - 1 - card.getBoundingClientRect().height); // 1 = 칸 아래 선
|
||||
});
|
||||
check("카드 높이 = 합친 칸 높이", fill < 2, fill);
|
||||
await p.screenshot({ path: path.join(__dirname, ".out", "live_merge.png") });
|
||||
// 이미지 링크에 마우스 → 오른쪽 달력 아래 미리보기, 벗어나면 숨김
|
||||
const imgLink = p.locator('td[data-day="2026-11-05"][data-start="06:00"] a[data-preview]');
|
||||
check("미리보기 처음엔 숨김", await p.locator("#lv-preview").isHidden());
|
||||
await imgLink.hover();
|
||||
await p.waitForTimeout(200);
|
||||
const pv = await p.evaluate(function () {
|
||||
const box = document.getElementById("lv-preview"), cal = document.getElementById("lv-side-cal").getBoundingClientRect(), b = box.getBoundingClientRect();
|
||||
const img = box.querySelector("img");
|
||||
return { hidden: box.hidden, src: img.getAttribute("src"), loaded: img.naturalWidth > 0, cap: box.querySelector("figcaption").textContent,
|
||||
below: b.top >= cal.bottom, sameCol: Math.abs(b.left - cal.left) < 2 && Math.abs(b.width - cal.width) < 2, bottom: b.bottom <= window.innerHeight };
|
||||
});
|
||||
check("이미지 링크에 마우스 = 달력 아래 미리보기", !pv.hidden && pv.src === "/live/images/7" && pv.loaded && pv.below && pv.sameCol && pv.bottom && pv.cap.includes("1/2"), pv);
|
||||
await p.screenshot({ path: path.join(__dirname, ".out", "live_preview.png") });
|
||||
await p.mouse.move(5, 5);
|
||||
await p.waitForTimeout(100);
|
||||
check("벗어나면 숨김", await p.locator("#lv-preview").isHidden());
|
||||
// 이미지 링크 클릭 = 화면 가운데 보기 창, 원본 크기, 회전, 다운로드, 앞뒤
|
||||
await imgLink.click();
|
||||
await p.waitForTimeout(300);
|
||||
const v = function () {
|
||||
return p.evaluate(function () {
|
||||
const d = document.getElementById("lv-viewer"), b = d.getBoundingClientRect(), img = d.querySelector("img"), st = d.querySelector(".lv-viewer-stage");
|
||||
const dl = d.querySelector("[data-download]");
|
||||
return { open: d.open, cx: Math.round(b.left + b.width / 2 - innerWidth / 2), cy: Math.round(b.top + b.height / 2 - innerHeight / 2),
|
||||
src: img.getAttribute("src"), natural: img.naturalWidth + "x" + img.naturalHeight, shown: Math.round(img.getBoundingClientRect().width) + "x" + Math.round(img.getBoundingClientRect().height),
|
||||
stage: st.style.width + "x" + st.style.height, dl: dl.getAttribute("href") + "|" + dl.download, count: d.querySelector(".lv-viewer-count").textContent };
|
||||
});
|
||||
};
|
||||
let s = await v();
|
||||
check("클릭 = 가운데 보기 창", s.open && Math.abs(s.cx) <= 1 && Math.abs(s.cy) <= 1, s);
|
||||
check("원본 크기", s.natural === "1566x459" && s.shown === "1566x459" && s.stage === "1566pxx459px", s);
|
||||
check("다운로드 = 원본·파일 이름", s.dl === "/live/images/7|r.png" && s.count === "1 / 2", s);
|
||||
await p.screenshot({ path: path.join(__dirname, ".out", "live_viewer.png") });
|
||||
await p.locator("#lv-viewer [data-rotate]").click();
|
||||
s = await v();
|
||||
check("회전 = 무대 가로세로 바뀜, 이미지 90°", s.stage === "459pxx1566px" && s.shown === "459x1566", s);
|
||||
await p.screenshot({ path: path.join(__dirname, ".out", "live_viewer_rot.png") });
|
||||
await p.locator('#lv-viewer [data-step="1"]').click();
|
||||
await p.waitForTimeout(200);
|
||||
s = await v();
|
||||
check("다음 이미지 = 회전 처음으로", s.src === "/live/images/8" && s.count === "2 / 2" && s.stage === "1566pxx459px" && s.dl.endsWith("|s.png"), s);
|
||||
await p.locator("#lv-viewer [data-viewer-close]").click();
|
||||
check("닫기", !(await v()).open);
|
||||
|
||||
await p.locator('#lv-side-cal [data-nav="1"]').click();
|
||||
await Promise.all([p.waitForURL(/month=2026-12/), day("2026-12-10").click()]);
|
||||
await p.waitForTimeout(300);
|
||||
check("다른 달 = 그 달 화면에서 맨 왼쪽", (await gap("2026-12-10")) < 2, await gap("2026-12-10"));
|
||||
check("크리스마스 표시", (await day("2026-12-25").getAttribute("title")) === "크리스마스");
|
||||
|
||||
await p.goto("http://erp.test/live_cal_en.html");
|
||||
await p.waitForTimeout(300);
|
||||
const text = await p.locator("#lv-side-cal").innerText();
|
||||
check("영문 화면 = 달력도 영어", !/[가-힣]/.test(text) && text.includes("November 2026") && text.includes("Sun") && text.includes("Replacement"), text);
|
||||
check("영문 말풍선", (await day("2026-11-09").getAttribute("title")) === "Deepavali (Replacement)");
|
||||
// 스케줄표 — 머리글 가운데·굵게·검정·12px × 1.12, 첫 열 = 쇼핑몰 아이콘
|
||||
await p.goto("http://erp.test/live_table_en.html");
|
||||
await p.waitForTimeout(300);
|
||||
const head = await p.evaluate(function () {
|
||||
const ths = Array.from(document.querySelectorAll(".lv-sched thead th")), c = getComputedStyle(ths[5]); // 5 = 금액 열(전엔 오른쪽 정렬)
|
||||
const img = document.querySelector(".lv-sched tbody tr td img.lv-pf");
|
||||
return [ths[0].textContent, c.textAlign, c.fontWeight, c.color, c.fontSize, img && img.naturalWidth, img && img.alt].join("|");
|
||||
});
|
||||
check("스케줄표 머리글·쇼핑몰 열", head === "Platform|center|700|rgb(0, 0, 0)|13.44px|64|TikTok", head);
|
||||
await p.screenshot({ path: path.join(__dirname, ".out", "live_table.png") });
|
||||
// 방송 창이 애니메이션으로 나타남(추가·고치기 같은 창), 움직임 줄이기 설정이면 없음
|
||||
await p.goto("http://erp.test/live/calendar?month=2026-11");
|
||||
await p.waitForTimeout(200);
|
||||
const anim = function () { return p.locator("#lv-dlg").evaluate(function (el) { const c = getComputedStyle(el); return c.animationName + "|" + c.animationDuration; }); };
|
||||
await p.locator("#lv-add").click();
|
||||
check("추가 창 애니메이션", (await anim()) === "lv-dlg-in|0.2s", await anim());
|
||||
await p.waitForTimeout(300);
|
||||
const opened = await p.locator("#lv-dlg").evaluate(function (el) { const c = getComputedStyle(el); return c.opacity + "|" + c.transform; });
|
||||
check("끝나면 제자리", opened === "1|none", opened);
|
||||
await p.screenshot({ path: path.join(__dirname, ".out", "live_dialog.png") });
|
||||
await p.locator("#lv-dlg [data-close]").click();
|
||||
await p.locator(".lv-card-edit").first().click();
|
||||
check("고치기 창 애니메이션", (await anim()) === "lv-dlg-in|0.2s", await anim());
|
||||
// 카드 머리 왼쪽 = 호스트 쇼핑몰 아이콘(예전 ✥ 없음), 쇼핑몰 없는 호스트 = 아이콘 없음
|
||||
const pf = await p.evaluate(function () {
|
||||
const icon = function (id) { const i = document.querySelector('[data-card="' + id + '"] .lv-card-pf'); return i ? i.getAttribute("src").split("/").pop() + ":" + i.naturalWidth + ":" + Math.round(i.getBoundingClientRect().width) : "-"; };
|
||||
return [icon(6), icon(8), icon(22), document.body.textContent.indexOf("✥") < 0].join("|");
|
||||
});
|
||||
check("카드 쇼핑몰 아이콘", pf === "live-icon-tiktok.png:64:12|live-icon-shopee.png:64:12|-|true", pf);
|
||||
// Fee(시간 × 25)·커미션(판매금액 10%) 자동, 광고비·호스트 비용 = 저장한 값, 방송 장소 없음(2026-11-06)
|
||||
const fees = function () { return p.locator("#lv-dlg").evaluate(function (d) {
|
||||
const q = function (s) { return d.querySelector(s).value; };
|
||||
return [q("[data-fee]"), q("[data-commission]"), q('[name="ad_spend"]'), q('[name="host_fee"]'), !!d.querySelector('[name="venue"]')].join("|");
|
||||
}); };
|
||||
check("고치기 창 금액", (await fees()) === "50.00|50.00|100.00|50.00|false", await fees());
|
||||
await p.locator('#lv-dlg [name="sales_amount"]').fill("RM 1,234.5");
|
||||
await p.locator('#lv-dlg [name="end_time"]').fill("08:30");
|
||||
check("판매금액·끝 시간 바꾸면 다시 계산", (await fees()) === "62.50|123.45|100.00|50.00|false", await fees());
|
||||
await p.screenshot({ path: path.join(__dirname, ".out", "live_dialog_fees.png") });
|
||||
await p.locator("#lv-dlg [data-close]").click();
|
||||
await p.emulateMedia({ reducedMotion: "reduce" });
|
||||
await p.locator("#lv-add").click();
|
||||
check("움직임 줄이기 = 없음", (await anim()).startsWith("none"), await anim());
|
||||
await p.emulateMedia({ reducedMotion: "no-preference" });
|
||||
check("스크립트 오류 없음", errors.length === 0, errors);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
if (fails.length) { console.log("\n" + fails.length + " FAILED"); process.exit(1); }
|
||||
console.log("\nALL OK");
|
||||
})();
|
||||
@@ -0,0 +1,105 @@
|
||||
// 실적 일자별 표 열 접기(2026-11-06) — 실제 브라우저(Chromium).
|
||||
// python tests/js/render_performance.py
|
||||
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/perf_colfold.browser.test.js
|
||||
// 머리글 위 버튼(.perf-cfold)으로 열 하나 접기/펴기(날짜 열 빼고) → 26px 띠, 칸 내용 숨김, PUT /api/my-col-fold {kind, cols}.
|
||||
// 서버가 그린 data-col-fold(그 사람 저장값)로 처음부터 접힘. 수동 열 너비 표에서도 같은 26px. 매출 실적·광고비 둘 다.
|
||||
const fs = require("fs"), path = require("path");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const fails = [];
|
||||
function check(name, cond, extra) {
|
||||
if (cond) console.log("PASS " + name);
|
||||
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
|
||||
}
|
||||
function route(p, file, folded, puts) {
|
||||
return p.route("**/*", function (r) {
|
||||
const url = new URL(r.request().url()).pathname;
|
||||
if (url.startsWith("/static/")) {
|
||||
const f = path.join(ROOT, "app", url);
|
||||
if (!fs.existsSync(f)) return r.fulfill({ status: 404, body: "" });
|
||||
return r.fulfill({ status: 200, contentType: f.endsWith(".css") ? "text/css" : "application/javascript", body: fs.readFileSync(f) });
|
||||
}
|
||||
if (url.includes("/api/")) {
|
||||
if (url.endsWith("/api/my-col-fold")) puts.push(JSON.parse(r.request().postData()));
|
||||
return r.fulfill({ status: 200, contentType: "application/json", body: "{}" });
|
||||
}
|
||||
const html = fs.readFileSync(path.join(__dirname, ".out", file), "utf8")
|
||||
.replace('data-col-fold="[]"', 'data-col-fold="' + JSON.stringify(folded).replace(/"/g, """) + '"');
|
||||
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: html });
|
||||
});
|
||||
}
|
||||
function state(p, col) {
|
||||
return p.evaluate(function (col) {
|
||||
const t = document.querySelector("table.perf-main"), th = t.querySelector('thead th[data-col="' + col + '"]');
|
||||
const i = th.cellIndex, cells = Array.from(t.tBodies[0].rows).map(function (r) { return r.cells[i]; });
|
||||
const btn = th.querySelector(".perf-cfold");
|
||||
return { w: Math.round(th.getBoundingClientRect().width), folded: th.classList.contains("is-cfold"),
|
||||
allCells: cells.every(function (c) { return c.classList.contains("is-cfold"); }),
|
||||
cellW: Math.round(cells[1].getBoundingClientRect().width), text: cells[1].innerText.trim(),
|
||||
expanded: btn && btn.getAttribute("aria-expanded"), buttons: t.querySelectorAll(".perf-cfold").length,
|
||||
labelBtn: !!t.querySelector('th[data-col="label"] .perf-cfold'), heads: t.tHead.rows[0].cells.length };
|
||||
}, col);
|
||||
}
|
||||
|
||||
(async function () {
|
||||
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
|
||||
try {
|
||||
for (const [file, kind] of [["perf_dash_shell.html", "sales"], ["perf_ads_shell.html", "ads"], ["perf_dash_colw_shell.html", "sales"]]) {
|
||||
const tag = "[" + file + "] ";
|
||||
const puts = [];
|
||||
const ctx = await browser.newContext({ viewport: { width: 1400, height: 800 } });
|
||||
const p = await ctx.newPage();
|
||||
await route(p, file, [], puts);
|
||||
await p.goto("http://perf.test/performance/");
|
||||
await p.waitForTimeout(150);
|
||||
const col = await p.evaluate(function () { // 접어 볼 열 = 일 합계 다음 첫 열
|
||||
return document.querySelector("table.perf-main").tHead.rows[0].cells[2].dataset.col;
|
||||
});
|
||||
const s0 = await state(p, col);
|
||||
check(tag + "날짜 열 빼고 열마다 버튼, 처음엔 펼침", s0.buttons === s0.heads - 1 && !s0.labelBtn && !s0.folded && s0.expanded === "true", s0);
|
||||
// 말풍선 — 버튼 위에 올리면 커서 바로 위에 열 이름(제목 글자 크기 12px), 커서 따라 움직임, 머리글 기본 말풍선(title) 없음
|
||||
const bb = await p.locator('thead th[data-col="' + col + '"] .perf-cfold').boundingBox();
|
||||
await p.mouse.move(bb.x + 4, bb.y + bb.height / 2);
|
||||
await p.mouse.move(bb.x + bb.width - 4, bb.y + bb.height / 2);
|
||||
const tip = await p.evaluate(function (col) {
|
||||
const t = document.querySelector(".perf-cfold-tip"), b = document.querySelector('thead th[data-col="' + col + '"] .perf-cfold');
|
||||
const head = document.querySelector('thead th[data-col="' + col + '"]');
|
||||
if (!t) return null;
|
||||
const r = t.getBoundingClientRect();
|
||||
return { text: t.textContent, name: head.textContent.replace(/[✎\s]+/g, " ").trim(), size: getComputedStyle(t).fontSize,
|
||||
headSize: getComputedStyle(head).fontSize, cx: Math.round(r.left + r.width / 2), bottom: Math.round(r.bottom), title: b.getAttribute("title") };
|
||||
}, col);
|
||||
const cursorX = Math.round(bb.x + bb.width - 4), cursorY = bb.y + bb.height / 2;
|
||||
check(tag + "말풍선 = 열 이름, 제목 글자 크기, 커서 위를 따라감", tip && tip.text === tip.name && tip.text !== "" && tip.size === tip.headSize &&
|
||||
Math.abs(tip.cx - cursorX) <= 1 && tip.bottom < cursorY && tip.title === "", tip);
|
||||
await p.mouse.move(5, 5);
|
||||
check(tag + "벗어나면 말풍선 닫힘", (await p.locator(".perf-cfold-tip").count()) === 0);
|
||||
await p.click('thead th[data-col="' + col + '"] .perf-cfold');
|
||||
await p.waitForTimeout(100);
|
||||
const s1 = await state(p, col);
|
||||
check(tag + "누르면 26px 띠로 접힘(칸 내용 숨김)", s1.folded && s1.allCells && s1.w === 26 && s1.cellW === 26 && s1.text === "" && s1.expanded === "false", s1);
|
||||
check(tag + "PUT /api/my-col-fold {kind, cols}", puts.length === 1 && puts[0].kind === kind && JSON.stringify(puts[0].cols) === JSON.stringify([col]), puts);
|
||||
await p.click('thead th[data-col="' + col + '"] .perf-cfold');
|
||||
await p.waitForTimeout(100);
|
||||
const s2 = await state(p, col);
|
||||
check(tag + "다시 누르면 원래 너비로", !s2.folded && Math.abs(s2.w - s0.w) <= 1 && s2.text !== "", { s0: s0, s2: s2 });
|
||||
check(tag + "펼친 것도 저장(빈 목록)", puts.length === 2 && puts[1].cols.length === 0, puts);
|
||||
await ctx.close();
|
||||
|
||||
// 서버가 그린 저장값(data-col-fold)으로 처음부터 접힘
|
||||
const ctx2 = await browser.newContext({ viewport: { width: 1400, height: 800 } });
|
||||
const q = await ctx2.newPage();
|
||||
await route(q, file, [col, "total"], []);
|
||||
await q.goto("http://perf.test/performance/");
|
||||
await q.waitForTimeout(150);
|
||||
const s3 = await state(q, col), t3 = await state(q, "total");
|
||||
check(tag + "저장값대로 처음부터 접힘(일 합계 포함)", s3.folded && s3.w === 26 && t3.folded && t3.w === 26, { s3: s3, t3: t3 });
|
||||
if (file === "perf_dash_shell.html") await q.screenshot({ path: path.join(__dirname, ".out", "perf_colfold.png") });
|
||||
await ctx2.close();
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
console.log(fails.length ? "\n" + fails.length + " FAIL" : "\nALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
})();
|
||||
@@ -0,0 +1,63 @@
|
||||
// 실적 틱톡 탭(2026-11-05) — 실제 브라우저(Chromium).
|
||||
// python tests/js/render_performance.py
|
||||
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/perf_tiktok.browser.test.js
|
||||
// 광고비 오른쪽 탭, ROAS·광고비·매출 열, 매출·광고비 그래프 둘, 합계 줄 스크롤 고정, 칸 입력 없음, 스크립트 오류 없음.
|
||||
const fs = require("fs"), path = require("path");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const fails = [];
|
||||
function check(name, cond, extra) {
|
||||
if (cond) console.log("PASS " + name);
|
||||
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
|
||||
}
|
||||
|
||||
(async function () {
|
||||
const exe = process.env.PJ_TEST_BROWSER;
|
||||
const browser = await chromium.launch(exe ? { executablePath: exe } : {});
|
||||
try {
|
||||
const p = await (await browser.newContext({ viewport: { width: 1400, height: 800 } })).newPage();
|
||||
const errors = [];
|
||||
p.on("pageerror", function (e) { errors.push(String(e)); });
|
||||
await p.route("**/*", function (r) {
|
||||
const url = new URL(r.request().url()).pathname;
|
||||
if (url.startsWith("/static/")) {
|
||||
const f = path.join(ROOT, "app", url);
|
||||
if (!fs.existsSync(f)) return r.fulfill({ status: 404, body: "" });
|
||||
const type = f.endsWith(".css") ? "text/css" : f.endsWith(".js") ? "application/javascript" : "font/woff2";
|
||||
return r.fulfill({ status: 200, contentType: type, body: fs.readFileSync(f) });
|
||||
}
|
||||
if (!url.endsWith(".html")) return r.fulfill({ status: 200, contentType: "application/json", body: "{}" });
|
||||
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fs.readFileSync(path.join(__dirname, ".out", url.slice(1)), "utf8") });
|
||||
});
|
||||
await p.goto("http://erp.test/perf_tiktok_shell.html");
|
||||
await p.waitForTimeout(300);
|
||||
const tabs = await p.locator(".perf-tabs-main .perf-tab").allInnerTexts();
|
||||
check("탭 순서 = 매출 실적·광고비·틱톡", tabs.map(function (t) { return t.replace(/^[a-z_]+\s*/, "").trim(); }).join() === "매출 실적,광고비,틱톡", tabs);
|
||||
check("틱톡 탭이 켜짐", await p.locator(".perf-tab-tiktok.is-active").count() === 1);
|
||||
const head = await p.locator("table.perf-main thead th").allInnerTexts();
|
||||
check("열 = 날짜·ROAS·광고비·매출", head.join() === "날짜,ROAS,광고비,매출", head);
|
||||
const total = await p.locator("table.perf-main tbody tr").first().innerText();
|
||||
check("맨 위 기간 합계", total.includes("합계") && total.includes("210,000") && total.includes("630,000") && total.includes("300%"), total);
|
||||
const day = await p.locator("table.perf-main tbody tr", { hasText: "400%" }).first().innerText();
|
||||
check("일자 줄 값", day.includes("120,000") && day.includes("480,000"), day);
|
||||
check("매출 그래프", await p.locator("#perf-chart-daily svg rect.bar").count() > 0);
|
||||
check("광고비 그래프", await p.locator("#perf-chart-daily2 svg rect.bar").count() > 0);
|
||||
check("칸 입력 없음", await p.locator("[data-manual-code]").count() === 0);
|
||||
check("업데이트 버튼", (await p.locator("#perf-ad-sync-btn").innerText()).includes("광고비 업데이트"));
|
||||
await p.screenshot({ path: path.join(__dirname, ".out", "perf_tiktok.png") });
|
||||
await p.locator("table.perf-main").hover();
|
||||
await p.mouse.wheel(0, 500);
|
||||
await p.waitForTimeout(250);
|
||||
const stuck = await p.evaluate(function () {
|
||||
const first = document.querySelector("table.perf-main tbody tr.perf-row-total:first-child th");
|
||||
const top = first.getBoundingClientRect().top;
|
||||
return document.querySelector("table.perf-main thead th").getBoundingClientRect().bottom <= top + 2 && top >= 0 && top < 300;
|
||||
});
|
||||
check("스크롤해도 제목·합계 줄 고정", stuck);
|
||||
check("스크립트 오류 없음", errors.length === 0, errors);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
if (fails.length) { console.log("\n" + fails.length + " FAILED"); process.exit(1); }
|
||||
console.log("\nALL OK");
|
||||
})();
|
||||
@@ -0,0 +1,52 @@
|
||||
"""입출고 날짜 칸 화면을 진짜 ERP 셸(erp_base.html)로 렌더 — 공용 달력 브라우저 테스트용(2026-11-05).
|
||||
|
||||
python tests/js/render_inout.py # → tests/js/.out/inout_form.html · inout_list.html · inout_locked.html
|
||||
|
||||
DB 없이 날짜 칸에 필요한 값만 넣는다(나머지 값은 비어 있음 — ChainableUndefined). 공휴일 = 실제 표.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import date
|
||||
|
||||
import jinja2
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.path.insert(0, ROOT)
|
||||
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
|
||||
|
||||
from app.modules.inout.router import _date_holidays # noqa: E402
|
||||
|
||||
|
||||
def _order(no: int, receipt_dates: list[date]) -> dict:
|
||||
return {"id": no, "order_no": f"PO-26102{no}-01", "factory_name": "대성화학", "items_label": "미라클 봉투", "line_count": 1,
|
||||
"order_date": date(2026, 10, 20), "due_date": None, "receipt_dates": receipt_dates, "status": "partial", "status_label": "일부 입고",
|
||||
"summary": {"ordered": 100, "received": 10, "remaining": 90, "over": 0}}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
env = jinja2.Environment(
|
||||
loader=jinja2.FileSystemLoader([os.path.join(ROOT, "app", "templates"), os.path.join(ROOT, "app", "modules", "inout", "templates")]),
|
||||
autoescape=True, undefined=jinja2.ChainableUndefined)
|
||||
base = {"date_holidays": _date_holidays(), "today": date(2026, 10, 5), "user": {"name": "테스트", "email": "t@test.local"}, "nav_items": [], "perms": {"can_order": True, "can_receive": True}}
|
||||
pages = {
|
||||
"inout_form.html": ("inout/order_form.html", {"vals": {"order_date": "2026-10-05", "due_date": ""}, "factories": []}),
|
||||
"inout_list.html": ("inout/index.html", {"filters": {"from": "2026-10-01", "to": "", "status": "open", "q": "", "factory": ""}, "factories": [], "status_filters": {}, "orders": [
|
||||
_order(1, [date(2026, 10, 21), date(2026, 10, 23)]), _order(2, [date(2026, 10, 22)]), _order(3, [])]}),
|
||||
}
|
||||
for out, (name, ctx) in pages.items():
|
||||
with open(os.path.join(OUT_DIR, out), "w", encoding="utf-8") as f:
|
||||
f.write(env.get_template(name).render(**base, **ctx))
|
||||
# 입고 칸만 — order_detail.html 은 값이 많아, 전체 입고 완료로 잠긴 입고일 칸(disabled)을 같은 스크립트로 확인
|
||||
locked = env.from_string('{% extends "erp_base.html" %}{% block head_extra %}<link rel="stylesheet" href="/static/inout.css" />{% endblock %}'
|
||||
'{% block content %}<section class="io"><input type="date" name="receipt_date" value="2026-10-05" aria-label="입고일" required disabled /></section>{% endblock %}'
|
||||
'{% block scripts %}{% include "inout/_datepop.html" %}<script src="/static/inout.js" defer></script>{% endblock %}')
|
||||
with open(os.path.join(OUT_DIR, "inout_locked.html"), "w", encoding="utf-8") as f:
|
||||
f.write(locked.render(**base))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,69 @@
|
||||
"""라이브 커머스 달력 보기를 진짜 앱 라우터로 렌더 — 오른쪽 달력 브라우저 테스트용(2026-11-05).
|
||||
|
||||
python tests/js/render_live.py # → tests/js/.out/live_cal_ko.html · live_cal_en.html · live_cal_dec.html
|
||||
|
||||
DB 없이 가짜 저장소로 11월·12월 화면을 그린다(공휴일 = 실제 표).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from datetime import date, time
|
||||
from decimal import Decimal
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.path.insert(0, ROOT)
|
||||
os.chdir(ROOT)
|
||||
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
|
||||
for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE", "MALAYSIA_STOCK", "ITEMCODE", "EXPENSE", "INOUT", "OUTREACH", "LIVE"):
|
||||
os.environ[key + "_DB_URL"] = ""
|
||||
os.environ.update(SESSION_SECRET_KEY="local-live-test-only", SESSION_COOKIE_SECURE="false", PERFORMANCE_AUTO_SYNC="false", DATA_DIR=tempfile.mkdtemp())
|
||||
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
import app.main as main # noqa: E402
|
||||
|
||||
|
||||
class Fake:
|
||||
def host_choices(self):
|
||||
return [{"id": 1, "display_name": "Nabella", "full_name": "Nazzureen Nabella binti Samad", "is_active": True}]
|
||||
|
||||
def list_broadcasts(self, start, end):
|
||||
if start.month != 11:
|
||||
return []
|
||||
# 운영 화면처럼 — 6·8·16시 칸에 카드(세 줄 모두 카드가 있으면 그 줄이 가장 높다), 모든 시간 칸을 채워 높이 최악으로
|
||||
return [{"id": h, "host_id": 1, "host_name": "Nabella", "host_platform": "tiktok" if h != 8 else "shopee", "tiktok_handle": "MainAccount", "broadcast_date": date(2026, 11, 5), "start_time": time(h),
|
||||
"end_time": time(h + 2), "venue": "", "sales_amount": Decimal("500"), "ad_spend": Decimal("100"), "host_fee": Decimal("50"),
|
||||
"images": [{"id": 7, "filename": "r.png"}, {"id": 8, "filename": "s.png"}] if h == 6 else []} for h in range(6, 24, 2) if h < 22] + \
|
||||
[{"id": 22, "host_id": 1, "host_name": "Nabella", "host_platform": "", "tiktok_handle": "MainAccount", "broadcast_date": date(2026, 11, 5), "start_time": time(22),
|
||||
"end_time": time(23, 30), "venue": "", "sales_amount": Decimal("500"), "ad_spend": None, "host_fee": None, "images": []}]
|
||||
|
||||
def broadcast_days(self, start, end):
|
||||
return ["2026-10-30", "2026-11-05", "2026-11-20", "2026-12-03"] # 오른쪽 달력 점 — 다른 달 날짜도
|
||||
|
||||
def account_choices(self):
|
||||
return ["MainAccount"]
|
||||
|
||||
|
||||
def main_() -> None:
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
main.app.state.live_store = Fake()
|
||||
user = {"email": "t@test.local", "name": "T", "role": "user", "is_super_admin": False, "modules": {"live": True}}
|
||||
with patch.object(main, "get_current_user_record", side_effect=lambda r: user), patch.object(main, "get_session_user", side_effect=lambda r: user), \
|
||||
patch.object(main.user_store, "get", side_effect=lambda e: user), patch.object(main.user_store, "list_all", side_effect=lambda: [user]):
|
||||
for name, lang, url in (("live_cal_ko.html", "ko", "/live/calendar?month=2026-11"), ("live_cal_en.html", "en", "/live/calendar?month=2026-11"),
|
||||
("live_cal_dec.html", "ko", "/live/calendar?month=2026-12"), ("live_table_en.html", "en", "/live/?month=2026-11")):
|
||||
client = TestClient(main.app)
|
||||
client.cookies.set("live_lang", lang)
|
||||
res = client.get(url)
|
||||
assert res.status_code == 200, (name, res.status_code)
|
||||
with open(os.path.join(OUT_DIR, name), "w", encoding="utf-8") as f:
|
||||
f.write(res.text)
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main_()
|
||||
@@ -19,7 +19,7 @@ ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)
|
||||
sys.path.insert(0, ROOT)
|
||||
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
|
||||
|
||||
from app.modules.performance.ad_spend import build_ad_dashboard # noqa: E402
|
||||
from app.modules.performance.ad_spend import build_ad_dashboard, build_tiktok_dashboard # noqa: E402
|
||||
from app.modules.performance.dashboard import amount_text, build_dashboard, build_settings # noqa: E402
|
||||
from app.modules.performance.router import _auto_sync_settings_ctx # noqa: E402
|
||||
|
||||
@@ -84,6 +84,12 @@ def env() -> jinja2.Environment:
|
||||
return e
|
||||
|
||||
|
||||
class TiktokStore:
|
||||
def ad_details(self, code, start, end):
|
||||
rows = [("2026-10-02", 120000, 480000), ("2026-10-05", 90000, 150000), ("2026-09-20", 50000, 100000)]
|
||||
return [{"date": d, "amount": a, "roas": None, "metrics": {"매출": b}, "source": "api"} for d, a, b in rows]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
e = env()
|
||||
@@ -117,6 +123,12 @@ def main() -> None:
|
||||
html = shell.get_template("performance/ads.html").render(**sbase, active_tab="ads", **sactx)
|
||||
with open(os.path.join(OUT_DIR, "perf_ads_shell.html"), "w", encoding="utf-8") as f:
|
||||
f.write(html)
|
||||
# 틱톡 탭(2026-11-05) — 가상의 광고 API 값
|
||||
tk = build_tiktok_dashboard(TiktokStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7), holidays={"2026-10-03": "개천절"})
|
||||
tk.update(auto_sync=ctx["auto_sync"], update_watch={"kind": "ads", "seen": "job-old"}, tiktok_configured=True, ad_running=False,
|
||||
ad_last_update_at=None, ad_sync_sources=[{"code": "tiktok", "name": "틱톡"}])
|
||||
with open(os.path.join(OUT_DIR, "perf_tiktok_shell.html"), "w", encoding="utf-8") as f:
|
||||
f.write(shell.get_template("performance/tiktok.html").render(**sbase, active_tab="tiktok", **tk))
|
||||
actx =build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
|
||||
sales_codes=["cafe24", "coupang"])
|
||||
actx["ad_sync_sources"] = [{"code": "google", "name": "구글 광고"}] # [구글 광고 불러오기]
|
||||
|
||||
+99
-11
@@ -492,6 +492,55 @@ def test_route_09_variants_partial_success():
|
||||
assert resp.status_code == 502
|
||||
|
||||
|
||||
def test_route_09b_display_selling_to_all_shops(monkeypatch):
|
||||
monkeypatch.setenv("CAFE24_SHOP_NOS", "1,2,3")
|
||||
no, cafe = _new_product()
|
||||
created = _create_options(no, ["A", "B"])
|
||||
a, b = (v["variant_code"] for v in created["variants"])
|
||||
cafe.calls.clear()
|
||||
resp = req("PUT", f"/cafe24/products/{no}/variants", json={"rows": [
|
||||
{"variant_code": a, "display": "off", "additional_amount": "500"},
|
||||
{"variant_code": b, "custom_variant_code": "X1"}]})
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["shop_failed"] == {}
|
||||
puts = [c[2] for c in cafe.calls if c[0] == "PUT" and c[1].endswith("/variants")]
|
||||
assert [p["shop_no"] for p in puts] == [1, 2, 3]
|
||||
# 다른 쇼핑몰엔 진열·판매만, 진열/판매를 안 바꾼 행(b)은 안 보낸다
|
||||
assert puts[1]["requests"] == puts[2]["requests"] == [{"variant_code": a, "display": "F"}]
|
||||
# 다른 쇼핑몰 실패는 경고로만(기본몰 반영은 성공)
|
||||
cafe._variant_puts = 0
|
||||
cafe.fail_variant_chunk = 2
|
||||
resp = req("PUT", f"/cafe24/products/{no}/variants", json={"rows": [{"variant_code": a, "selling": "off"}]})
|
||||
cafe.fail_variant_chunk = 0
|
||||
assert resp.status_code == 200 and resp.json()["ok"]
|
||||
assert list(resp.json()["shop_failed"]) == ["2"]
|
||||
|
||||
|
||||
def test_sync_variant_flags_script(monkeypatch, capsys):
|
||||
from app.integrations import cafe24 as integ
|
||||
from app.integrations.cafe24 import products as cp
|
||||
from app.modules.cafe24 import sync_variant_flags
|
||||
|
||||
no, cafe = _new_product()
|
||||
created = _create_options(no, ["A", "B"])
|
||||
a = created["variants"][0]["variant_code"]
|
||||
before = [dict(v) for v in cafe.variants]
|
||||
assert req("PUT", f"/cafe24/products/{no}/variants",
|
||||
json={"rows": [{"variant_code": a, "display": "off"}]}).status_code == 200
|
||||
cafe.stale_variants = before # 다른 쇼핑몰(과 지연된 GET)은 아직 진열함
|
||||
monkeypatch.setenv("CAFE24_DB_URL", os.environ["CAFE24_TEST_DB_URL"])
|
||||
monkeypatch.setattr(integ, "build_cafe24_api", lambda st, **kw: fakes.FakeApi(MULTI))
|
||||
monkeypatch.setattr(cp, "list_all_products", lambda client: ([{"product_no": no}], False))
|
||||
|
||||
cafe.calls.clear()
|
||||
assert sync_variant_flags.main(["--shops", "3"]) == 0
|
||||
assert not [c for c in cafe.calls if c[0] == "PUT"] # 미리보기는 쓰지 않음
|
||||
assert sync_variant_flags.main(["--shops", "3", "--apply"]) == 0
|
||||
puts = [c[2] for c in cafe.calls if c[0] == "PUT"]
|
||||
assert puts == [{"shop_no": 3, "requests": [{"variant_code": a, "display": "F"}]}]
|
||||
assert "BEFORE" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_route_10_rename_with_lagging_variants_keeps_rows():
|
||||
no, cafe = _new_product()
|
||||
created = _create_options(no, ["Black", "Red"])
|
||||
@@ -519,20 +568,15 @@ def test_route_10_rename_with_lagging_variants_keeps_rows():
|
||||
assert created["variants"]
|
||||
|
||||
|
||||
def test_route_08_appended_value_pending_until_variant_appears():
|
||||
def test_route_08_append_value_rejected_before_put():
|
||||
# 카페24 PUT 은 옵션값 추가를 오류 없이 무시한다 — "저장했는데 사라짐" 대신 400 으로 재생성 안내.
|
||||
no, cafe = _new_product()
|
||||
_create_options(no, ["A"])
|
||||
cafe.hidden_variants = 99 # 새 품목이 한동안 안 보인다
|
||||
puts = len([c for c in cafe.calls if c[0] == "PUT"])
|
||||
resp = req("PUT", f"/cafe24/products/{no}/options", json={"options": [{
|
||||
"option_name": "구성", "option_value": [{"option_text": "A"}, {"option_text": "B"}]}]}).json()
|
||||
values = resp["option"]["options"][0]["option_value"]
|
||||
assert values[1]["option_text"] == "B" and values[1]["pending"] is True
|
||||
got = req("GET", f"/cafe24/products/{no}/options").json()
|
||||
assert got["option"]["options"][0]["option_value"][1]["pending"] is True
|
||||
cafe.hidden_variants = 0
|
||||
got = req("GET", f"/cafe24/products/{no}/options").json()
|
||||
assert got["option"]["options"][0]["option_value"][1]["pending"] is False
|
||||
assert len(got["variants"]) == 2
|
||||
"option_name": "구성", "option_value": [{"option_text": "A"}, {"option_text": "B"}]}]})
|
||||
assert resp.status_code == 400 and "옵션 재생성" in resp.text, resp.text
|
||||
assert len([c for c in cafe.calls if c[0] == "PUT"]) == puts
|
||||
|
||||
|
||||
def test_route_11_deleted_variant_stays_hidden():
|
||||
@@ -588,6 +632,50 @@ def test_worker_real_db_success_and_needs_review():
|
||||
assert q("SELECT status FROM cafe24_write_attempts WHERE schedule_id=%s", sid2)[0]["status"] == "RECORDED"
|
||||
|
||||
|
||||
def test_schedule_main_image_route_and_worker():
|
||||
"""대표 이미지 예약(006): 등록 → 파일 DB 보관 → 그 시각에 worker 가 교체 → 목록 미리보기."""
|
||||
no, cafe = _new_product("<p>A</p>")
|
||||
at = (now_kst() + timedelta(days=1)).strftime("%Y-%m-%dT%H:%M")
|
||||
png = b"\x89PNG\r\n\x1a\n" + b"x" * 64
|
||||
form = {"product_no": str(no), "scheduled_at": at, "set_display": "", "set_selling": ""}
|
||||
# 내용 없는 예약(이미지도 안 고름 — 이름 없는 빈 파트) 거부
|
||||
resp = req("POST", "/cafe24/schedules", data=form, files={"image": ("", b"", "application/octet-stream")})
|
||||
assert "하나 이상" in _location(resp).get("err", ""), resp.headers
|
||||
# 이미지 아닌 파일 거부
|
||||
resp = req("POST", "/cafe24/schedules", data=form, files={"image": ("a.txt", b"hi", "text/plain")})
|
||||
assert "이미지만" in _location(resp).get("err", ""), resp.headers
|
||||
resp = req("POST", "/cafe24/schedules", data=form, files={"image": ("가을.png", png, "image/png")})
|
||||
assert "대표이미지" in _location(resp).get("msg", ""), resp.headers
|
||||
sid = q("SELECT id FROM cafe24_product_schedules WHERE product_no=%s", no)[0]["id"]
|
||||
row = ST.get_schedule(sid)
|
||||
assert row["image_type"] == "image/png" and row["image_name"] == "가을.png" and row["revision_id"] is None
|
||||
got = req("GET", f"/cafe24/schedules/{sid}/image")
|
||||
assert got.status_code == 200 and got.content == png and got.headers["content-type"] == "image/png"
|
||||
listed = json.loads(req("GET", "/cafe24/schedules").text.split("\n", 1)[1])["rows"]
|
||||
mine = [r for r in listed if r["id"] == sid][0]
|
||||
assert mine["image_type"] == "image/png" and mine["action_label"] == "대표이미지", mine
|
||||
|
||||
q("UPDATE cafe24_product_schedules SET scheduled_at = now() - interval '3000 days' WHERE id=%s RETURNING id", sid)
|
||||
worker.process_once(ST, fakes.FakeApi(MULTI))
|
||||
row = ST.get_schedule(sid)
|
||||
assert row["status"] == "SUCCESS", row
|
||||
posts = [c for c in cafe.calls if c[0] == "POST" and c[1].endswith("/images")]
|
||||
assert len(posts) == 1 and posts[0][2]["request"]["detail_image"].startswith("data:image/png;base64,")
|
||||
assert cafe.state["detail_image"] == f"/web/product/detail/{no}_1.png"
|
||||
assert [c for c in cafe.calls if c[0] == "PUT"] == [] # 이미지만 — 상세설명·진열 PUT 없음
|
||||
assert ST.get_write_snapshot(no)["product"]["data"]["detail_image"] == cafe.state["detail_image"]
|
||||
|
||||
# 이미지 + 진열을 한 예약에: 이미지 먼저, 그다음 진열 PUT
|
||||
no2, cafe2 = _new_product("<p>A</p>")
|
||||
sid2 = ST.create_schedule(product_no=no2, scheduled_at=now_kst() - timedelta(days=3000), revision_id=None,
|
||||
set_display=False, set_selling=None, image=png, image_type="image/png", image_name="b.png")
|
||||
worker.process_once(ST, fakes.FakeApi(MULTI))
|
||||
assert ST.get_schedule(sid2)["status"] == "SUCCESS"
|
||||
kinds = [(c[0], c[1].rsplit("/", 1)[-1]) for c in cafe2.calls if c[0] in ("POST", "PUT")]
|
||||
assert kinds == [("POST", "images"), ("PUT", str(no2))], kinds
|
||||
assert cafe2.state["display"] == "F" and cafe2.state["detail_image"].endswith(f"{no2}_1.png")
|
||||
|
||||
|
||||
def test_worker_real_db_recovers_crash_after_remote_ok():
|
||||
no, cafe = _new_product("<p>A</p>")
|
||||
rid = _draft(no, "<p>R</p>")
|
||||
|
||||
@@ -15,6 +15,26 @@ DSN = os.getenv("INOUT_TEST_DB_URL", "")
|
||||
ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
|
||||
|
||||
|
||||
class ListReceiptDatesNoDbTests(unittest.TestCase):
|
||||
"""DB 없이 — 발주별로 입고일을 묶어 돌려주는지(입고 없는 발주 = 빈 목록)."""
|
||||
|
||||
def test_groups_dates_by_order(self):
|
||||
from contextlib import nullcontext
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from app.modules.inout.db import InoutDBStore
|
||||
|
||||
heads = [{"id": i, "order_no": f"PO-{i}", "closed_at": None, "cancelled_at": None} for i in (1, 2)]
|
||||
lines = [{"order_id": i, "item_code": "A", "item_name": "A", "qty": 10, "received": 1} for i in (1, 2)]
|
||||
receipts = [{"order_id": 1, "receipt_date": date(2026, 10, 21)}, {"order_id": 1, "receipt_date": date(2026, 10, 23)}]
|
||||
conn = MagicMock()
|
||||
conn.execute.side_effect = lambda sql, *a: MagicMock(fetchall=lambda: receipts if "receipt_date" in sql else lines if "inout_order_lines l" in sql else heads)
|
||||
st = InoutDBStore.__new__(InoutDBStore)
|
||||
st._pool = MagicMock(connection=lambda: nullcontext(conn))
|
||||
got = {o["id"]: o["receipt_dates"] for o in st.list_orders()}
|
||||
self.assertEqual(got, {1: [date(2026, 10, 21), date(2026, 10, 23)], 2: []})
|
||||
|
||||
|
||||
@unittest.skipUnless(ENABLED, "INOUT_TEST_DB_URL(localhost) not set")
|
||||
class InoutDbTests(unittest.TestCase):
|
||||
@classmethod
|
||||
@@ -66,6 +86,16 @@ class InoutDbTests(unittest.TestCase):
|
||||
self.assertNotIn(o["id"], [x["id"] for x in self.st.list_orders(status="active", factory_id=self.fid)])
|
||||
self.assertIn(o["id"], [x["id"] for x in self.st.list_orders(status="done", factory_id=self.fid)])
|
||||
|
||||
def test_list_receipt_dates(self):
|
||||
"""목록 입고일 — 입고 전 빈 목록, 여러 날은 오래된 날부터, 같은 날 두 번은 한 번만."""
|
||||
o = self.order([("MT-D", 100)])
|
||||
line = self.line_ids(o["id"])["MT-D"]
|
||||
dates = lambda: next(x for x in self.st.list_orders(status="all", factory_id=self.fid) if x["id"] == o["id"])["receipt_dates"]
|
||||
self.assertEqual(dates(), [])
|
||||
for day in ("2026-10-23", "2026-10-21", "2026-10-23"):
|
||||
self.st.add_receipt(o["id"], {line: "10"}, receipt_date=day, memo="", confirm_over=False, by="w@x")
|
||||
self.assertEqual(dates(), [date(2026, 10, 21), date(2026, 10, 23)])
|
||||
|
||||
def test_over_receipt_needs_confirm(self):
|
||||
from app.modules.inout.db import OverReceipt
|
||||
|
||||
|
||||
+360
-62
@@ -21,7 +21,7 @@ from PIL import Image
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from app.modules.live import i18n, store # noqa: E402
|
||||
from app.modules.live import i18n, ocr, store # noqa: E402
|
||||
|
||||
DSN = os.getenv("LIVE_TEST_DB_URL", "")
|
||||
DB_ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
|
||||
@@ -60,16 +60,50 @@ def _run(code: str, extra_env: dict[str, str] | None = None) -> subprocess.Compl
|
||||
|
||||
class StoreTests(unittest.TestCase):
|
||||
def test_clean_host(self):
|
||||
got = store.clean_host({"full_name": " Siti Aisyah ", "phone": "+60 12-345 6789", "email": "siti@example.my", "address": "KL",
|
||||
got = store.clean_host({"platform": "TikTok", "display_name": " Siti ", "full_name": " Siti Aisyah ", "phone": "+60 12-345 6789", "email": "siti@example.my", "address": "KL",
|
||||
"bank_name": "Maybank", "bank_account": "1234-5678", "tiktok_handle": "@siti.live"})
|
||||
self.assertEqual((got["full_name"], got["tiktok_handle"]), ("Siti Aisyah", "siti.live"))
|
||||
self.assertEqual(store.clean_host({"full_name": "A"})["phone"], "") # Full Name 만 필수
|
||||
for bad in ({}, {"full_name": " "}, {"full_name": "A", "email": "nope"}, {"full_name": "A", "phone": "abc"},
|
||||
{"full_name": "A", "bank_account": "12a"}, {"full_name": "A", "tiktok_handle": "한글"},
|
||||
{"full_name": "x" * 201}):
|
||||
self.assertEqual((got["platform"], got["display_name"], got["full_name"]), ("tiktok", "Siti", "Siti Aisyah"))
|
||||
self.assertNotIn("tiktok_handle", got) # 계정은 방송마다 — 호스트에는 저장 안 함
|
||||
ok = {"platform": "shopee", "display_name": "A", "full_name": "A"}
|
||||
self.assertEqual(store.clean_host(ok)["phone"], "") # 쇼핑몰·두 이름만 필수
|
||||
for bad in ({}, {**ok, "full_name": ""}, {**ok, "display_name": ""}, {**ok, "platform": ""}, {**ok, "platform": "lazada"}, {**ok, "full_name": " "}, {**ok, "email": "nope"}, {**ok, "phone": "abc"},
|
||||
{**ok, "bank_account": "12a"}, {**ok, "full_name": "x" * 201}, {**ok, "display_name": "x" * 51}):
|
||||
with self.assertRaises(ValueError, msg=bad):
|
||||
store.clean_host(bad)
|
||||
|
||||
def test_broadcast_account(self):
|
||||
good = {"host_id": "3", "broadcast_date": "2026-11-04", "start_time": "20:00", "end_time": "22:00"}
|
||||
self.assertEqual(store.clean_broadcast(good)["tiktok_handle"], "") # 선택 칸
|
||||
self.assertEqual(store.clean_broadcast({**good, "tiktok_handle": "https://www.tiktok.com/@alt.acc?lang=en"})["tiktok_handle"], "alt.acc")
|
||||
for bad in ("한글", "x" * 65):
|
||||
with self.assertRaises(ValueError, msg=bad):
|
||||
store.clean_broadcast({**good, "tiktok_handle": bad})
|
||||
|
||||
def test_edit_keeps_broadcast_account(self):
|
||||
"""고치기 창에 계정이 채워져야 저장하면서 지워지지 않는다."""
|
||||
view = store.broadcast_view({"id": 1, "host_id": 2, "host_name": "Yaya", "host_platform": "shopee", "tiktok_handle": "alt.acc", "broadcast_date": date(2026, 11, 4),
|
||||
"start_time": time(20, 0), "end_time": time(22, 0), "venue": "", "sales_amount": None, "ad_spend": None,
|
||||
"host_fee": Decimal("40"), "images": []})
|
||||
self.assertEqual((view["edit"]["sales_amount"], view["edit"]["ad_spend"], view["edit"]["host_fee"], view["base"]), ("", "", "40.00", "50.00"))
|
||||
self.assertNotIn("venue", view["edit"]) # 방송 장소는 창에서 뺌(2026-11-06)
|
||||
self.assertEqual(view["platform"], "shopee") # 표 첫 열·카드 머리 아이콘
|
||||
self.assertEqual((view["tiktok_handle"], view["edit"]["tiktok_handle"], view["label"]), ("alt.acc", "alt.acc", "Yaya")) # 카드 머리 = 호스트, 계정은 아래
|
||||
|
||||
def test_my_holidays(self):
|
||||
from app.modules.live import holidays
|
||||
ko, en = holidays.holiday_names("ko"), holidays.holiday_names("en")
|
||||
self.assertEqual(set(ko), set(en))
|
||||
for day in ko:
|
||||
date.fromisoformat(day)
|
||||
self.assertEqual((ko["2026-11-08"], ko["2026-11-09"]), ("디파발리", "디파발리 대체"))
|
||||
self.assertEqual((en["2026-11-08"], en["2026-11-09"]), ("Deepavali", "Deepavali (Replacement)"))
|
||||
self.assertIn("Federal Territory Day", en["2026-02-01"])
|
||||
self.assertFalse([n for n in en.values() if re.search("[가-힣]", n)])
|
||||
# 대체휴일은 평일에 — 토·일이면 표가 틀린 것
|
||||
for day, name in en.items():
|
||||
if "Replacement" in name:
|
||||
self.assertLess(date.fromisoformat(day).weekday(), 5, day)
|
||||
|
||||
def test_clean_handle(self):
|
||||
for raw in ("@siti.live", "siti.live", "https://www.tiktok.com/@siti.live?lang=en", "tiktok.com/@siti.live/video/1"):
|
||||
self.assertEqual(store.clean_handle(raw), "siti.live", raw)
|
||||
@@ -81,15 +115,19 @@ class StoreTests(unittest.TestCase):
|
||||
for bad in ("-1", "abc", "NaN", "Infinity", "1e20"):
|
||||
with self.assertRaises(ValueError, msg=bad):
|
||||
store.parse_money(bad)
|
||||
with self.assertRaises(store.LiveError) as err:
|
||||
store.parse_money("x", "호스트 비용")
|
||||
self.assertEqual(err.exception.text("en"), "Host Fee must be a number.")
|
||||
|
||||
def test_clean_broadcast(self):
|
||||
got = store.clean_broadcast({"host_id": "3", "broadcast_date": "2026-11-04", "start_time": "20:00", "end_time": "22:00",
|
||||
"venue": " Studio ", "sales_amount": "100"})
|
||||
"venue": " Studio ", "sales_amount": "100", "ad_spend": "RM 20", "host_fee": ""})
|
||||
self.assertEqual(got, {"host_id": 3, "broadcast_date": date(2026, 11, 4), "start_time": time(20, 0), "end_time": time(22, 0),
|
||||
"venue": "Studio", "sales_amount": Decimal("100.00")})
|
||||
"tiktok_handle": "", "sales_amount": Decimal("100.00"), "ad_spend": Decimal("20.00"), "host_fee": None})
|
||||
good = {"host_id": "3", "broadcast_date": "2026-11-04", "start_time": "20:00", "end_time": "22:00"}
|
||||
for over in ({"host_id": ""}, {"host_id": "x"}, {"broadcast_date": ""}, {"broadcast_date": "2026-13-01"}, {"start_time": ""},
|
||||
{"start_time": "25:00"}, {"end_time": ""}, {"end_time": "nope"}, {"end_time": "20:00"}, {"venue": "x" * 201}, {"sales_amount": "-5"}):
|
||||
{"start_time": "25:00"}, {"end_time": ""}, {"end_time": "nope"}, {"end_time": "20:00"}, {"sales_amount": "-5"},
|
||||
{"ad_spend": "-1"}, {"host_fee": "abc"}):
|
||||
with self.assertRaises(ValueError, msg=over):
|
||||
store.clean_broadcast({**good, **over})
|
||||
|
||||
@@ -113,12 +151,12 @@ class StoreTests(unittest.TestCase):
|
||||
self.assertEqual(store.fmt_money(None), "")
|
||||
|
||||
def test_session_pay(self):
|
||||
"""호스트 비용 = 시간 × RM 25 + 판매금액 10%. 받은 화면의 예: 2시간·판매 48 → 50 + 4.8."""
|
||||
"""Fee = 시간 × RM 25, 커미션 = 판매금액 10%. 받은 화면의 예: 2시간·판매 48 → 50·4.8."""
|
||||
p = store.session_pay(time(12, 0), time(14, 0), Decimal("48"))
|
||||
self.assertEqual((p["base"], p["commission"], p["fee"]), (Decimal("50.00"), Decimal("4.80"), Decimal("54.80")))
|
||||
self.assertEqual(store.session_pay(time(22, 0), time(0, 0), None)["fee"], Decimal("50.00")) # 자정까지
|
||||
self.assertEqual((p["base"], p["commission"]), (Decimal("50.00"), Decimal("4.80")))
|
||||
self.assertEqual(store.session_pay(time(22, 0), time(0, 0), None)["base"], Decimal("50.00")) # 자정까지
|
||||
self.assertEqual(store.session_pay(time(23, 0), time(1, 30), None)["base"], Decimal("62.50")) # 자정 넘김·30분
|
||||
self.assertEqual(store.session_pay(time(12, 0), None, Decimal("10"))["fee"], Decimal("1.00")) # 끝 시간 없음 = 기본 요금 없음
|
||||
self.assertEqual(store.session_pay(time(12, 0), None, Decimal("10"))["base"], Decimal("0.00")) # 끝 시간 없음 = 기본 요금 없음
|
||||
self.assertEqual(store.session_pay(time(12, 0), time(14, 0), Decimal("0.05"))["commission"], Decimal("0.01")) # 반올림
|
||||
self.assertEqual((store.fmt_short(Decimal("48")), store.fmt_short(Decimal("4.80")), store.fmt_short(Decimal("1234.5"))), ("48", "4.80", "1,234.50"))
|
||||
|
||||
@@ -132,38 +170,56 @@ class StoreTests(unittest.TestCase):
|
||||
store.parse_move(*bad)
|
||||
|
||||
def test_build_calendar(self):
|
||||
def b(id, day, start, end, sales=None, host=1, handle="yaya"):
|
||||
return {"id": id, "host_id": host, "host_name": "Yaya", "tiktok_handle": handle, "broadcast_date": day, "start_time": start,
|
||||
"end_time": end, "venue": "", "sales_amount": sales, "images": []}
|
||||
def b(id, day, start, end, sales=None, host=1, handle="yaya", ad=None, fee=None):
|
||||
return {"id": id, "host_id": host, "host_name": "Yaya", "host_platform": "tiktok", "tiktok_handle": handle, "broadcast_date": day, "start_time": start,
|
||||
"end_time": end, "venue": "", "sales_amount": sales, "ad_spend": ad, "host_fee": fee, "images": []}
|
||||
span = store.month_range("2026-11", date(2026, 11, 4))
|
||||
cal = store.build_calendar(span, [b(1, date(2026, 11, 4), time(12, 0), time(14, 0), Decimal("48")),
|
||||
b(2, date(2026, 11, 4), time(22, 0), time(0, 0), handle=""),
|
||||
cal = store.build_calendar(span, [b(1, date(2026, 11, 4), time(12, 0), time(14, 0), Decimal("48"), ad=Decimal("20"), fee=Decimal("54.8")),
|
||||
b(2, date(2026, 11, 4), time(22, 0), time(0, 0), handle="", ad=Decimal("4"), fee=Decimal("50")),
|
||||
b(3, date(2026, 11, 7), time(13, 30), time(15, 0))],
|
||||
{date(2026, 11, 4): Decimal("24")}, date(2026, 11, 4), "en")
|
||||
ko = store.build_calendar(span, [], {}, date(2026, 11, 4))
|
||||
self.assertEqual((ko["days"][3]["weekday"], ko["days"][3]["label"], ko["slot_note"]), ("수요일", "11월 4일", "2시간 (기본 RM50)"))
|
||||
date(2026, 11, 4), "en")
|
||||
ko = store.build_calendar(span, [], date(2026, 11, 4))
|
||||
self.assertEqual((ko["days"][3]["weekday"], ko["days"][3]["label"], ko["slot_note"]), ("수요일", "11월 4일", "1시간 (기본 RM25)"))
|
||||
self.assertEqual(len(cal["days"]), 30)
|
||||
self.assertEqual([s["label"] for s in cal["slots"]][0], "06:00 - 08:00")
|
||||
self.assertEqual([s["label"] for s in cal["slots"]][-1], "22:00 - 00:00")
|
||||
self.assertEqual(len(cal["slots"]), 9)
|
||||
self.assertEqual(cal["slot_note"], "2 Hours (RM50 Base)")
|
||||
self.assertEqual([s["label"] for s in cal["slots"]][0], "06:00 - 07:00")
|
||||
self.assertEqual([s["label"] for s in cal["slots"]][-1], "23:00 - 00:00")
|
||||
self.assertEqual(len(cal["slots"]), 18)
|
||||
self.assertEqual(cal["slot_note"], "1 Hour (RM25 Base)")
|
||||
d4 = cal["days"][3]
|
||||
self.assertEqual((d4["weekday"], d4["label"], d4["count"], d4["is_today"], d4["is_weekend"]), ("WEDNESDAY", "4 NOV", 2, True, False))
|
||||
self.assertEqual((d4["sales_text"], d4["spend_text"], d4["fee_text"], d4["roas"]), ("48", "24", "104.80", "2.00"))
|
||||
self.assertEqual(cal["days"][6]["is_weekend"], True) # 11-07 토
|
||||
self.assertEqual(cal["days"][0]["roas"], "-") # 광고비 없음
|
||||
noon = next(s for s in cal["slots"] if s["start"] == "12:00")
|
||||
self.assertEqual(noon["cells"][3]["cards"][0]["label"], "yaya") # 카드 머리 = Tiktok Handle
|
||||
self.assertEqual(noon["cells"][3]["cards"][0]["label"], "Yaya") # 카드 머리 = 호스트 간단한 이름
|
||||
self.assertEqual((noon["cells"][3]["cards"][0]["card_sales"], noon["cells"][3]["cards"][0]["card_commission"], noon["cells"][3]["cards"][0]["card_fee"]),
|
||||
("48", "4.80", "54.80"))
|
||||
late = next(s for s in cal["slots"] if s["start"] == "22:00")
|
||||
self.assertEqual((late["end"], late["cells"][3]["cards"][0]["label"]), ("00:00", "Yaya")) # 핸들 없으면 이름
|
||||
self.assertEqual(next(s for s in cal["slots"] if s["start"] == "12:00")["cells"][6]["cards"][0]["id"], 3) # 13:30 = 12~14 칸
|
||||
self.assertEqual((late["end"], late["cells"][3]["cards"][0]["label"]), ("23:00", "Yaya")) # 핸들 없으면 이름
|
||||
self.assertEqual(next(s for s in cal["slots"] if s["start"] == "13:00")["cells"][6]["cards"][0]["id"], 3) # 13:30 = 13~14 칸
|
||||
self.assertEqual(cal["totals"]["sales"], "48")
|
||||
# 06시보다 이른 칸은 방송이 있을 때만
|
||||
early = store.build_calendar(span, [b(9, date(2026, 11, 1), time(3, 0), time(5, 0))], {}, date(2026, 11, 4))
|
||||
self.assertEqual(early["slots"][0]["label"], "02:00 - 04:00")
|
||||
self.assertEqual(len(early["slots"]), 10)
|
||||
early = store.build_calendar(span, [b(9, date(2026, 11, 1), time(3, 0), time(5, 0))], date(2026, 11, 4))
|
||||
self.assertEqual([s["label"] for s in early["slots"]][:3], ["03:00 - 04:00", "04:00 - 05:00", "06:00 - 07:00"]) # 걸친 칸은 늘 있음
|
||||
self.assertEqual(len(early["slots"]), 20)
|
||||
|
||||
# 칸 합치기(rowspan) — 방송이 걸친 시간만큼, 겹쳐 시작하는 방송은 같은 칸, 자정 넘김은 그날 끝까지
|
||||
def col(c, day_index):
|
||||
return [(s["start"], cell.get("rowspan"), [x["id"] for x in cell.get("cards", [])]) for s in c["slots"]
|
||||
for cell in [s["cells"][day_index]] if not cell.get("skip")]
|
||||
self.assertEqual(col(cal, 3)[6:9], [("12:00", 2, [1]), ("14:00", 1, []), ("15:00", 1, [])]) # 12~14 = 두 칸
|
||||
self.assertEqual(col(cal, 3)[-1], ("22:00", 2, [2])) # 22~00 = 22·23 칸
|
||||
self.assertEqual(col(cal, 6)[7], ("13:00", 2, [3])) # 13:30~15:00 = 13·14 칸
|
||||
self.assertEqual(sum(1 for s in cal["slots"] if s["cells"][3].get("skip")), 2)
|
||||
m = store.build_calendar(span, [b(5, date(2026, 11, 2), time(6, 0), time(8, 0)), b(6, date(2026, 11, 2), time(7, 0), time(10, 0)),
|
||||
b(7, date(2026, 11, 2), time(23, 0), time(1, 0)), b(8, date(2026, 11, 2), time(20, 0), time(20, 30))],
|
||||
date(2026, 11, 4))
|
||||
self.assertEqual(col(m, 1)[0], ("06:00", 4, [5, 6])) # 6~8 + 7~10 = 6·7·8·9
|
||||
self.assertEqual(col(m, 1)[1][0], "10:00")
|
||||
self.assertIn(("20:00", 1, [8]), col(m, 1)) # 30분 = 한 칸
|
||||
self.assertEqual(col(m, 1)[-1], ("23:00", 1, [7])) # 자정 넘김 = 그날 마지막 칸까지
|
||||
for s in m["slots"]: # 날짜마다 칸 수(합친 칸 포함) = 줄 수
|
||||
self.assertEqual(len(s["cells"]), 30)
|
||||
|
||||
def test_thumbnail(self):
|
||||
for mode, fmt in (("RGB", "JPEG"), ("RGBA", "PNG")):
|
||||
@@ -173,6 +229,39 @@ class StoreTests(unittest.TestCase):
|
||||
self.assertEqual((im.format, im.size), ("JPEG", (160, 80)))
|
||||
|
||||
|
||||
class OcrTests(unittest.TestCase):
|
||||
"""결과 이미지 → 매출(2026-11-06). 실제 글자 인식(tesseract)은 서버 이미지에만 — 여기서는 읽은 글자 풀이와 흐름."""
|
||||
|
||||
def test_parse_sales(self):
|
||||
# 틱톡 LIVE 결과 화면을 tesseract --psm 11 로 읽은 모양(단어마다 줄)
|
||||
screen = "Duration: 2h 5m\n\nCongratulations!\n\nRM672.2\n\n10\n\n16\n\nAttr. GMV\n\nAttr. items sold\n\nPer-LIVE\n\n$0.04"
|
||||
self.assertEqual(ocr.parse_sales(screen), (Decimal("672.20"), "RM672.2"))
|
||||
for text, want in (("RM 1,234.50", Decimal("1234.50")), ("R M672,2", Decimal("672.20")), ("RM12,345", Decimal("12345.00")),
|
||||
("RM0", Decimal("0.00")), ("Attr GMV RM98.75 x", Decimal("98.75"))):
|
||||
self.assertEqual(ocr.parse_sales(text)[0], want, text)
|
||||
self.assertEqual(ocr.parse_sales("RM1.2K\nAttr. GMV"), (None, "RM1.2K")) # 줄인 값 = 쓰지 않음
|
||||
self.assertEqual(ocr.parse_sales("Rewards $0.04 6.5K"), (None, ""))
|
||||
self.assertEqual(ocr.parse_sales(""), (None, ""))
|
||||
|
||||
def test_read_sales_top_half_and_errors(self):
|
||||
from unittest.mock import patch
|
||||
raw = io.BytesIO()
|
||||
Image.new("RGB", (464, 1005), "white").save(raw, format="PNG")
|
||||
seen = {}
|
||||
|
||||
def fake(img):
|
||||
seen["size"] = img.size
|
||||
return "RM672.2\nAttr. GMV"
|
||||
with patch.object(ocr, "_ocr_text", side_effect=fake):
|
||||
self.assertEqual(ocr.read_sales(raw.getvalue()), (Decimal("672.20"), "RM672.2"))
|
||||
self.assertEqual(seen["size"], (464, 502)) # 위 절반만
|
||||
with patch.object(ocr.shutil, "which", return_value=None):
|
||||
with self.assertRaises(i18n.LiveError):
|
||||
ocr.read_sales(raw.getvalue())
|
||||
with self.assertRaises(ValueError):
|
||||
ocr.read_sales(b"not an image")
|
||||
|
||||
|
||||
class I18nTests(unittest.TestCase):
|
||||
def test_every_text_has_english(self):
|
||||
"""템플릿·오류·권한 문구가 모두 영문 표에 있다 — 새 문구를 넣고 빠뜨리면 여기서 걸린다."""
|
||||
@@ -180,7 +269,7 @@ class I18nTests(unittest.TestCase):
|
||||
keys = set(i18n.JS_KEYS) | set(store._LABELS.values()) | {"시작 시간", "끝 시간"}
|
||||
for path in (live / "templates" / "live").glob("*.html"):
|
||||
keys |= set(re.findall(r"\bt\('([^']+)'\)", path.read_text(encoding="utf-8")))
|
||||
for name in ("store.py", "db.py", "router.py"):
|
||||
for name in ("store.py", "db.py", "router.py", "ocr.py"):
|
||||
text = (live / name).read_text(encoding="utf-8")
|
||||
keys |= set(re.findall(r'LiveError\("([^"]+)"', text))
|
||||
keys |= set(re.findall(r'_t\(request, "([^"]+)"\)', text))
|
||||
@@ -213,6 +302,181 @@ def body(c):
|
||||
assert nav and nav[0]["label"] == "라이브 커머스" # 사이드바는 짧게
|
||||
print("OK")
|
||||
run(body)
|
||||
''')
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
def test_live_host_chip_adds_only(self):
|
||||
"""`live_host` 칩 = 새 호스트 등록만 — 계좌 안 보임, 고치기·지우기·사용 안 함 불가. DB 없이 가짜 저장소로."""
|
||||
res = _run('''
|
||||
from app.store import MODULE_KEYS
|
||||
assert "live_host" in MODULE_KEYS and "live_host" in main.MODULE_LABELS
|
||||
|
||||
class Fake:
|
||||
saved = []
|
||||
def host_choices(self):
|
||||
return [{"id": 1, "platform": "tiktok", "display_name": "Siti", "full_name": "Siti Binti Awa", "is_active": True}]
|
||||
def list_hosts(self):
|
||||
return [{"id": 1, "platform": "tiktok", "display_name": "Siti", "full_name": "Siti Binti Awa", "phone": "012", "email": "s@e.my", "address": "KL", "bank_name": "Maybank",
|
||||
"bank_account": "998877", "is_active": True}]
|
||||
def list_broadcasts(self, start, end):
|
||||
return []
|
||||
def account_choices(self):
|
||||
return ["MainAccount", "alt.acc"]
|
||||
def save_host(self, host_id, values, *, is_active, by):
|
||||
self.saved.append((host_id, values["full_name"], is_active, by))
|
||||
return 2
|
||||
def delete_host(self, host_id):
|
||||
self.saved.append(("deleted", host_id))
|
||||
|
||||
fake = main.app.state.live_store = Fake()
|
||||
adder = U("adder@t.local"); adder["modules"]["live_host"] = True
|
||||
chip_only = U("chip@t.local", live=False); chip_only["modules"]["live_host"] = True
|
||||
new = {"platform": "tiktok", "display_name": "Newbie", "full_name": "New Host", "bank_account": "111"}
|
||||
|
||||
def body(c):
|
||||
who["u"] = adder
|
||||
sched = c.get("/live/").text
|
||||
assert 'href="/live/settings"' in sched and 'name="tiktok_handle"' in sched and '<option value="alt.acc">' in sched
|
||||
page = c.get("/live/settings")
|
||||
assert page.status_code == 200 and "Siti" in page.text and 'name="full_name"' in page.text
|
||||
for hidden in ("998877", "Maybank", "s@e.my", 'name="tiktok_handle"', "data-edit='", "/delete", 'name="is_active"', "data-active="):
|
||||
assert hidden not in page.text, hidden
|
||||
assert c.post("/live/settings/hosts", data=new).json()["ok"]
|
||||
assert fake.saved == [(None, "New Host", True, "adder@t.local")], fake.saved
|
||||
assert c.post("/live/settings/hosts", data={**new, "id": "1"}).status_code == 403
|
||||
assert c.post("/live/settings/hosts/1/delete").status_code == 403
|
||||
assert c.post("/live/settings/hosts/1/active", data={"is_active": "0"}).status_code == 403 # 토글 = 고치기 권한
|
||||
assert len(fake.saved) == 1, fake.saved
|
||||
|
||||
for no_add in (U("staff@t.local"), chip_only):
|
||||
who["u"] = no_add
|
||||
assert c.get("/live/settings").status_code == 403
|
||||
assert c.post("/live/settings/hosts", data=new).status_code == 403
|
||||
assert len(fake.saved) == 1, fake.saved
|
||||
|
||||
# 관리자는 그대로 — 계좌 보임, 고치기, 사용 안 함
|
||||
who["u"] = U("a@t.local", role="admin")
|
||||
page = c.get("/live/settings").text
|
||||
assert "998877" in page and "data-edit='" in page and 'name="is_active"' in page
|
||||
assert c.post("/live/settings/hosts", data={**new, "id": "1"}).json()["ok"]
|
||||
assert fake.saved[-1] == (1, "New Host", False, "a@t.local"), fake.saved
|
||||
print("OK")
|
||||
run(body)
|
||||
''')
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
def test_live_host_edit_chip(self):
|
||||
"""`live_host_edit` 칩 = 고치기 — 개인정보는 페이지에 없고, 빈칸은 그대로·입력하면 바뀜, 등록·지우기는 안 됨."""
|
||||
res = _run('''
|
||||
from app.store import MODULE_KEYS
|
||||
assert "live_host_edit" in MODULE_KEYS and main.MODULE_LABELS["live_host_edit"] == "라이브 호스트 수정"
|
||||
|
||||
OLD = {"id": 1, "platform": "shopee", "display_name": "Siti", "full_name": "Siti Binti Awa", "phone": "012", "email": "s@e.my", "address": "KL", "bank_name": "Maybank",
|
||||
"bank_account": "998877", "is_active": True}
|
||||
|
||||
class Fake:
|
||||
saved = []
|
||||
def host_choices(self):
|
||||
return [{k: OLD[k] for k in ("id", "platform", "display_name", "full_name", "is_active")}]
|
||||
def list_hosts(self):
|
||||
return [OLD]
|
||||
def get_host(self, host_id):
|
||||
return OLD if host_id == 1 else None
|
||||
def list_broadcasts(self, start, end):
|
||||
return []
|
||||
def account_choices(self):
|
||||
return []
|
||||
def save_host(self, host_id, values, *, is_active, by):
|
||||
self.saved.append((host_id, values, is_active))
|
||||
return 1
|
||||
def delete_host(self, host_id):
|
||||
self.saved.append(("deleted", host_id))
|
||||
def set_host_active(self, host_id, is_active, *, by):
|
||||
if host_id != 1:
|
||||
raise ValueError("호스트를 찾을 수 없습니다.")
|
||||
self.saved.append(("active", host_id, is_active))
|
||||
|
||||
fake = main.app.state.live_store = Fake()
|
||||
editor = U("edit@t.local"); editor["modules"]["live_host_edit"] = True
|
||||
chip_only = U("chip@t.local", live=False); chip_only["modules"]["live_host_edit"] = True
|
||||
form = {"id": "1", "platform": "shopee", "display_name": "Nabella", "full_name": "Siti Binti Awa", "is_active": "1"}
|
||||
|
||||
def body(c):
|
||||
who["u"] = editor
|
||||
assert \'href="/live/settings"\' in c.get("/live/").text
|
||||
page = c.get("/live/settings").text
|
||||
for hidden in ("998877", "Maybank", "s@e.my", "/delete", \'id="lv-add"\'):
|
||||
assert hidden not in page, hidden
|
||||
assert "data-edit=\'" in page and "Siti Binti Awa" in page and \'name="is_active"\' in page and "data-edit-only" in page
|
||||
assert \'data-active="/live/settings/hosts/1/active"\' in page and \'src="/static/dispatch/courier/shopee.png"\' in page
|
||||
assert \'"platform": "shopee"\' in page and page.count(\'name="platform"\') == 2
|
||||
|
||||
# 목록 토글 — 사용 여부만
|
||||
assert c.post("/live/settings/hosts/1/active", data={"is_active": "0"}).json()["ok"] and fake.saved[-1] == ("active", 1, False)
|
||||
assert c.post("/live/settings/hosts/1/active", data={"is_active": "1"}).json()["ok"] and fake.saved[-1] == ("active", 1, True)
|
||||
assert c.post("/live/settings/hosts/9/active", data={"is_active": "1"}).status_code == 400
|
||||
assert c.post("/live/settings/hosts", data={**form, "platform": ""}).status_code == 400 # 쇼핑몰 필수
|
||||
|
||||
assert c.post("/live/settings/hosts", data=form).json()["ok"]
|
||||
host_id, values, active = fake.saved[-1]
|
||||
assert host_id == 1 and active is True and values["display_name"] == "Nabella"
|
||||
assert (values["bank_account"], values["phone"], values["address"]) == ("998877", "012", "KL") # 빈칸 = 그대로
|
||||
assert c.post("/live/settings/hosts", data={**form, "bank_account": "111-222"}).json()["ok"]
|
||||
assert fake.saved[-1][1]["bank_account"] == "111-222" and fake.saved[-1][1]["phone"] == "012" # 입력 = 바뀜
|
||||
assert c.post("/live/settings/hosts", data={**form, "is_active": ""}).json()["ok"] and fake.saved[-1][2] is False
|
||||
assert c.post("/live/settings/hosts", data={**form, "id": "9"}).status_code == 400 # 없는 호스트
|
||||
assert c.post("/live/settings/hosts", data={**form, "display_name": ""}).status_code == 400 # 간단한 이름 필수
|
||||
|
||||
count = len(fake.saved)
|
||||
assert c.post("/live/settings/hosts", data={**form, "id": ""}).status_code == 403 # 등록 권한 없음
|
||||
assert c.post("/live/settings/hosts/1/delete").status_code == 403
|
||||
for no_edit in (U("staff@t.local"), chip_only):
|
||||
who["u"] = no_edit
|
||||
assert c.get("/live/settings").status_code == 403
|
||||
assert c.post("/live/settings/hosts", data=form).status_code == 403
|
||||
assert c.post("/live/settings/hosts/1/active", data={"is_active": "0"}).status_code == 403
|
||||
assert len(fake.saved) == count
|
||||
|
||||
# 관리자는 빈칸 = 지우기 그대로
|
||||
who["u"] = U("a@t.local", role="admin")
|
||||
assert c.post("/live/settings/hosts", data=form).json()["ok"] and fake.saved[-1][1]["bank_account"] == ""
|
||||
print("OK")
|
||||
run(body)
|
||||
''')
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
def test_calendar_page_side_calendar(self):
|
||||
res = _run('''
|
||||
import json, re
|
||||
|
||||
class Fake:
|
||||
def host_choices(self):
|
||||
return []
|
||||
def list_broadcasts(self, start, end):
|
||||
return []
|
||||
def broadcast_days(self, start, end):
|
||||
assert (start.isoformat(), end.isoformat()) == ("2025-10-31", "2027-12-02"), (start, end) # 보는 달 ±1년
|
||||
return ["2026-11-05"]
|
||||
def account_choices(self):
|
||||
return []
|
||||
main.app.state.live_store = Fake()
|
||||
|
||||
def names(page):
|
||||
return json.loads(re.search(r'id="lv-my-holidays">(.*?)</script>', page).group(1))
|
||||
|
||||
def body(c):
|
||||
who["u"] = U("s@t.local")
|
||||
page = c.get("/live/calendar?month=2026-11").text
|
||||
assert 'id="lv-side-cal"' in page and "/static/erp-datepop.js" in page
|
||||
assert names(page)["2026-11-09"] == "디파발리 대체"
|
||||
assert '<script type="application/json" id="lv-live-days">["2026-11-05"]</script>' in page
|
||||
c.cookies.set("live_lang", "en")
|
||||
assert names(c.get("/live/calendar?month=2026-11").text)["2026-11-09"] == "Deepavali (Replacement)"
|
||||
print("OK")
|
||||
run(body)
|
||||
''')
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
@@ -234,6 +498,39 @@ def body(c):
|
||||
assert c.get("/live/images/1").status_code == 403
|
||||
print("OK")
|
||||
run(body)
|
||||
''')
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
def test_read_sales_endpoint(self):
|
||||
"""결과 이미지 → 매출 읽기 — 저장 없이 값만, 권한 필요, 못 찾거나 줄인 값이면 amount 없음(DB 없이)."""
|
||||
res = _run('''
|
||||
import io
|
||||
from PIL import Image
|
||||
from app.modules.live import ocr
|
||||
|
||||
raw = io.BytesIO(); Image.new("RGB", (400, 800), "white").save(raw, format="PNG"); png = raw.getvalue()
|
||||
said = {"text": "RM672.2\\nAttr. GMV"}
|
||||
|
||||
def body(c):
|
||||
send = lambda: c.post("/live/broadcasts/read-sales", files={"image": ("r.png", png, "image/png")})
|
||||
with patch.object(ocr, "_ocr_text", side_effect=lambda img: said["text"]):
|
||||
who["u"] = U("s@t.local")
|
||||
r = send().json()
|
||||
assert r["ok"] and r["amount"] == "672.20" and "RM672.2" in r["message"], r
|
||||
said["text"] = "RM1.2K"
|
||||
r = send().json()
|
||||
assert r["ok"] and r["amount"] is None and "RM1.2K" in r["message"], r
|
||||
said["text"] = "nothing"
|
||||
assert send().json()["amount"] is None
|
||||
c.cookies.set("live_lang", "en")
|
||||
assert send().json()["message"].startswith("Couldn't find the sales")
|
||||
bad = c.post("/live/broadcasts/read-sales", files={"image": ("x.png", b"nope", "image/png")})
|
||||
assert bad.status_code == 400
|
||||
who["u"] = U("x@t.local", live=False)
|
||||
assert send().status_code == 403
|
||||
print("OK")
|
||||
run(body)
|
||||
''')
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
@@ -258,8 +555,8 @@ def jpeg():
|
||||
return raw.getvalue()
|
||||
|
||||
def body(c):
|
||||
host = {"full_name": NAME, "phone": "+60 12-345", "email": "siti@example.my", "address": "Kuala Lumpur",
|
||||
"bank_name": "Maybank", "bank_account": ACCOUNT, "tiktok_handle": "@siti.%s" % tag, "is_active": "1"}
|
||||
host = {"platform": "tiktok", "display_name": "S" + tag, "full_name": NAME, "phone": "+60 12-345", "email": "siti@example.my", "address": "Kuala Lumpur",
|
||||
"bank_name": "Maybank", "bank_account": ACCOUNT, "is_active": "1"}
|
||||
# ── 호스트 설정 = ERP 관리자만 ──
|
||||
who["u"] = staff
|
||||
assert c.get("/live/settings").status_code == 403
|
||||
@@ -272,29 +569,34 @@ def body(c):
|
||||
r = c.post("/live/settings/hosts", data=host)
|
||||
assert r.json()["ok"], r.text
|
||||
hid = next(h["id"] for h in st.list_hosts() if h["full_name"] == NAME)
|
||||
assert st.get_host(hid)["platform"] == "tiktok"
|
||||
assert c.post("/live/settings/hosts/%d/active" % hid, data={"is_active": "0"}).json()["ok"] and st.get_host(hid)["is_active"] is False
|
||||
assert c.post("/live/settings/hosts/%d/active" % hid, data={"is_active": "1"}).json()["ok"] and st.get_host(hid)["is_active"] is True
|
||||
page = c.get("/live/settings").text
|
||||
for field in ("이름 (IC 기준)", "전화번호", "이메일", "주소", "은행명", "계좌번호", "틱톡 핸들"):
|
||||
for field in ("이름 (IC 기준)", "전화번호", "이메일", "주소", "은행명", "계좌번호"):
|
||||
assert field in page, field
|
||||
assert ACCOUNT in page and "Siti <b>" in page and "<b>" + tag not in page
|
||||
assert st.list_hosts() and next(h for h in st.list_hosts() if h["id"] == hid)["tiktok_handle"] == "siti." + tag
|
||||
assert "틱톡 핸들" not in page and 'name="tiktok_handle"' not in page # 계정은 방송마다
|
||||
|
||||
# ── 스케줄: 일반 권한자도 추가·고치기, 화면에 계좌·주소 없음 ──
|
||||
who["u"] = staff
|
||||
page = c.get("/live/?month=2031-03").text
|
||||
assert 'value="%d"' % hid in page and "@siti." + tag in page
|
||||
assert 'value="%d"' % hid in page
|
||||
assert ACCOUNT not in page and "Kuala Lumpur" not in page and "Maybank" not in page
|
||||
show = {"host_id": hid, "broadcast_date": "2031-03-05", "start_time": "20:00", "end_time": "22:30", "venue": "KL Studio", "sales_amount": "1,234.5"}
|
||||
show = {"host_id": hid, "broadcast_date": "2031-03-05", "start_time": "20:00", "end_time": "22:30", "tiktok_handle": "@siti.%s" % tag, "sales_amount": "1,234.5",
|
||||
"ad_spend": "30", "host_fee": "77.7"}
|
||||
assert c.post("/live/broadcasts", data={**show, "host_id": ""}).status_code == 400
|
||||
assert c.post("/live/broadcasts", data={**show, "host_id": 99999999}).status_code == 400
|
||||
junk = c.post("/live/broadcasts", data=show, files=[("images", ("x.jpg", b"not an image", "image/jpeg"))])
|
||||
assert junk.status_code == 400 and "x.jpg" in junk.json()["message"]
|
||||
assert "KL Studio" not in c.get("/live/?month=2031-03").text # 이미지가 틀리면 방송도 저장 안 됨
|
||||
assert "1,234.50" not in c.get("/live/?month=2031-03").text # 이미지가 틀리면 방송도 저장 안 됨
|
||||
r = c.post("/live/broadcasts", data=show, files=[("images", ("../../evil.jpg", jpeg(), "image/jpeg"))])
|
||||
assert r.json()["ok"], r.text
|
||||
page = c.get("/live/?month=2031-03").text
|
||||
assert "2031.03.05(수)" in page and "20:00 ~ 22:30" in page and "KL Studio" in page and "1,234.50" in page
|
||||
assert ">123.45</td>" in page and ">185.95</td>" in page # 커미션 10%·호스트 비용(2.5시간 × 25 + 123.45)
|
||||
assert "KL Studio" not in c.get("/live/?month=2031-04").text
|
||||
assert "2031.03.05(수)" in page and "20:00 ~ 22:30" in page and "1,234.50" in page and 'name="venue"' not in page
|
||||
assert '<img class="lv-pf" src="/static/live-icon-tiktok.png" alt="TikTok"' in page # 첫 열 = 호스트 쇼핑몰 아이콘
|
||||
assert ">62.50</td>" in page and ">123.45</td>" in page and ">30.00</td>" in page and ">77.70</td>" in page # Fee 2.5시간 × 25·커미션 10%·광고비·호스트 비용(수기)
|
||||
assert "1,234.50" not in c.get("/live/?month=2031-04").text
|
||||
row = st.list_broadcasts(__import__("datetime").date(2031, 3, 1), __import__("datetime").date(2031, 4, 1))
|
||||
row = next(b for b in row if b["host_id"] == hid)
|
||||
bid, img = row["id"], row["images"][0]
|
||||
@@ -313,17 +615,19 @@ def body(c):
|
||||
who["u"] = staff
|
||||
|
||||
# ── 고치기: 값 바뀜, 이미지 유지 + 더하기, 판매금액 지우기, 10장 제한 ──
|
||||
r = c.post("/live/broadcasts", data={**show, "id": bid, "venue": "PJ Studio", "sales_amount": "", "end_time": "21:00"})
|
||||
r = c.post("/live/broadcasts", data={**show, "id": bid, "host_fee": "", "sales_amount": "", "end_time": "21:00"})
|
||||
assert r.json()["ok"], r.text
|
||||
page = c.get("/live/?month=2031-03").text
|
||||
assert "PJ Studio" in page and "1,234.50" not in page and "20:00 ~ 21:00" in page
|
||||
assert ">77.70</td>" not in page and "1,234.50" not in page and "20:00 ~ 21:00" in page and ">25.00</td>" in page
|
||||
assert c.post("/live/broadcasts", data={**show, "end_time": ""}).status_code == 400 # 끝 시간 필수
|
||||
|
||||
# ── 달력: 카드 머리 = Tiktok Handle, Fee, 옮기기(길이 유지)·맞바꾸기, 광고비·ROAS, 권한 ──
|
||||
c.post("/live/broadcasts", data={**show, "id": bid, "sales_amount": "48", "start_time": "12:00", "end_time": "14:00", "broadcast_date": "2031-03-05"})
|
||||
cal = c.get("/live/calendar?month=2031-03").text
|
||||
assert "날짜로 이동" in cal and "토요일" in cal and "12:00 - 14:00" in cal and "2시간 (기본 RM50)" in cal
|
||||
assert '<span class="lv-card-name">siti.%s</span>' % tag in cal and "RM54.80" in cal and ">4.80</b>" in cal
|
||||
assert "날짜로 이동" not in cal and "토요일" in cal and "12:00 - 13:00" in cal and "1시간 (기본 RM25)" in cal
|
||||
assert '"2031-03-05"' in cal.split('id="lv-live-days">')[1].split("</script>")[0] # 오른쪽 달력 점
|
||||
assert '<span class="lv-card-name">S%s<small>@siti.%s</small></span>' % (tag, tag) in cal and "RM77.70" in cal and ">4.80</b>" in cal # 카드 Fee = 호스트 비용(수기)
|
||||
assert 'data-spend=' not in cal and "<dd>RM 30</dd>" in cal # 날짜 광고비 = 방송 Ad Spend 합
|
||||
|
||||
# ── 영문: 화면 세 개 모두 한글 없음(입력한 데이터 제외)·날짜·오류·권한 문구 ──
|
||||
def no_korean(url):
|
||||
@@ -337,18 +641,17 @@ def body(c):
|
||||
page = no_korean("/live/?month=2031-03")
|
||||
assert 'lang="en"' in page and "March 2031" in page and "2031.03.05 (Wed)" in page and "Commission 10% (RM)" in page
|
||||
cal = no_korean("/live/calendar?month=2031-03")
|
||||
assert "Jump to Date" in cal and "SATURDAY" in cal and "1 MAR" in cal and "2 Hours (RM50 Base)" in cal and ">Sales<" in cal and "Com (10%)" in cal and "Fee: <b>RM54.80" in cal
|
||||
assert "SATURDAY" in cal and "1 MAR" in cal and "1 Hour (RM25 Base)" in cal and ">Sales<" in cal and "Com (10%)" in cal and "Fee: <b>RM77.70" in cal
|
||||
assert "Total Sales:" in cal and "Ad Spend:" in cal and "Host Fee:" in cal and "Total & ROAS" in cal
|
||||
assert c.post("/live/broadcasts", data={**show, "id": bid, "sales_amount": "abc"}).json()["message"] == "Sales must be a number."
|
||||
assert c.post("/live/broadcasts", data={**show, "id": bid, "ad_spend": "-1"}).json()["message"] == "Ad Spend must be a number of 0 or more."
|
||||
assert c.post("/live/broadcasts", data={**show, "id": bid, "end_time": ""}).json()["message"] == "Enter the End Time."
|
||||
junk = c.post("/live/broadcasts", data=show, files=[("images", ("x.jpg", b"not an image", "image/jpeg"))]).json()["message"]
|
||||
assert junk == "x.jpg: The image can't be read. Please choose a valid JPG, PNG or WebP file.", junk
|
||||
assert c.post("/live/settings/hosts", data=host).json()["detail"] == "Only ERP admins can view host information."
|
||||
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "1"}).json()["message"] == "Ad spend saved."
|
||||
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": ""}).json()["ok"]
|
||||
who["u"] = admin
|
||||
page = no_korean("/live/settings")
|
||||
for field in ("Full Name (as per IC)", "Phone Number", "Email", "Address", "Bank Name", "Bank Account Number", "Tiktok Handle"):
|
||||
for field in ("Full Name (as per IC)", "Phone Number", "Email", "Address", "Bank Name", "Bank Account Number", "Platform"):
|
||||
assert field in page, field
|
||||
who["u"] = staff
|
||||
c.cookies.set("live_lang", "<bad>") # 모르는 값 = 한글
|
||||
@@ -363,28 +666,23 @@ def body(c):
|
||||
assert (got["broadcast_date"], str(got["start_time"]), str(got["end_time"])) == (day(2031, 3, 7), "22:00:00", "00:00:00")
|
||||
assert c.post("/live/broadcasts/%d/move" % bid, data={"broadcast_date": "bad", "start_time": "22:00"}).status_code == 400
|
||||
assert c.post("/live/broadcasts/99999999/move", data={"broadcast_date": "2031-03-07", "start_time": "22:00"}).status_code == 400
|
||||
c.post("/live/broadcasts", data={**show, "broadcast_date": "2031-03-09", "start_time": "08:00", "end_time": "09:00", "venue": "Second"})
|
||||
other = next(b["id"] for b in st.list_broadcasts(day(2031, 3, 9), day(2031, 3, 10)) if b["venue"] == "Second")
|
||||
c.post("/live/broadcasts", data={**show, "broadcast_date": "2031-03-09", "start_time": "08:00", "end_time": "09:00"})
|
||||
other = next(b["id"] for b in st.list_broadcasts(day(2031, 3, 9), day(2031, 3, 10)) if b["id"] != bid)
|
||||
assert c.post("/live/broadcasts/%d/move" % bid, data={"swap_with": other}).json()["ok"]
|
||||
a, b2 = one(bid), one(other)
|
||||
assert (a["broadcast_date"], str(a["start_time"]), str(a["end_time"])) == (day(2031, 3, 9), "08:00:00", "09:00:00")
|
||||
assert (b2["broadcast_date"], str(b2["start_time"]), str(b2["end_time"])) == (day(2031, 3, 7), "22:00:00", "00:00:00")
|
||||
assert c.post("/live/broadcasts/%d/move" % bid, data={"swap_with": 99999999}).status_code == 400
|
||||
assert c.post("/live/broadcasts/%d/move" % bid, data={"swap_with": bid}).json()["ok"]
|
||||
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "24"}).json()["ok"]
|
||||
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "12"}).json()["ok"] # 덮어쓰기
|
||||
assert st.ad_spends(day(2031, 3, 1), day(2031, 4, 1)) == {day(2031, 3, 9): __import__("decimal").Decimal("12.00")}
|
||||
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "-1"}).status_code == 400
|
||||
assert c.post("/live/ad-spend", data={"day": "bad", "amount": "1"}).status_code == 400
|
||||
assert "4.00" in c.get("/live/calendar?month=2031-03").text # ROAS 48 ÷ 12
|
||||
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": ""}).json()["ok"] # 빈칸 = 지우기
|
||||
assert st.ad_spends(day(2031, 3, 1), day(2031, 4, 1)) == {}
|
||||
assert c.post("/live/broadcasts", data={**show, "id": bid, "sales_amount": "48", "ad_spend": "12", "broadcast_date": "2031-03-09",
|
||||
"start_time": "08:00", "end_time": "09:00"}).json()["ok"]
|
||||
cal = c.get("/live/calendar?month=2031-03").text
|
||||
assert "<dd>RM 12</dd>" in cal and "<dd>4.00</dd>" in cal and "<b>RM 42</b>" in cal # 날짜 광고비 = 방송 합, ROAS 48 ÷ 12, 달 합 12 + 30
|
||||
assert c.post("/live/broadcasts/%d/delete" % other).json()["ok"]
|
||||
c.post("/live/broadcasts", data={**show, "id": bid}) # 아래 시험을 위해 원래 값으로
|
||||
who["u"] = outsider
|
||||
assert c.get("/live/calendar").status_code == 403
|
||||
assert c.post("/live/broadcasts/%d/move" % bid, data={"swap_with": bid}).status_code == 403
|
||||
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "1"}).status_code == 403
|
||||
who["u"] = staff
|
||||
many = [("images", ("%d.jpg" % i, jpeg(), "image/jpeg")) for i in range(10)]
|
||||
r = c.post("/live/broadcasts", data={**show, "id": bid}, files=many)
|
||||
|
||||
Reference in New Issue
Block a user