Merge branch 'feat/live-commerce-module'
This commit is contained in:
@@ -161,6 +161,11 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
||||
# 초기화: scripts/sql/outreach_db_init.sql (docs/DEPLOYMENT.md "안내문 발송 DB 생성"). 미설정 시 "설정 필요" 안내만.
|
||||
# OUTREACH_DB_URL=postgresql://outreach_app:replace-me@postgres-db:5432/outreach_db
|
||||
|
||||
# ─── 라이브 커머스 모듈 (live_db) — app/modules/live ───
|
||||
# 말레이시아 라이브 방송의 호스트 정보·방송 스케줄·판매금액·결과 이미지.
|
||||
# 초기화: scripts/sql/live_db_init.sql (docs/DEPLOYMENT.md "라이브 커머스 DB 생성"). 미설정 시 "설정 필요" 안내만.
|
||||
# LIVE_DB_URL=postgresql://live_app:replace-me@postgres-db:5432/live_db
|
||||
|
||||
# ─── 상품 검색 (itemcode_db 읽기 전용) ───
|
||||
# cupang 설정 화면에서 제품명을 itemcode_db 에서 검색해 등록한다(읽기만).
|
||||
# 미설정 시 검색 비활성 → 수동 등록만 가능.
|
||||
|
||||
@@ -47,6 +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.*` |
|
||||
| `[공통]` `[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` | — |
|
||||
@@ -62,6 +63,7 @@
|
||||
- `APP_ENCRYPTION_KEY`: 실적(쇼핑몰·광고 인증) + 입출고(Gmail 토큰).
|
||||
- 입출고 Gmail 연결(`inout_gmail_tokens`·`/inout/gmail/callback`, `_GMAIL_ORIGINS`): 입출고 발주 메일 + 휴가 메일(`vacation/notify.py`) + 안내문 발송(`outreach/send.py`) — 모두 보내는 사람 본인 Gmail.
|
||||
- `app/integrations/google_sheets.py`(쿠팡) · `google_slides.py`(프로젝트 회의록 보드).
|
||||
- `asset/media.py prepare_photo`(이미지 확인·메타데이터 제거): 자산 + 라이브 커머스.
|
||||
- `app/mail.py`: 프로젝트 알림 메일.
|
||||
- ERP 모든 화면 스크립트: `erp-notice.js`(공지) · `erp-overdue.js`(프로젝트 마감 알림).
|
||||
- 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청) — 바꾸면 둘 다.
|
||||
|
||||
+18
@@ -26,6 +26,8 @@ from .modules.expense import CategoryStore, build_expense_store
|
||||
from .modules.expense import router as expense_router
|
||||
from .modules.inout import build_inout_items, build_inout_store
|
||||
from .modules.inout import router as inout_router
|
||||
from .modules.live import build_live_store
|
||||
from .modules.live import router as live_router
|
||||
from .modules.malaysia import build_malaysia_itemcode, build_malaysia_store
|
||||
from .modules.malaysia import router as malaysia_router
|
||||
from .modules.notice import build_notice_store
|
||||
@@ -65,6 +67,7 @@ MODULE_LABELS: dict[str, str] = {
|
||||
"asset": "자산관리",
|
||||
"inout": "입출고 관리",
|
||||
"outreach": "안내문 발송",
|
||||
"live": "라이브 커머스",
|
||||
"expense_approver": "개인경비",
|
||||
"vacation_approver": "휴가",
|
||||
}
|
||||
@@ -161,6 +164,7 @@ _MODULE_TEMPLATE_DIRS = [
|
||||
BASE_DIR / "modules" / "notice" / "templates",
|
||||
BASE_DIR / "modules" / "inout" / "templates",
|
||||
BASE_DIR / "modules" / "outreach" / "templates",
|
||||
BASE_DIR / "modules" / "live" / "templates",
|
||||
]
|
||||
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
||||
templates.env.loader = ChoiceLoader(
|
||||
@@ -233,6 +237,8 @@ app.state.inout_items = build_inout_items()
|
||||
# 안내문 발송(메일 일괄·인스타 DM 반자동): OUTREACH_DB_URL 없으면 store=None(화면이 "설정 필요" 안내).
|
||||
# 메일은 보내는 사람 본인 Gmail — 입출고 Gmail 연결(inout_store.inout_gmail_tokens)을 같이 쓴다.
|
||||
app.state.outreach_store = build_outreach_store(dsn=env("OUTREACH_DB_URL") or None)
|
||||
# 라이브 커머스(말레이시아 방송 호스트·스케줄): LIVE_DB_URL 없으면 store=None(화면이 "설정 필요" 안내).
|
||||
app.state.live_store = build_live_store(dsn=env("LIVE_DB_URL") or None)
|
||||
|
||||
# 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄.
|
||||
app.include_router(expense_router)
|
||||
@@ -247,6 +253,7 @@ app.include_router(asset_router)
|
||||
app.include_router(notice_router)
|
||||
app.include_router(inout_router)
|
||||
app.include_router(outreach_router)
|
||||
app.include_router(live_router)
|
||||
|
||||
|
||||
def public_url_for(request: Request, route_name: str) -> str:
|
||||
@@ -459,6 +466,16 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"status": "ready",
|
||||
"category": "운영",
|
||||
},
|
||||
{
|
||||
"key": "live",
|
||||
"title": "라이브 커머스",
|
||||
"subtitle": "Live Commerce",
|
||||
"description": "말레이시아 라이브 방송의 호스트 정보와 방송 스케줄·판매금액·결과 이미지를 관리합니다.",
|
||||
"url": "/live/",
|
||||
"health_url": "/live/health",
|
||||
"status": "ready",
|
||||
"category": "운영",
|
||||
},
|
||||
]
|
||||
items.append({
|
||||
"key": "asset", "title": "자산관리", "subtitle": "Asset Management",
|
||||
@@ -476,6 +493,7 @@ def _icon_svg(name: str) -> str:
|
||||
paths = {
|
||||
"inout": '<path d="M3 7l9-4 9 4v10l-9 4-9-4z"/><path d="M3 7l9 4 9-4"/><path d="M12 11v10"/>',
|
||||
"outreach": '<path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4z"/>',
|
||||
"live": '<rect x="2" y="6" width="14" height="12" rx="2"/><path d="m16 11 6-4v10l-6-4"/>',
|
||||
"asset": '<rect x="3" y="3" width="18" height="13" rx="2"/><path d="M8 21h8M12 16v5"/><path d="M7 7h10M7 11h6"/>',
|
||||
"home": '<path d="M3 11 12 3l9 8"/><path d="M5 10v10h14V10"/>',
|
||||
"expense": '<rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/><path d="M7 15h4"/>',
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# [라이브커머스] 라이브 커머스 모듈 — `app/modules/live/`, `live_db`(2026-11-04)
|
||||
|
||||
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 코드가 기준.
|
||||
> 정적 파일: `app/static/live.js`, `live.css`. 템플릿: `templates/live/`. 테스트: `tests/test_live.py`(`LIVE_TEST_DB_URL` 이 localhost 일 때 실제 DB).
|
||||
> 다른 모듈과 연결: 이미지 검사 = 자산 모듈 `app/modules/asset/media.py prepare_photo` 재사용(바꾸면 양쪽 확인).
|
||||
|
||||
- 말레이시아 라이브 커머스 방송의 호스트 정보·방송 스케줄. 권한키 `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`(이름·틱톡·사용 여부)만 넘긴다.
|
||||
사용 안 함 = 새 방송에서 못 고름(그 호스트로 이미 등록된 방송을 고칠 때만 보임). 방송 기록이 있는 호스트는 못 지움(FK RESTRICT).
|
||||
- **스케줄표** `/live/?month=YYYY-MM`(`live` 권한자 모두) — 호스트·날짜·시작/끝 시간·방송 장소·판매금액·결과 이미지. 호스트·날짜·시작 시간만 필수(판매금액은 방송 후 입력).
|
||||
시간은 입력한 말레이시아 시간 그대로(시간대 변환 없음, DATE·TIME). 판매금액 단위 RM(`NUMERIC(14,2)`, `store.parse_money`). 끝 시간이 시작보다 이르면 자정을 넘긴 방송.
|
||||
- **결과 이미지** — 방송 저장과 한 트랜잭션, JPG·PNG·WebP, 한 장 8MB, 방송당 10장(`store.MAX_IMAGES`). `prepare_photo` 가 실제 이미지 확인·긴 변 2400px·EXIF(GPS 등) 제거. BYTEA 저장.
|
||||
`GET /live/images/{id}`(권한 필요, 하루 private 캐시), `?thumb=1` = 160px JPEG(그때그때 만듦). 올린 뒤 내용이 안 바뀐다는 전제 — 이미지를 고치는 기능을 넣으면 캐시도 바꿀 것.
|
||||
- 저장은 `live.js` 가 fetch → JSON `{ok, message}`(틀려도 창의 입력값 유지). 창 하나로 추가·고치기(`data-edit` JSON).
|
||||
@@ -0,0 +1,21 @@
|
||||
"""라이브 커머스(live) 모듈 — 말레이시아 라이브 방송의 호스트 정보와 방송 스케줄(2026-11-04).
|
||||
|
||||
- 라우터: `router.py` (prefix=/live) · 저장소: `db.py` (live_db) · 순수 함수: `store.py`(입력 검사·표시 형식)
|
||||
- 템플릿: `templates/live/`, 화면 스크립트·스타일 `static/live.{js,css}`
|
||||
|
||||
LIVE_DB_URL 미설정이면 build_live_store 가 None → 화면이 "설정 필요" 안내(앱은 죽지 않음). 권한키 `live`.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from .router import router
|
||||
|
||||
__all__ = ["router", "build_live_store"]
|
||||
|
||||
|
||||
def build_live_store(*, dsn: str | None) -> Any:
|
||||
if not dsn:
|
||||
return None
|
||||
from .db import LiveDBStore # 지연 import
|
||||
|
||||
return LiveDBStore(dsn)
|
||||
@@ -0,0 +1,129 @@
|
||||
"""live_db PostgreSQL 저장소 — 라이브 커머스 호스트·방송 스케줄·결과 이미지(2026-11-04).
|
||||
|
||||
- 연결: 환경변수 `LIVE_DB_URL` (예: postgresql://live_app:<pwd>@postgres-db:5432/live_db)
|
||||
- 스키마는 앱이 만들지 않는다 — `scripts/sql/live_db_init.sql` 을 superuser 가 먼저 적용(앱 계정은 CRUD 만).
|
||||
- 연결 풀은 lazy open — 부팅 때 DB 가 잠시 끊겨도 컨테이너가 죽지 않게(다른 모듈과 같은 방식).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
|
||||
from psycopg.errors import ForeignKeyViolation
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from . import store
|
||||
|
||||
_HOST_COLUMNS = ("full_name", "phone", "email", "address", "bank_name", "bank_account", "tiktok_handle")
|
||||
|
||||
|
||||
class LiveDBStore:
|
||||
def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 4):
|
||||
self._pool = ConnectionPool(conninfo=dsn, min_size=min_size, max_size=max_size,
|
||||
kwargs={"row_factory": dict_row, "autocommit": True}, open=False)
|
||||
self._pool.open(wait=False)
|
||||
|
||||
def close(self) -> None:
|
||||
self._pool.close()
|
||||
|
||||
# ── 호스트 ─────────────────────────────────────────────
|
||||
def list_hosts(self) -> list[dict[str, Any]]:
|
||||
"""전체 정보(계좌 포함) — 설정 화면(ERP 관리자)에서만 쓴다."""
|
||||
with self._pool.connection() as conn:
|
||||
return conn.execute("SELECT * FROM live_hosts ORDER BY is_active DESC, full_name, id").fetchall()
|
||||
|
||||
def host_choices(self) -> list[dict[str, Any]]:
|
||||
"""스케줄 화면 호스트 고르기 — 개인정보·계좌는 뺀다."""
|
||||
with self._pool.connection() as conn:
|
||||
return conn.execute("SELECT id, full_name, tiktok_handle, is_active FROM live_hosts "
|
||||
"ORDER BY full_name, id").fetchall()
|
||||
|
||||
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",
|
||||
(*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",
|
||||
(*cols, is_active, by, host_id)).fetchone()
|
||||
if not row:
|
||||
raise ValueError("호스트를 찾을 수 없습니다.")
|
||||
return int(row["id"])
|
||||
|
||||
def delete_host(self, host_id: int) -> None:
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute("DELETE FROM live_hosts WHERE id=%s RETURNING id", (host_id,)).fetchone()
|
||||
except ForeignKeyViolation:
|
||||
raise ValueError("방송 기록이 있는 호스트는 지울 수 없습니다 — 사용 안 함으로 바꾸세요.") from None
|
||||
if not row:
|
||||
raise ValueError("호스트를 찾을 수 없습니다.")
|
||||
|
||||
# ── 방송 스케줄 ─────────────────────────────────────────
|
||||
def list_broadcasts(self, start: date, end: date) -> list[dict[str, Any]]:
|
||||
"""start 이상 end 미만, 날짜·시간 순. 줄마다 images = [{id, filename}](내용 제외)."""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT b.*, h.full_name AS host_name, h.tiktok_handle FROM live_broadcasts b JOIN live_hosts h ON h.id = b.host_id "
|
||||
"WHERE b.broadcast_date >= %s AND b.broadcast_date < %s ORDER BY b.broadcast_date, b.start_time, b.id",
|
||||
(start, end)).fetchall()
|
||||
images = conn.execute(
|
||||
"SELECT id, broadcast_id, filename FROM live_broadcast_images WHERE broadcast_id = ANY(%s) ORDER BY id",
|
||||
([r["id"] for r in rows],)).fetchall()
|
||||
for r in rows:
|
||||
r["images"] = [i for i in images if i["broadcast_id"] == r["id"]]
|
||||
return rows
|
||||
|
||||
def save_broadcast(self, broadcast_id: int | None, values: dict[str, Any], images: list[dict[str, Any]], *, by: str) -> int:
|
||||
"""방송·이미지를 한 트랜잭션으로. 사용 안 함 호스트는 이미 그 호스트인 방송을 고칠 때만 허용."""
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
current = None
|
||||
if broadcast_id is not None:
|
||||
found = conn.execute("SELECT host_id FROM live_broadcasts WHERE id=%s FOR UPDATE", (broadcast_id,)).fetchone()
|
||||
if not found:
|
||||
raise ValueError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
|
||||
current = found["host_id"]
|
||||
host = conn.execute("SELECT is_active FROM live_hosts WHERE id=%s", (values["host_id"],)).fetchone()
|
||||
if not host:
|
||||
raise ValueError("호스트를 찾을 수 없습니다.")
|
||||
if not host["is_active"] and values["host_id"] != current:
|
||||
raise ValueError("사용 안 함으로 바뀐 호스트입니다 — 다른 호스트를 고르세요.")
|
||||
args = (values["host_id"], values["broadcast_date"], values["start_time"], values["end_time"], values["venue"],
|
||||
values["sales_amount"], 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"])
|
||||
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))
|
||||
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 ValueError(f"방송 한 건에 이미지는 {store.MAX_IMAGES}장까지입니다(지금 {have}장).")
|
||||
for im in images:
|
||||
conn.execute("INSERT INTO live_broadcast_images (broadcast_id, filename, content_type, data, width, height, created_by) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s)",
|
||||
(broadcast_id, im["filename"], im["content_type"], im["data"], im["width"], im["height"], by))
|
||||
return broadcast_id
|
||||
|
||||
def delete_broadcast(self, broadcast_id: int) -> None:
|
||||
with self._pool.connection() as conn:
|
||||
if not conn.execute("DELETE FROM live_broadcasts WHERE id=%s RETURNING id", (broadcast_id,)).fetchone():
|
||||
raise ValueError("방송을 찾을 수 없습니다.")
|
||||
|
||||
# ── 결과 이미지 ─────────────────────────────────────────
|
||||
def get_image(self, image_id: int) -> dict[str, Any] | None:
|
||||
with self._pool.connection() as conn:
|
||||
return conn.execute("SELECT content_type, data FROM live_broadcast_images WHERE id=%s", (image_id,)).fetchone()
|
||||
|
||||
def delete_image(self, image_id: int) -> None:
|
||||
with self._pool.connection() as conn:
|
||||
if not conn.execute("DELETE FROM live_broadcast_images WHERE id=%s RETURNING id", (image_id,)).fetchone():
|
||||
raise ValueError("이미지를 찾을 수 없습니다.")
|
||||
@@ -0,0 +1,239 @@
|
||||
"""라이브 커머스(live) 라우터 — 말레이시아 라이브 방송의 호스트 정보·방송 스케줄(2026-11-04).
|
||||
|
||||
GET /live/ 스케줄표(?month=YYYY-MM)
|
||||
POST /live/broadcasts 방송 추가·고치기(id 칸이 있으면 고치기) + 결과 이미지 올리기
|
||||
POST /live/broadcasts/{id}/delete 방송 지우기(이미지도 함께)
|
||||
GET /live/images/{id} 결과 이미지(?thumb=1 = 작은 그림) · POST /live/images/{id}/delete
|
||||
GET /live/settings 설정 — 호스트 정보(ERP 관리자만, 계좌 등 개인정보)
|
||||
POST /live/settings/hosts 호스트 추가·고치기 · POST /live/settings/hosts/{id}/delete
|
||||
권한: 모듈 권한키 `live`(스케줄), 설정은 ERP 관리자. DB: LIVE_DB_URL(live_db) — 없으면 "설정 필요" 안내.
|
||||
저장 요청은 live.js 가 fetch 로 보내고 JSON {ok, message} 를 받는다(틀려도 입력한 값이 창에 남게).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import PurePath
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, Response
|
||||
|
||||
from app.modules.asset.media import MAX_PHOTO_BYTES, prepare_photo
|
||||
from app.timezone import today_kst
|
||||
|
||||
from . import store
|
||||
|
||||
router = APIRouter(prefix="/live", tags=["live"])
|
||||
|
||||
|
||||
def _store(request: Request) -> Any:
|
||||
return getattr(request.app.state, "live_store", None)
|
||||
|
||||
|
||||
def _user(request: Request) -> dict[str, Any]:
|
||||
from app.main import get_current_user_record # noqa: WPS433
|
||||
from app.store import has_module # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
|
||||
if not has_module(user, "live"):
|
||||
raise HTTPException(status_code=403, detail="라이브 커머스 모듈 권한이 없습니다.")
|
||||
return user
|
||||
|
||||
|
||||
def _admin(request: Request) -> dict[str, Any]:
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
user = _user(request)
|
||||
if not is_admin(user):
|
||||
raise HTTPException(status_code=403, detail="호스트 정보는 ERP 관리자만 볼 수 있습니다.")
|
||||
return user
|
||||
|
||||
|
||||
def _db(request: Request) -> Any:
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
raise HTTPException(status_code=503, detail="라이브 커머스 DB(LIVE_DB_URL)가 설정되지 않았습니다.")
|
||||
return st
|
||||
|
||||
|
||||
def _page(request: Request) -> Any:
|
||||
"""화면 공통 — (st, user) 또는 응답(로그인·권한·설정 필요)."""
|
||||
from app.main import build_erp_nav, get_current_user_record, render_template # noqa: WPS433
|
||||
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return login_redirect(request)
|
||||
if not has_module(user, "live"):
|
||||
return render_template(request, "denied.html", {"reason": "라이브 커머스 모듈 접근 권한이 없습니다.",
|
||||
"is_admin": is_admin(user)}, status_code=403)
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
return render_template(request, "denied.html", {
|
||||
"reason": "라이브 커머스 모듈이 아직 설정되지 않았습니다. scripts/sql/live_db_init.sql 로 live_db 를 만들고 "
|
||||
".env 에 LIVE_DB_URL 을 넣은 뒤 컨테이너를 다시 시작하세요.",
|
||||
"user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active="live")}, status_code=503)
|
||||
return st, user
|
||||
|
||||
|
||||
def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, Any]) -> HTMLResponse:
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
return render_template(request, name, {"user": user, "is_admin": is_admin(user),
|
||||
"nav_items": build_erp_nav(user, active="live"), **ctx})
|
||||
|
||||
|
||||
def _ok(message: str) -> JSONResponse:
|
||||
return JSONResponse({"ok": True, "message": message})
|
||||
|
||||
|
||||
def _fail(exc: Exception) -> JSONResponse:
|
||||
return JSONResponse({"ok": False, "message": str(exc)}, status_code=400)
|
||||
|
||||
|
||||
def _opt_id(raw: str) -> int | None:
|
||||
s = (raw or "").strip()
|
||||
if not s:
|
||||
return None
|
||||
if not s.isdigit():
|
||||
raise ValueError("잘못된 요청입니다.")
|
||||
return int(s)
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health(request: Request) -> JSONResponse:
|
||||
return JSONResponse({"status": "ok" if _store(request) is not None else "not_configured"})
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# 스케줄표
|
||||
# ────────────────────────────────────────────────────────────
|
||||
@router.get("/", response_class=HTMLResponse)
|
||||
def index(request: Request, month: str = "") -> Any:
|
||||
got = _page(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
span = store.month_range(month, today_kst())
|
||||
rows = []
|
||||
for b in st.list_broadcasts(span["start"], span["end"]):
|
||||
rows.append({
|
||||
"date": store.fmt_date(b["broadcast_date"]), "times": store.fmt_times(b["start_time"], b["end_time"]),
|
||||
"host_name": b["host_name"], "tiktok_handle": b["tiktok_handle"], "venue": b["venue"],
|
||||
"sales": store.fmt_money(b["sales_amount"]), "images": b["images"],
|
||||
"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 "",
|
||||
"images": [{"id": i["id"], "filename": i["filename"]} for i in b["images"]]},
|
||||
})
|
||||
return _render(request, "live/index.html", user, {"span": span, "rows": rows, "hosts": st.host_choices(),
|
||||
"max_images": store.MAX_IMAGES})
|
||||
|
||||
|
||||
def _read_images(files: list[UploadFile]) -> list[dict[str, Any]]:
|
||||
"""고른 파일을 실제 이미지로 확인·메타데이터 제거(GPS 등). 틀리면 ValueError — 아무것도 저장하지 않게 DB 전에."""
|
||||
picked = [f for f in files if f.filename]
|
||||
if len(picked) > store.MAX_IMAGES:
|
||||
raise ValueError(f"방송 한 건에 이미지는 {store.MAX_IMAGES}장까지입니다.")
|
||||
out = []
|
||||
for f in picked:
|
||||
name = PurePath(f.filename.replace("\\", "/")).name[:200]
|
||||
try:
|
||||
data, ctype, width, height = prepare_photo(f.file.read(MAX_PHOTO_BYTES + 1))
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"{name}: {exc}") from None
|
||||
out.append({"filename": name, "content_type": ctype, "data": data, "width": width, "height": height})
|
||||
return out
|
||||
|
||||
|
||||
@router.post("/broadcasts")
|
||||
def broadcast_save(request: Request, id: str = Form(""), host_id: str = Form(""), broadcast_date: str = Form(""),
|
||||
start_time: str = Form(""), end_time: str = Form(""), venue: str = Form(""), sales_amount: 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})
|
||||
st.save_broadcast(broadcast_id, values, _read_images(images), by=user.get("email", ""))
|
||||
except ValueError as exc:
|
||||
return _fail(exc)
|
||||
return _ok("저장했습니다.")
|
||||
|
||||
|
||||
@router.post("/broadcasts/{broadcast_id}/delete")
|
||||
def broadcast_delete(request: Request, broadcast_id: int) -> JSONResponse:
|
||||
_user(request)
|
||||
try:
|
||||
_db(request).delete_broadcast(broadcast_id)
|
||||
except ValueError as exc:
|
||||
return _fail(exc)
|
||||
return _ok("방송을 지웠습니다.")
|
||||
|
||||
|
||||
@router.get("/images/{image_id}")
|
||||
def image(request: Request, image_id: int, thumb: int = 0) -> Response:
|
||||
_user(request)
|
||||
row = _db(request).get_image(image_id)
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="이미지를 찾을 수 없습니다.")
|
||||
data, ctype = (store.thumbnail(row["data"]), "image/jpeg") if thumb else (bytes(row["data"]), row["content_type"])
|
||||
# 올린 뒤 내용이 바뀌지 않으므로 하루 캐시. 권한이 필요한 이미지라 private.
|
||||
return Response(data, media_type=ctype, headers={"Cache-Control": "private, max-age=86400", "X-Content-Type-Options": "nosniff"})
|
||||
|
||||
|
||||
@router.post("/images/{image_id}/delete")
|
||||
def image_delete(request: Request, image_id: int) -> JSONResponse:
|
||||
_user(request)
|
||||
try:
|
||||
_db(request).delete_image(image_id)
|
||||
except ValueError as exc:
|
||||
return _fail(exc)
|
||||
return _ok("이미지를 지웠습니다.")
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# 설정 — 호스트 정보(ERP 관리자만: 계좌 등 개인정보)
|
||||
# ────────────────────────────────────────────────────────────
|
||||
@router.get("/settings", response_class=HTMLResponse)
|
||||
def settings(request: Request) -> Any:
|
||||
from app.main import render_template # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
got = _page(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
if not is_admin(user):
|
||||
return render_template(request, "denied.html", {"reason": "호스트 정보는 ERP 관리자만 볼 수 있습니다.", "is_admin": False},
|
||||
status_code=403)
|
||||
return _render(request, "live/settings.html", user, {"hosts": st.list_hosts()})
|
||||
|
||||
|
||||
@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(""),
|
||||
is_active: str = Form("")) -> JSONResponse:
|
||||
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", ""))
|
||||
except ValueError as exc:
|
||||
return _fail(exc)
|
||||
return _ok("호스트를 저장했습니다.")
|
||||
|
||||
|
||||
@router.post("/settings/hosts/{host_id}/delete")
|
||||
def host_delete(request: Request, host_id: int) -> JSONResponse:
|
||||
_admin(request)
|
||||
try:
|
||||
_db(request).delete_host(host_id)
|
||||
except ValueError as exc:
|
||||
return _fail(exc)
|
||||
return _ok("호스트를 지웠습니다.")
|
||||
@@ -0,0 +1,132 @@
|
||||
"""라이브 커머스 순수 함수 — 입력 검사·표시 형식(DB 없이 시험 가능)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import re
|
||||
from datetime import date, time
|
||||
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from PIL import Image
|
||||
|
||||
MAX_IMAGES = 10 # 방송 한 건에
|
||||
MAX_SALES = Decimal("999999999999.99")
|
||||
THUMB_SIZE = 160
|
||||
|
||||
HOST_LIMITS = {"full_name": 200, "phone": 40, "email": 254, "address": 500, "bank_name": 100, "bank_account": 40, "tiktok_handle": 64}
|
||||
_LABELS = {"full_name": "Full Name", "phone": "Phone Number", "email": "Email", "address": "Address", "bank_name": "Bank Name",
|
||||
"bank_account": "Bank Account Number", "tiktok_handle": "Tiktok Handle"}
|
||||
_EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+\-']+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$")
|
||||
_PHONE_RE = re.compile(r"^\+?[0-9()\-\s]+$")
|
||||
_ACCOUNT_RE = re.compile(r"^[0-9\-\s]+$")
|
||||
_HANDLE_RE = re.compile(r"^[A-Za-z0-9._]+$")
|
||||
_HANDLE_URL_RE = re.compile(r"^(?:https?://)?(?:www\.|m\.)?tiktok\.com/@?", re.I)
|
||||
WEEKDAYS_KO = "월화수목금토일"
|
||||
|
||||
|
||||
def clean_handle(raw: Any) -> str:
|
||||
"""'@name'·'https://www.tiktok.com/@name?lang=en' → 'name'."""
|
||||
s = _HANDLE_URL_RE.sub("", str(raw or "").strip())
|
||||
return re.split(r"[/?#]", s, maxsplit=1)[0].lstrip("@")
|
||||
|
||||
|
||||
def clean_host(values: dict[str, Any]) -> dict[str, str]:
|
||||
"""호스트 입력 검사 — Full Name 만 필수, 나머지는 있으면 형식 확인. 틀리면 ValueError."""
|
||||
out = {k: str(values.get(k) or "").strip() for k in HOST_LIMITS}
|
||||
out["tiktok_handle"] = clean_handle(values.get("tiktok_handle"))
|
||||
if not out["full_name"]:
|
||||
raise ValueError("Full Name (as per IC) 을 입력하세요.")
|
||||
for key, limit in HOST_LIMITS.items():
|
||||
if len(out[key]) > limit:
|
||||
raise ValueError(f"{_LABELS[key]} 이(가) 너무 깁니다({limit}자까지).")
|
||||
if out["email"] and not _EMAIL_RE.match(out["email"]):
|
||||
raise ValueError("Email 형식이 올바르지 않습니다.")
|
||||
if out["phone"] and not _PHONE_RE.match(out["phone"]):
|
||||
raise ValueError("Phone Number 는 숫자·+·-·괄호만 입력하세요.")
|
||||
if out["bank_account"] and not _ACCOUNT_RE.match(out["bank_account"]):
|
||||
raise ValueError("Bank Account Number 는 숫자·-만 입력하세요.")
|
||||
if out["tiktok_handle"] and not _HANDLE_RE.match(out["tiktok_handle"]):
|
||||
raise ValueError("Tiktok Handle 은 영문·숫자·밑줄·점만 입력하세요.")
|
||||
return out
|
||||
|
||||
|
||||
def parse_money(raw: Any) -> 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 ValueError("판매금액은 숫자로 입력하세요.") from None
|
||||
if not n.is_finite() or n < 0:
|
||||
raise ValueError("판매금액은 0 이상 숫자로 입력하세요.")
|
||||
if n > MAX_SALES:
|
||||
raise ValueError("판매금액이 너무 큽니다.")
|
||||
return n.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||
|
||||
|
||||
def _parse_time(raw: Any, *, label: str, required: bool) -> time | None:
|
||||
s = str(raw or "").strip()
|
||||
if not s:
|
||||
if required:
|
||||
raise ValueError(f"{label}을 입력하세요.")
|
||||
return None
|
||||
try:
|
||||
return time.fromisoformat(s).replace(second=0, microsecond=0, tzinfo=None)
|
||||
except ValueError:
|
||||
raise ValueError(f"{label}이 올바르지 않습니다.") from None
|
||||
|
||||
|
||||
def clean_broadcast(values: dict[str, Any]) -> dict[str, Any]:
|
||||
"""방송 입력 검사 — 호스트·날짜·시작 시간 필수. 끝 시간이 시작보다 이르면 자정을 넘긴 방송으로 본다. 틀리면 ValueError."""
|
||||
host = str(values.get("host_id") or "").strip()
|
||||
if not host.isdigit():
|
||||
raise ValueError("호스트를 고르세요.")
|
||||
try:
|
||||
day = date.fromisoformat(str(values.get("broadcast_date") or "").strip())
|
||||
except ValueError:
|
||||
raise ValueError("방송 날짜를 입력하세요.") from None
|
||||
venue = str(values.get("venue") or "").strip()
|
||||
if len(venue) > 200:
|
||||
raise ValueError("방송 장소가 너무 깁니다(200자까지).")
|
||||
return {"host_id": int(host), "broadcast_date": day,
|
||||
"start_time": _parse_time(values.get("start_time"), label="시작 시간", required=True),
|
||||
"end_time": _parse_time(values.get("end_time"), label="끝 시간", required=False),
|
||||
"venue": venue, "sales_amount": parse_money(values.get("sales_amount"))}
|
||||
|
||||
|
||||
def month_range(raw: Any, today: date) -> dict[str, Any]:
|
||||
"""'YYYY-MM'(틀리거나 없으면 이번 달) → 그 달 첫날·다음 달 첫날·앞뒤 달 주소 값·제목."""
|
||||
m = re.fullmatch(r"(\d{4})-(\d{2})", str(raw or "").strip())
|
||||
year, month = (int(m[1]), int(m[2])) if m and 2000 <= int(m[1]) <= 2100 and 1 <= int(m[2]) <= 12 else (today.year, today.month)
|
||||
start = date(year, month, 1)
|
||||
end = date(year + (month == 12), month % 12 + 1, 1)
|
||||
prev = date(year - (month == 1), (month - 2) % 12 + 1, 1)
|
||||
return {"start": start, "end": end, "prev": prev.strftime("%Y-%m"), "next": end.strftime("%Y-%m"),
|
||||
"label": f"{year}년 {month}월"}
|
||||
|
||||
|
||||
def fmt_date(d: date) -> str:
|
||||
return f"{d:%Y.%m.%d}({WEEKDAYS_KO[d.weekday()]})"
|
||||
|
||||
|
||||
def fmt_times(start: time, end: time | None) -> str:
|
||||
return f"{start:%H:%M}" + (f" ~ {end:%H:%M}" if end else "")
|
||||
|
||||
|
||||
def fmt_money(n: Decimal | None) -> str:
|
||||
return f"{n:,.2f}" if n is not None else ""
|
||||
|
||||
|
||||
def thumbnail(data: bytes) -> bytes:
|
||||
"""목록 작은 그림 — JPEG(투명은 흰 바탕). 저장할 때 이미 확인한 이미지만 들어온다."""
|
||||
with Image.open(io.BytesIO(data)) as source:
|
||||
source.thumbnail((THUMB_SIZE, THUMB_SIZE))
|
||||
rgba = source.convert("RGBA")
|
||||
canvas = Image.new("RGB", rgba.size, "white")
|
||||
canvas.paste(rgba, mask=rgba.getchannel("A"))
|
||||
out = io.BytesIO()
|
||||
canvas.save(out, format="JPEG", quality=80)
|
||||
return out.getvalue()
|
||||
@@ -0,0 +1,77 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{#- 라이브 커머스 스케줄표(2026-11-04) — 달마다 방송 목록. 추가·고치기는 같은 창(live.js). 호스트 고르기엔 이름·틱톡만(계좌 등은 설정 화면). -#}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261104a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="lv">
|
||||
<div class="lv-bar">
|
||||
<a class="erp-btn erp-btn-outline" href="/live/?month={{ span.prev }}" aria-label="이전 달">◀</a>
|
||||
<h2 class="lv-month">{{ span.label }}</h2>
|
||||
<a class="erp-btn erp-btn-outline" href="/live/?month={{ span.next }}" aria-label="다음 달">▶</a>
|
||||
<span class="lv-gap"></span>
|
||||
{% if is_admin %}<a class="erp-btn erp-btn-outline" href="/live/settings">호스트 설정</a>{% endif %}
|
||||
<button type="button" class="erp-btn erp-btn-primary" id="lv-add"{% if not hosts | selectattr('is_active') | list %} disabled{% endif %}>+ 방송 추가</button>
|
||||
</div>
|
||||
{% if not hosts | selectattr('is_active') | list %}
|
||||
<p class="lv-note">방송을 추가하려면 먼저 {% if is_admin %}<a href="/live/settings">호스트 설정</a>에서{% else %}ERP 관리자가 호스트 설정에서{% endif %} 호스트를 등록해야 합니다.</p>
|
||||
{% endif %}
|
||||
|
||||
<div class="erp-card-block">
|
||||
<div class="erp-table-wrap">
|
||||
<table class="erp-table lv-table">
|
||||
<thead><tr><th>날짜</th><th>시간</th><th>호스트</th><th>방송 장소</th><th class="lv-r">판매금액(RM)</th><th>방송 결과</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in rows %}
|
||||
<tr>
|
||||
<td class="lv-nowrap" data-label="날짜">{{ r.date }}</td>
|
||||
<td class="lv-nowrap" data-label="시간">{{ r.times }}</td>
|
||||
<td data-label="호스트">{{ r.host_name }}{% if r.tiktok_handle %}<div class="lv-sub">@{{ r.tiktok_handle }}</div>{% endif %}</td>
|
||||
<td data-label="방송 장소">{{ r.venue }}</td>
|
||||
<td class="lv-r lv-num" data-label="판매금액(RM)">{{ r.sales }}</td>
|
||||
<td data-label="방송 결과"><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 }}'>고치기</button>
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-post="/live/broadcasts/{{ r.edit.id }}/delete" data-confirm="{{ r.date }} {{ r.host_name }} 방송을 지울까요? 결과 이미지도 함께 지워집니다.">지우기</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="7" class="erp-empty">이 달에 등록한 방송이 없습니다.</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<dialog class="lv-dlg" id="lv-dlg" aria-labelledby="lv-dlg-title">
|
||||
<form id="lv-form" action="/live/broadcasts">
|
||||
<h3 id="lv-dlg-title" data-add="방송 추가" data-edit="방송 고치기"></h3>
|
||||
<input type="hidden" name="id" />
|
||||
<label class="lv-field">호스트
|
||||
<select class="erp-select" name="host_id" required>
|
||||
<option value="">호스트를 고르세요</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 %} — 사용 안 함{% endif %}</option>{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<div class="lv-row">
|
||||
<label class="lv-field">방송 날짜 <input class="erp-input" type="date" name="broadcast_date" required /></label>
|
||||
<label class="lv-field">시작 시간 <input class="erp-input" type="time" name="start_time" required /></label>
|
||||
<label class="lv-field">끝 시간 <input class="erp-input" type="time" name="end_time" /></label>
|
||||
</div>
|
||||
<p class="lv-sub">시간은 말레이시아 시간으로 입력합니다.</p>
|
||||
<label class="lv-field">방송 장소 <input class="erp-input" type="text" name="venue" maxlength="200" /></label>
|
||||
<label class="lv-field">판매금액 (RM) <input class="erp-input lv-num" type="text" name="sales_amount" inputmode="decimal" placeholder="방송 후 입력" /></label>
|
||||
<label class="lv-field">방송 결과 이미지 (JPG·PNG·WebP, 한 장 8MB, 방송당 {{ max_images }}장까지)
|
||||
<input type="file" name="images" accept="image/jpeg,image/png,image/webp" multiple />
|
||||
</label>
|
||||
<ul class="lv-saved" data-saved hidden></ul>
|
||||
<p class="lv-msg" data-msg role="alert" hidden></p>
|
||||
<div class="lv-foot">
|
||||
<button type="button" class="erp-btn erp-btn-outline" data-close>취소</button>
|
||||
<button type="submit" class="erp-btn erp-btn-primary">저장</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/live.js?v=20261104a" defer></script>{% endblock %}
|
||||
@@ -0,0 +1,66 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{#- 라이브 커머스 설정(2026-11-04) — 호스트 정보. 계좌 등 개인정보라 ERP 관리자만(router.settings). 추가·고치기는 같은 창(live.js). -#}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261104a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="lv">
|
||||
<div class="lv-bar">
|
||||
<a class="erp-btn erp-btn-outline" href="/live/">◀ 스케줄표</a>
|
||||
<h2 class="lv-month">호스트 설정</h2>
|
||||
<span class="lv-gap"></span>
|
||||
<button type="button" class="erp-btn erp-btn-primary" id="lv-add">+ 호스트 등록</button>
|
||||
</div>
|
||||
|
||||
<div class="erp-card-block">
|
||||
<div class="erp-table-wrap">
|
||||
<table class="erp-table lv-table">
|
||||
<thead><tr><th>Full Name (as per IC)</th><th>Phone Number</th><th>Email</th><th>Address</th><th>Bank Name</th><th>Bank Account Number</th><th>Tiktok Handle</th><th>상태</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for h in hosts %}
|
||||
<tr{% if not h.is_active %} class="lv-off"{% endif %}>
|
||||
<td data-label="Full Name (as per IC)">{{ h.full_name }}</td>
|
||||
<td class="lv-nowrap" data-label="Phone Number">{{ h.phone }}</td>
|
||||
<td data-label="Email">{{ h.email }}</td>
|
||||
<td data-label="Address">{{ h.address }}</td>
|
||||
<td data-label="Bank Name">{{ h.bank_name }}</td>
|
||||
<td class="lv-nowrap" data-label="Bank Account Number">{{ h.bank_account }}</td>
|
||||
<td data-label="Tiktok Handle">{% if h.tiktok_handle %}@{{ h.tiktok_handle }}{% endif %}</td>
|
||||
<td class="lv-nowrap" data-label="상태">{{ '사용' if h.is_active else '사용 안 함' }}</td>
|
||||
<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 }}'>고치기</button>
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-post="/live/settings/hosts/{{ h.id }}/delete" data-confirm="{{ h.full_name }} 호스트를 지울까요?">지우기</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="9" class="erp-empty">등록한 호스트가 없습니다.</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<dialog class="lv-dlg" id="lv-dlg" aria-labelledby="lv-dlg-title">
|
||||
<form id="lv-form" action="/live/settings/hosts">
|
||||
<h3 id="lv-dlg-title" data-add="호스트 등록" data-edit="호스트 고치기"></h3>
|
||||
<input type="hidden" name="id" />
|
||||
<label class="lv-field">Full Name (as per IC) <input class="erp-input" type="text" name="full_name" maxlength="200" required /></label>
|
||||
<label class="lv-field">Phone Number <input class="erp-input" type="tel" name="phone" maxlength="40" /></label>
|
||||
<label class="lv-field">Email <input class="erp-input" type="email" name="email" maxlength="254" /></label>
|
||||
<label class="lv-field">Address <textarea class="erp-input" name="address" rows="2" maxlength="500"></textarea></label>
|
||||
<div class="lv-row">
|
||||
<label class="lv-field">Bank Name <input class="erp-input" type="text" name="bank_name" maxlength="100" /></label>
|
||||
<label class="lv-field">Bank Account Number <input class="erp-input" type="text" name="bank_account" maxlength="40" inputmode="numeric" /></label>
|
||||
</div>
|
||||
<label class="lv-field">Tiktok Handle <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 /> 사용 (끄면 새 방송에서 고를 수 없습니다)</label>
|
||||
<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>취소</button>
|
||||
<button type="submit" class="erp-btn erp-btn-primary">저장</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/live.js?v=20261104a" defer></script>{% endblock %}
|
||||
@@ -0,0 +1,43 @@
|
||||
/* 라이브 커머스(2026-11-04) — 스케줄표·호스트 설정 */
|
||||
.erp-page:has(> .lv) { box-sizing: border-box; } /* 공용 .erp-page 는 폭 100% + 안쪽 여백이라 그대로면 화면보다 넓어진다 */
|
||||
.lv { display: flex; flex-direction: column; gap: 14px; min-width: 0; }
|
||||
.lv *, .lv-dlg *, .lv-dlg *::before, .lv-dlg *::after { box-sizing: border-box; }
|
||||
.lv-dlg [hidden] { display: none !important; }
|
||||
.lv-bar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.lv-gap { flex: 1 1 auto; }
|
||||
.lv-month { margin: 0 6px; font-size: 18px; font-weight: 600; white-space: nowrap; }
|
||||
.lv-note { margin: 0; padding: 10px 14px; border-radius: 8px; background: #eef6ff; color: #0b4a8b; border: 1px solid #cfe3fb; font-size: 13px; }
|
||||
|
||||
.lv-table td { vertical-align: middle; overflow-wrap: anywhere; }
|
||||
.lv-table th { white-space: nowrap; }
|
||||
.lv-table tr.lv-off td { color: var(--color-midtone-gray, #666); }
|
||||
.lv-r { text-align: right; }
|
||||
.lv-table th.lv-r { text-align: right; }
|
||||
.lv-num { font-variant-numeric: tabular-nums; }
|
||||
.lv-nowrap { white-space: nowrap; }
|
||||
.lv-sub { margin: 0; font-size: 12px; color: var(--color-midtone-gray, #666); }
|
||||
.lv-actions { white-space: nowrap; text-align: right; }
|
||||
.lv-thumbs { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
.lv-thumbs img { display: block; width: 44px; height: 44px; object-fit: cover; border-radius: 6px; border: 1px solid var(--color-subtle-ash, #e5e5e5); }
|
||||
|
||||
/* 공용 .erp-table 은 640px 아래에서 제목 줄을 숨기고 카드로 바뀐다 — 칸 이름을 칸마다 보여 준다 */
|
||||
@media (max-width: 640px) {
|
||||
.lv-table td[data-label]::before { content: attr(data-label); display: block; font-size: 12px; font-weight: 400; color: var(--color-midtone-gray, #666); text-align: left; }
|
||||
.lv-table td.lv-r { text-align: left; }
|
||||
}
|
||||
|
||||
.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); }
|
||||
.lv-dlg form { display: flex; flex-direction: column; gap: 12px; padding: 20px 22px; }
|
||||
.lv-dlg h3 { margin: 0; font-size: 17px; font-weight: 600; }
|
||||
.lv-field { display: flex; flex: 1 1 0; flex-direction: column; gap: 4px; min-width: 0; font-size: 13px; font-weight: 500; }
|
||||
.lv-field .erp-input, .lv-field .erp-select { width: 100%; min-width: 0; font-weight: 400; }
|
||||
.lv-field textarea { resize: vertical; }
|
||||
.lv-row { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
.lv-row .lv-field { flex-basis: 140px; }
|
||||
.lv-check { display: flex; align-items: center; gap: 6px; font-size: 13px; }
|
||||
.lv-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-foot { display: flex; justify-content: flex-end; gap: 8px; }
|
||||
@@ -0,0 +1,105 @@
|
||||
/* 라이브 커머스(2026-11-04) — 스케줄표·호스트 설정 공용: 추가·고치기 창, 저장·지우기(fetch → JSON {ok, message}, 틀려도 입력한 값이 창에 남음). */
|
||||
(function () {
|
||||
"use strict";
|
||||
const dlg = document.getElementById("lv-dlg");
|
||||
const form = document.getElementById("lv-form");
|
||||
if (!dlg || !form) return;
|
||||
const title = dlg.querySelector("#lv-dlg-title");
|
||||
const msg = form.querySelector("[data-msg]");
|
||||
const saved = form.querySelector("[data-saved]");
|
||||
const hostSelect = form.querySelector('select[name="host_id"]');
|
||||
const fileInput = form.querySelector('input[type="file"]');
|
||||
|
||||
function say(text) {
|
||||
msg.textContent = text || "";
|
||||
msg.hidden = !text;
|
||||
}
|
||||
|
||||
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 };
|
||||
} catch (_) {
|
||||
return { ok: false, message: "서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요." };
|
||||
}
|
||||
}
|
||||
|
||||
// 사용 안 함 호스트는 그 호스트로 이미 등록된 방송을 고칠 때만 보인다
|
||||
function showHosts(current) {
|
||||
if (!hostSelect) return;
|
||||
Array.from(hostSelect.options).forEach(function (opt) {
|
||||
const off = opt.dataset.inactive === "1" && opt.value !== String(current || "");
|
||||
opt.hidden = off;
|
||||
opt.disabled = off;
|
||||
});
|
||||
}
|
||||
|
||||
function showSaved(images) {
|
||||
if (!saved) return;
|
||||
saved.textContent = "";
|
||||
(images || []).forEach(function (im) {
|
||||
const li = document.createElement("li");
|
||||
const link = document.createElement("a");
|
||||
link.href = "/live/images/" + im.id;
|
||||
link.target = "_blank";
|
||||
link.rel = "noopener";
|
||||
link.textContent = im.filename || "이미지 " + im.id;
|
||||
const del = document.createElement("button");
|
||||
del.type = "button";
|
||||
del.className = "erp-btn erp-btn-outline erp-btn-sm";
|
||||
del.dataset.post = "/live/images/" + im.id + "/delete";
|
||||
del.dataset.confirm = (im.filename || "이 이미지") + " 를 지울까요?";
|
||||
del.textContent = "지우기";
|
||||
li.append(link, del);
|
||||
saved.appendChild(li);
|
||||
});
|
||||
saved.hidden = !saved.children.length;
|
||||
}
|
||||
|
||||
function open(row) {
|
||||
form.reset();
|
||||
say("");
|
||||
title.textContent = row ? title.dataset.edit : title.dataset.add;
|
||||
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 !== "file") el.value = row[el.name];
|
||||
});
|
||||
if (!row) form.elements.id.value = "";
|
||||
showHosts(row && row.host_id);
|
||||
if (row && hostSelect) hostSelect.value = String(row.host_id); // 위에서 보이게 한 뒤 다시 고름
|
||||
showSaved(row && row.images);
|
||||
dlg.showModal();
|
||||
}
|
||||
|
||||
const addBtn = document.getElementById("lv-add");
|
||||
if (addBtn) addBtn.addEventListener("click", function () { open(null); });
|
||||
dlg.addEventListener("click", function (e) {
|
||||
if (e.target.closest("[data-close]")) dlg.close();
|
||||
});
|
||||
|
||||
document.addEventListener("click", async function (e) {
|
||||
const edit = e.target.closest("[data-edit]");
|
||||
if (edit && edit.tagName === "BUTTON") { open(JSON.parse(edit.dataset.edit)); return; }
|
||||
const btn = e.target.closest("button[data-post]");
|
||||
if (!btn) return;
|
||||
if (!(await window.erpConfirm(btn.dataset.confirm))) return;
|
||||
const r = await post(btn.dataset.post);
|
||||
if (r.ok) { location.reload(); return; }
|
||||
if (dlg.open) say(r.message); else window.erpAlert(r.message);
|
||||
});
|
||||
|
||||
form.addEventListener("submit", async function (e) {
|
||||
e.preventDefault();
|
||||
const save = form.querySelector('button[type="submit"]');
|
||||
const body = new FormData(form);
|
||||
if (fileInput && !fileInput.files.length) body.delete("images");
|
||||
save.disabled = true;
|
||||
say("");
|
||||
const r = await post(form.getAttribute("action"), body);
|
||||
if (r.ok) { location.reload(); return; }
|
||||
save.disabled = false;
|
||||
say(r.message);
|
||||
});
|
||||
})();
|
||||
@@ -39,6 +39,7 @@ MODULE_KEYS: tuple[str, ...] = (
|
||||
"asset",
|
||||
"inout",
|
||||
"outreach",
|
||||
"live",
|
||||
"expense_approver",
|
||||
"vacation_approver",
|
||||
)
|
||||
|
||||
@@ -305,6 +305,17 @@ DDL: `scripts/sql/outreach_db_init.sql` (멱등). DB·역할(`outreach_app`)·
|
||||
| `outreach_logs` | 보낸 기록(메일·DM, 성공·오류) — 줄을 지워도 남음, 본문·토큰은 안 남김 |
|
||||
| `outreach_dm_bodies` | DM 수동 보내기 탭의 저장한 본문({이름} 이 든 글, 최대 1000자, 제목 = 첫 줄) — 마이그레이션 `outreach_db_002_dm_bodies.sql`(2026-10-30) |
|
||||
|
||||
## live_db 스키마 / 초기화 (라이브 커머스, 2026-11-04)
|
||||
|
||||
DDL: `scripts/sql/live_db_init.sql` (멱등). DB·역할(`live_app`)·테이블·인덱스·트리거. **JSON 폴백 없음** — `LIVE_DB_URL` 미설정 시 "설정 필요" 안내.
|
||||
생성·연결 명령은 `docs/DEPLOYMENT.md` "라이브 커머스 DB 생성". 호스트 계좌·주소 등 개인정보 포함(평문 저장, 화면은 ERP 관리자만).
|
||||
|
||||
| 테이블 | 용도 |
|
||||
| --- | --- |
|
||||
| `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_broadcast_images` | 방송 결과 이미지(메타데이터 제거 후 BYTEA, 방송을 지우면 CASCADE) — 방송당 최대 10장(앱에서 확인) |
|
||||
|
||||
## malaysia_stock_db 스키마 / 초기화
|
||||
|
||||
DDL: `scripts/sql/malaysia_stock_db_init.sql` (멱등). DB·역할(`malaysia_app`)·테이블·인덱스·트리거·창고/아이템 seed 를 한 번에 생성. **JSON 폴백 없음** — `MALAYSIA_STOCK_DB_URL` 미설정 시 모듈이 "설정 필요" 안내만 표시. 상품명은 `itemcode_db` 읽기 전용 재사용.
|
||||
|
||||
@@ -375,6 +375,25 @@ docker exec dbx-main python -c "import os,psycopg; psycopg.connect(os.environ['O
|
||||
백업: 매일 `docker exec postgres-db pg_dump -U postgres outreach_db > /var/backups/postgres/outreach_db_$(date +%F).sql`.
|
||||
백업: 매일 `docker exec postgres-db pg_dump -U postgres inout_db > /var/backups/postgres/inout_db_$(date +%F).sql`.
|
||||
|
||||
## 라이브 커머스 DB 생성 (live_db, 2026-11-04)
|
||||
|
||||
입출고 DB 와 같은 방법(새 DB — 기존 DB·데이터는 건드리지 않음, 초기화 SQL 멱등, 비밀번호는 URL 인코딩). 호스트 계좌·주소 등 개인정보가 들어가므로 백업 파일 권한에 주의.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main && git pull
|
||||
docker exec postgres-db psql -U postgres -lqt | cut -d| -f1 | grep -w live_db || echo "live_db 없음 — 새로 만든다"
|
||||
read -s -p "live_app password: " APP_PWD; echo
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -v app_password="$APP_PWD" < scripts/sql/live_db_init.sql
|
||||
ENC=$(APP_PWD="$APP_PWD" python3 -c "import os,urllib.parse;print(urllib.parse.quote(os.environ['APP_PWD'],safe=''))")
|
||||
grep -q "^LIVE_DB_URL=" .env && sed -i "s|^LIVE_DB_URL=.*|LIVE_DB_URL=postgresql://live_app:${ENC}@postgres-db:5432/live_db|" .env \
|
||||
|| printf '\nLIVE_DB_URL=postgresql://live_app:%s@postgres-db:5432/live_db\n' "$ENC" >> .env
|
||||
docker compose up --build -d --no-deps web
|
||||
docker exec dbx-main python -c "import os,psycopg; psycopg.connect(os.environ['LIVE_DB_URL']).execute('select 1 from live_hosts limit 1'); print('DB OK')"
|
||||
```
|
||||
|
||||
그다음 ERP 관리자 화면에서 쓸 사람에게 **라이브 커머스** 권한 → ERP 관리자가 라이브 커머스 → 호스트 설정에서 호스트 등록.
|
||||
백업: 매일 `docker exec postgres-db pg_dump -U postgres live_db > /var/backups/postgres/live_db_$(date +%F).sql`.
|
||||
|
||||
## 연간 목표 주차별 매출 목표 두 칸 마이그레이션 (project_db 030)
|
||||
|
||||
030은 `goal_week_targets` 에 `value_dist`(유통·인플)·`value_mall`(카페24·네이버) 열만 추가한다(다시 실행 가능, 기존 값 변경 없음, 새 환경변수 없음).
|
||||
@@ -597,6 +616,7 @@ docker compose down # 컨테이너 제거 (볼륨 유지)
|
||||
| `APP_ENCRYPTION_KEY_VERSION` | 현재 마스터 키 버전(기본 1). 교체 시 올리고 예전 키는 `APP_ENCRYPTION_KEY_V{n}` 로 남긴 뒤 설정 화면에서 재암호화(`docs/PERFORMANCE_MODULE.md`) |
|
||||
| `PERFORMANCE_SYNC_DAYS` | [매출 업데이트] 수집 기간(오늘 포함 최근 N일, 기본 7, 최대 90) |
|
||||
| `OUTREACH_DB_URL` | 안내문 발송 DB DSN (예: `postgresql://outreach_app:<pwd>@postgres-db:5432/outreach_db`, 비밀번호는 URL 인코딩). 미설정 시 모듈 비활성(설정 필요 안내). 권한키 `outreach`. 메일은 `INOUT_DB_URL` 의 Gmail 연결 재사용 |
|
||||
| `LIVE_DB_URL` | 라이브 커머스 DB DSN (예: `postgresql://live_app:<pwd>@postgres-db:5432/live_db`, 비밀번호는 URL 인코딩). 미설정 시 모듈 비활성(설정 필요 안내). 권한키 `live` |
|
||||
| `INOUT_DB_URL` | 입출고 관리 DB DSN (예: `postgresql://inout_app:<pwd>@postgres-db:5432/inout_db`). 미설정 시 입출고 모듈 비활성(설정 필요 안내). 권한키 `inout`. 제품은 `ITEMCODE_DB_URL`(단품) 재사용 |
|
||||
|
||||
---
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
| 입출고 관리 | 본사 → 공장 제품 제작 발주, 물류 입고(여러 번 나눠), 발주 대비 미입고·초과 입고 관리 (`app/modules/inout/`, `inout_db`) — 발주 담당·입고 담당·공장은 모듈 옵션에서 지정, 제품은 `itemcode_db` 단품 읽기 전용. `docs/INOUT_MODULE.md` |
|
||||
| 긴급 공지 | 수퍼관리자가 정한 시각에 전체/고른 사람의 ERP 화면 정가운데에 띄우는 공지(`app/modules/notice/`, project_db 024) — [확인] 전까지 다시 뜸, 확인 현황. `docs/NOTICE_MODULE.md` |
|
||||
| 안내문 발송 | 리스트(이메일·인스타 주소 + 이름)에 `{이름}`을 넣은 안내문 — 메일 일괄 발송(보내는 사람 본인 Gmail)·인스타 DM 반자동(문구 복사 + DM 창) (`app/modules/outreach/`, `outreach_db`) |
|
||||
| 라이브 커머스 | 말레이시아 라이브 방송의 호스트 정보(설정)와 스케줄표(호스트·날짜·시간·판매금액·장소·결과 이미지) (`app/modules/live/`, `live_db`) |
|
||||
| 실적 | 쇼핑몰 통합 매출 (`app/modules/performance/`) — 쇼핑몰별 어댑터로 수집 → `performance_db` 저장 → 일자×쇼핑몰 표·KPI·월/연 누적·그래프. 수수료율 이력, API 인증정보는 설정 화면 입력 + AES-256-GCM 암호화 저장. 1단계는 모의 데이터·구조까지(실제 API 는 쇼핑몰별로 순차 연동). `docs/PERFORMANCE_MODULE.md` |
|
||||
|
||||
### 권한 키 (`MODULE_KEYS`)
|
||||
@@ -39,6 +40,7 @@
|
||||
| `expense_approver` | 결재 | 개인경비 승인/반려/정산 |
|
||||
| `asset` | 접근 | 자산관리 조회·등록·수정·배정·반납·보고서 |
|
||||
| `outreach` | 접근 | 안내문 발송 — 리스트·메일 발송·DM·설정 |
|
||||
| `live` | 접근 | 라이브 커머스 스케줄표 보기·고치기(호스트 정보 설정은 ERP 관리자만) |
|
||||
| `inout` | 접근 | 입출고 관리 조회. 발주·입고 입력은 모듈 옵션의 발주 담당·입고 담당(ERP 관리자는 둘 다 + 옵션) |
|
||||
| `vacation_approver` | 결재 | 휴가 승인/반려 (모듈 미개발) |
|
||||
|
||||
@@ -114,6 +116,7 @@ app/modules/<name>/
|
||||
| `vacation_db` | 휴가 신청/공휴일/연차잔여 (`VACATION_DB_URL` 필수, JSON 폴백 없음) |
|
||||
| `malaysia_stock_db` | 말레이시아 창고 재고/세트BOM/재고조사 (`MALAYSIA_STOCK_DB_URL` 필수, JSON 폴백 없음) |
|
||||
| `outreach_db` | 안내문 발송 — 리스트·보낸 기록·제목/본문 설정·사진 (`OUTREACH_DB_URL` 필수, JSON 폴백 없음) |
|
||||
| `live_db` | 라이브 커머스 — 호스트 정보·방송 스케줄·결과 이미지 (`LIVE_DB_URL` 필수, JSON 폴백 없음) |
|
||||
| `performance_db` | 실적 — 쇼핑몰 설정/수수료 이력/인증정보(암호문)/매출 사건 (`PERFORMANCE_DB_URL` 필수, JSON 폴백 없음) |
|
||||
|
||||
> 신규 DB 생성은 서버 실행 명령을 제공하고 사용자가 직접 진행한다 (사용자 지시: 2026-10-06). 대상·상태·백업 확인 명령을 제공하고 이름은 `_db`로 끝낸다. 기존 DB 삭제·덮어쓰기는 별도 승인 대상이다. 상세는 `DATABASES.md`.
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
-- =====================================================================
|
||||
-- live_db 초기화 스크립트 (PostgreSQL) — 라이브 커머스 모듈(2026-11-04)
|
||||
-- =====================================================================
|
||||
-- 말레이시아 라이브 커머스 방송 — 호스트 정보(설정)와 방송 스케줄(호스트·날짜·시간·판매금액·장소·결과 이미지).
|
||||
-- 멱등(idempotent): 여러 번 실행해도 안전. 기존 데이터를 삭제하지 않는다. DROP/TRUNCATE 없음(트리거 다시 만들기만).
|
||||
--
|
||||
-- 실행 방법 (운영 PostgreSQL 컨테이너명: postgres-db, 백업 먼저):
|
||||
--
|
||||
-- 1) DB / 역할 / 테이블 생성 (superuser 로 1회)
|
||||
-- read -s -p "live_app password: " APP_PWD; echo
|
||||
-- docker exec -i postgres-db psql -U postgres -v app_password="$APP_PWD" < scripts/sql/live_db_init.sql
|
||||
--
|
||||
-- 2) main-app .env 에 연결 정보 등록
|
||||
-- LIVE_DB_URL=postgresql://live_app:<APP_PWD>@postgres-db:5432/live_db
|
||||
--
|
||||
-- 3) main-app 재기동
|
||||
-- cd /opt/www/main && docker compose up -d --build --no-deps web
|
||||
-- =====================================================================
|
||||
|
||||
\set ON_ERROR_STOP on
|
||||
|
||||
SELECT 'CREATE DATABASE live_db ENCODING ''UTF8'' TEMPLATE template0'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM pg_database WHERE datname = 'live_db')
|
||||
\gexec
|
||||
|
||||
SELECT 'CREATE ROLE live_app LOGIN PASSWORD ' || quote_literal(:'app_password')
|
||||
WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'live_app')
|
||||
\gexec
|
||||
|
||||
SELECT 'ALTER ROLE live_app WITH LOGIN PASSWORD ' || quote_literal(:'app_password')
|
||||
\gexec
|
||||
|
||||
GRANT CONNECT ON DATABASE live_db TO live_app;
|
||||
|
||||
\connect live_db
|
||||
|
||||
CREATE OR REPLACE FUNCTION live_set_updated_at() RETURNS trigger AS $$
|
||||
BEGIN
|
||||
NEW.updated_at := now();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 1) 호스트 — 설정에서 미리 등록(개인정보·계좌 포함, 설정 화면은 ERP 관리자만)
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS live_hosts (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
full_name TEXT NOT NULL CHECK (char_length(full_name) BETWEEN 1 AND 200), -- Full Name (as per IC)
|
||||
phone TEXT NOT NULL DEFAULT '',
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
address TEXT NOT NULL DEFAULT '',
|
||||
bank_name TEXT NOT NULL DEFAULT '',
|
||||
bank_account TEXT NOT NULL DEFAULT '',
|
||||
tiktok_handle TEXT NOT NULL DEFAULT '', -- @ 없이
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE, -- FALSE = 새 방송에서 못 고름
|
||||
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()
|
||||
);
|
||||
COMMENT ON TABLE live_hosts IS '라이브 커머스 — 호스트 정보(개인정보·계좌 포함)';
|
||||
DROP TRIGGER IF EXISTS trg_live_hosts_updated_at ON live_hosts;
|
||||
CREATE TRIGGER trg_live_hosts_updated_at BEFORE UPDATE ON live_hosts
|
||||
FOR EACH ROW EXECUTE FUNCTION live_set_updated_at();
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 2) 방송 스케줄 — 날짜·시간은 입력한 말레이시아 시간 그대로(시간대 변환 없음), 판매금액 단위 RM
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS live_broadcasts (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
host_id BIGINT NOT NULL REFERENCES live_hosts(id) ON DELETE RESTRICT, -- 방송 기록이 있는 호스트는 못 지움
|
||||
broadcast_date DATE NOT NULL,
|
||||
start_time TIME NOT NULL,
|
||||
end_time TIME,
|
||||
venue TEXT NOT NULL DEFAULT '',
|
||||
sales_amount NUMERIC(14,2) CHECK (sales_amount IS NULL OR sales_amount >= 0), -- NULL = 아직 입력 안 함
|
||||
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()
|
||||
);
|
||||
COMMENT ON TABLE live_broadcasts IS '라이브 커머스 — 방송 스케줄';
|
||||
CREATE INDEX IF NOT EXISTS idx_live_broadcasts_date ON live_broadcasts (broadcast_date, start_time);
|
||||
CREATE INDEX IF NOT EXISTS idx_live_broadcasts_host ON live_broadcasts (host_id);
|
||||
DROP TRIGGER IF EXISTS trg_live_broadcasts_updated_at ON live_broadcasts;
|
||||
CREATE TRIGGER trg_live_broadcasts_updated_at BEFORE UPDATE ON live_broadcasts
|
||||
FOR EACH ROW EXECUTE FUNCTION live_set_updated_at();
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 3) 방송 결과 이미지 — 서버가 확인·메타데이터 제거 후 저장(방송을 지우면 함께 지워짐)
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS live_broadcast_images (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
broadcast_id BIGINT NOT NULL REFERENCES live_broadcasts(id) ON DELETE CASCADE,
|
||||
filename TEXT NOT NULL DEFAULT '',
|
||||
content_type TEXT NOT NULL,
|
||||
data BYTEA NOT NULL,
|
||||
width INTEGER NOT NULL DEFAULT 0,
|
||||
height INTEGER NOT NULL DEFAULT 0,
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE live_broadcast_images IS '라이브 커머스 — 방송 결과 이미지';
|
||||
CREATE INDEX IF NOT EXISTS idx_live_images_broadcast ON live_broadcast_images (broadcast_id, id);
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 4) 권한 (live_app: CRUD only)
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
GRANT USAGE ON SCHEMA public TO live_app;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON live_hosts, live_broadcasts, live_broadcast_images TO live_app;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO live_app;
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO live_app;
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT USAGE, SELECT ON SEQUENCES TO live_app;
|
||||
|
||||
SELECT 'live_db ready' AS status;
|
||||
@@ -0,0 +1,254 @@
|
||||
"""라이브 커머스(live, 2026-11-04).
|
||||
|
||||
1) store — 호스트·방송 입력 검사, 판매금액, 달 범위, 표시 형식, 작은 그림.
|
||||
2) 실제 앱(격리된 하위 프로세스) — 메뉴·권한 칩·"설정 필요" 안내(DB 없이 늘 실행).
|
||||
3) 전체 흐름(LIVE_TEST_DB_URL 이 localhost 일 때만) — 호스트 등록·권한·스케줄·이미지·지우기.
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import date, time
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from app.modules.live import store # noqa: E402
|
||||
|
||||
DSN = os.getenv("LIVE_TEST_DB_URL", "")
|
||||
DB_ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
|
||||
|
||||
PRELUDE = '''
|
||||
from unittest.mock import patch
|
||||
from fastapi.testclient import TestClient
|
||||
import app.main as main
|
||||
|
||||
def U(email, role="user", live=True):
|
||||
return {"email": email, "name": email.split("@")[0], "role": role, "is_super_admin": False, "modules": {"live": live}}
|
||||
|
||||
who = {"u": None}
|
||||
|
||||
def run(body):
|
||||
with patch.object(main, "get_current_user_record", side_effect=lambda r: who["u"]), \\
|
||||
patch.object(main, "get_session_user", side_effect=lambda r: who["u"]), \\
|
||||
patch.object(main.user_store, "get", side_effect=lambda e: who["u"]), \\
|
||||
patch.object(main.user_store, "list_all", side_effect=lambda: [who["u"]]):
|
||||
body(TestClient(main.app))
|
||||
'''
|
||||
|
||||
|
||||
def _run(code: str, extra_env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
|
||||
env = dict(os.environ)
|
||||
for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE", "MALAYSIA_STOCK",
|
||||
"ITEMCODE", "EXPENSE", "INOUT", "OUTREACH", "LIVE"):
|
||||
env[key + "_DB_URL"] = ""
|
||||
env.update(SESSION_SECRET_KEY="local-live-test-only", SESSION_COOKIE_SECURE="false", PERFORMANCE_AUTO_SYNC="false")
|
||||
env.update(extra_env or {})
|
||||
with tempfile.TemporaryDirectory(prefix="live-web-") as directory:
|
||||
env["DATA_DIR"] = directory
|
||||
return subprocess.run([sys.executable, "-c", PRELUDE + code], cwd=ROOT, env=env, capture_output=True,
|
||||
text=True, encoding="utf-8", timeout=90)
|
||||
|
||||
|
||||
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",
|
||||
"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}):
|
||||
with self.assertRaises(ValueError, msg=bad):
|
||||
store.clean_host(bad)
|
||||
|
||||
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)
|
||||
|
||||
def test_parse_money(self):
|
||||
self.assertIsNone(store.parse_money(""))
|
||||
self.assertEqual(store.parse_money("RM 1,234.5"), Decimal("1234.50"))
|
||||
self.assertEqual(store.parse_money("0"), Decimal("0.00"))
|
||||
for bad in ("-1", "abc", "NaN", "Infinity", "1e20"):
|
||||
with self.assertRaises(ValueError, msg=bad):
|
||||
store.parse_money(bad)
|
||||
|
||||
def test_clean_broadcast(self):
|
||||
got = store.clean_broadcast({"host_id": "3", "broadcast_date": "2026-11-04", "start_time": "20:00", "end_time": "",
|
||||
"venue": " Studio ", "sales_amount": "100"})
|
||||
self.assertEqual(got, {"host_id": 3, "broadcast_date": date(2026, 11, 4), "start_time": time(20, 0), "end_time": None,
|
||||
"venue": "Studio", "sales_amount": Decimal("100.00")})
|
||||
good = {"host_id": "3", "broadcast_date": "2026-11-04", "start_time": "20:00"}
|
||||
for over in ({"host_id": ""}, {"host_id": "x"}, {"broadcast_date": ""}, {"broadcast_date": "2026-13-01"}, {"start_time": ""},
|
||||
{"start_time": "25:00"}, {"end_time": "nope"}, {"venue": "x" * 201}, {"sales_amount": "-5"}):
|
||||
with self.assertRaises(ValueError, msg=over):
|
||||
store.clean_broadcast({**good, **over})
|
||||
|
||||
def test_month_range(self):
|
||||
today = date(2026, 11, 4)
|
||||
self.assertEqual(store.month_range("", today)["label"], "2026년 11월")
|
||||
self.assertEqual(store.month_range("bad", today)["start"], date(2026, 11, 1))
|
||||
self.assertEqual(store.month_range("2026-13", today)["start"], date(2026, 11, 1))
|
||||
dec = store.month_range("2026-12", today)
|
||||
self.assertEqual((dec["start"], dec["end"], dec["prev"], dec["next"]), (date(2026, 12, 1), date(2027, 1, 1), "2026-11", "2027-01"))
|
||||
jan = store.month_range("2027-01", today)
|
||||
self.assertEqual((jan["end"], jan["prev"], jan["next"]), (date(2027, 2, 1), "2026-12", "2027-02"))
|
||||
|
||||
def test_format(self):
|
||||
self.assertEqual(store.fmt_date(date(2026, 11, 4)), "2026.11.04(수)")
|
||||
self.assertEqual(store.fmt_times(time(20, 0), time(22, 30)), "20:00 ~ 22:30")
|
||||
self.assertEqual(store.fmt_times(time(20, 0), None), "20:00")
|
||||
self.assertEqual(store.fmt_money(Decimal("1234.5")), "1,234.50")
|
||||
self.assertEqual(store.fmt_money(None), "")
|
||||
|
||||
def test_thumbnail(self):
|
||||
for mode, fmt in (("RGB", "JPEG"), ("RGBA", "PNG")):
|
||||
raw = io.BytesIO()
|
||||
Image.new(mode, (800, 400)).save(raw, format=fmt)
|
||||
with Image.open(io.BytesIO(store.thumbnail(raw.getvalue()))) as im:
|
||||
self.assertEqual((im.format, im.size), ("JPEG", (160, 80)))
|
||||
|
||||
|
||||
class WebTests(unittest.TestCase):
|
||||
def test_registered_and_unconfigured(self):
|
||||
res = _run('''
|
||||
from app.store import MODULE_KEYS
|
||||
assert "live" in MODULE_KEYS and main.MODULE_LABELS["live"] == "라이브 커머스"
|
||||
|
||||
def body(c):
|
||||
who["u"] = U("a@test.local", role="admin")
|
||||
assert c.get("/live/health").json() == {"status": "not_configured"}
|
||||
r = c.get("/live/")
|
||||
assert r.status_code == 503 and "LIVE_DB_URL" in r.text and "라이브 커머스" in r.text, r.status_code
|
||||
assert c.post("/live/broadcasts", data={}).status_code == 503
|
||||
who["u"] = U("b@test.local", live=False)
|
||||
assert c.get("/live/").status_code == 403
|
||||
assert c.post("/live/broadcasts", data={}).status_code == 403
|
||||
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)
|
||||
|
||||
@unittest.skipUnless(DB_ENABLED, "LIVE_TEST_DB_URL(localhost) not set")
|
||||
def test_full_flow(self):
|
||||
res = _run('''
|
||||
import io, re, uuid
|
||||
from PIL import Image
|
||||
from app.modules.live.db import LiveDBStore
|
||||
st = LiveDBStore(__import__("os").environ["LIVE_TEST_DB_URL"])
|
||||
main.app.state.live_store = st
|
||||
tag = uuid.uuid4().hex[:8]
|
||||
admin, staff, outsider = U("admin-%s@t.local" % tag, role="admin"), U("staff-%s@t.local" % tag), U("out-%s@t.local" % tag, live=False)
|
||||
ACCOUNT = "9988%s" % int(tag, 16)
|
||||
NAME = "Siti <b>" + tag
|
||||
|
||||
def jpeg():
|
||||
raw = io.BytesIO()
|
||||
exif = Image.Exif(); exif[0x010F] = "SECRET-CAMERA"
|
||||
Image.new("RGB", (3000, 1500), "red").save(raw, format="JPEG", exif=exif)
|
||||
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"}
|
||||
# ── 호스트 설정 = ERP 관리자만 ──
|
||||
who["u"] = staff
|
||||
assert c.get("/live/settings").status_code == 403
|
||||
assert c.post("/live/settings/hosts", data=host).status_code == 403
|
||||
assert c.post("/live/settings/hosts/1/delete").status_code == 403
|
||||
assert 'href="/live/settings"' not in c.get("/live/").text
|
||||
who["u"] = admin
|
||||
bad = c.post("/live/settings/hosts", data={**host, "email": "nope"})
|
||||
assert bad.status_code == 400 and "Email" in bad.json()["message"]
|
||||
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)
|
||||
page = c.get("/live/settings").text
|
||||
for field in ("Full Name (as per IC)", "Phone Number", "Email", "Address", "Bank Name", "Bank Account Number", "Tiktok Handle"):
|
||||
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
|
||||
|
||||
# ── 스케줄: 일반 권한자도 추가·고치기, 화면에 계좌·주소 없음 ──
|
||||
who["u"] = staff
|
||||
page = c.get("/live/?month=2031-03").text
|
||||
assert 'value="%d"' % hid in page and "@siti." + tag 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"}
|
||||
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 # 이미지가 틀리면 방송도 저장 안 됨
|
||||
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 "KL Studio" 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]
|
||||
assert img["filename"] == "evil.jpg" and len(row["images"]) == 1 # 파일 이름의 경로 제거
|
||||
|
||||
# ── 이미지: 크기 줄임·EXIF 제거·권한 ──
|
||||
r = c.get("/live/images/%d" % img["id"])
|
||||
assert r.status_code == 200 and r.headers["content-type"] == "image/jpeg" and "private" in r.headers["cache-control"]
|
||||
assert b"SECRET-CAMERA" not in r.content
|
||||
assert Image.open(io.BytesIO(r.content)).size == (2400, 1200)
|
||||
assert Image.open(io.BytesIO(c.get("/live/images/%d?thumb=1" % img["id"]).content)).size == (160, 80)
|
||||
assert c.get("/live/images/99999999").status_code == 404
|
||||
who["u"] = outsider
|
||||
assert c.get("/live/images/%d" % img["id"]).status_code == 403
|
||||
assert c.post("/live/images/%d/delete" % img["id"]).status_code == 403
|
||||
who["u"] = staff
|
||||
|
||||
# ── 고치기: 값 바뀜, 이미지 유지 + 더하기, 판매금액 지우기, 10장 제한 ──
|
||||
r = c.post("/live/broadcasts", data={**show, "id": bid, "venue": "PJ Studio", "sales_amount": "", "end_time": ""})
|
||||
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 ~" not in page
|
||||
many = [("images", ("%d.jpg" % i, jpeg(), "image/jpeg")) for i in range(10)]
|
||||
r = c.post("/live/broadcasts", data={**show, "id": bid}, files=many)
|
||||
assert r.status_code == 400 and "10장" in r.json()["message"], r.text # 이미 1장 + 10장
|
||||
assert c.post("/live/broadcasts", data={**show, "id": 99999999}).status_code == 400
|
||||
assert c.post("/live/broadcasts", data={**show, "id": "x"}).status_code == 400
|
||||
|
||||
# ── 호스트: 방송이 있으면 못 지움, 사용 안 함이면 새 방송 불가·기존 방송 고치기는 가능 ──
|
||||
who["u"] = admin
|
||||
r = c.post("/live/settings/hosts/%d/delete" % hid)
|
||||
assert r.status_code == 400 and "사용 안 함" in r.json()["message"]
|
||||
assert c.post("/live/settings/hosts", data={**host, "id": hid, "is_active": ""}).json()["ok"]
|
||||
who["u"] = staff
|
||||
assert 'data-inactive="1"' in c.get("/live/?month=2031-03").text
|
||||
r = c.post("/live/broadcasts", data=show)
|
||||
assert r.status_code == 400 and "사용 안 함" in r.json()["message"]
|
||||
assert c.post("/live/broadcasts", data={**show, "id": bid}).json()["ok"]
|
||||
|
||||
# ── 지우기: 이미지 하나, 방송(이미지도), 그 뒤 호스트 ──
|
||||
assert c.post("/live/images/%d/delete" % img["id"]).json()["ok"]
|
||||
assert c.get("/live/images/%d" % img["id"]).status_code == 404
|
||||
assert c.post("/live/broadcasts", data={**show, "id": bid}, files=[("images", ("a.png", jpeg(), "image/jpeg"))]).json()["ok"]
|
||||
assert c.post("/live/broadcasts/%d/delete" % bid).json()["ok"]
|
||||
assert c.post("/live/broadcasts/%d/delete" % bid).status_code == 400
|
||||
who["u"] = admin
|
||||
assert c.post("/live/settings/hosts/%d/delete" % hid).json()["ok"]
|
||||
assert c.post("/live/settings/hosts/%d/delete" % hid).status_code == 400
|
||||
print("OK")
|
||||
run(body)
|
||||
''', {"LIVE_TEST_DB_URL": DSN})
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user