f54f19fa45
말레이시아 라이브 방송의 호스트 정보와 방송 스케줄을 관리하는 새 모듈. 호스트 설정(이름·연락처·주소·계좌·틱톡)은 ERP 관리자만 다루고, 스케줄표에서 등록된 호스트를 골라 날짜·시간·장소·판매금액(RM)·결과 이미지를 저장한다. 권한키 live, DB live_db(LIVE_DB_URL), 미설정이면 설정 필요 안내만 표시한다. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
130 lines
7.9 KiB
Python
130 lines
7.9 KiB
Python
"""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("이미지를 찾을 수 없습니다.")
|