"""live_db PostgreSQL 저장소 — 라이브 커머스 호스트·방송 스케줄·결과 이미지(2026-11-04). - 연결: 환경변수 `LIVE_DB_URL` (예: postgresql://live_app:@postgres-db:5432/live_db) - 스키마는 앱이 만들지 않는다 — `scripts/sql/live_db_init.sql` 을 superuser 가 먼저 적용(앱 계정은 CRUD 만). - 연결 풀은 lazy open — 부팅 때 DB 가 잠시 끊겨도 컨테이너가 죽지 않게(다른 모듈과 같은 방식). """ from __future__ import annotations from datetime import date, time from decimal import Decimal from typing import Any from psycopg.errors import ForeignKeyViolation, UndefinedTable 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") 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 LiveError("호스트를 찾을 수 없습니다.") 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 LiveError("방송 기록이 있는 호스트는 지울 수 없습니다 — 사용 안 함으로 바꾸세요.") from None if not row: raise LiveError("호스트를 찾을 수 없습니다.") # ── 방송 스케줄 ───────────────────────────────────────── def list_broadcasts(self, start: date, end: date) -> list[dict[str, Any]]: """start 이상 end 미만, 날짜·시간 순. 줄마다 images = [{id, filename}](내용 제외).""" with self._pool.connection() as conn: rows = conn.execute( "SELECT b.*, 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 LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).") current = found["host_id"] host = conn.execute("SELECT is_active FROM live_hosts WHERE id=%s", (values["host_id"],)).fetchone() if not host: raise LiveError("호스트를 찾을 수 없습니다.") if not host["is_active"] and values["host_id"] != current: raise LiveError("사용 안 함으로 바뀐 호스트입니다 — 다른 호스트를 고르세요.") 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 LiveError("방송 한 건에 이미지는 {max}장까지입니다(지금 {have}장).", max=store.MAX_IMAGES, have=have) for im in images: conn.execute("INSERT INTO live_broadcast_images (broadcast_id, filename, content_type, data, width, height, created_by) " "VALUES (%s,%s,%s,%s,%s,%s,%s)", (broadcast_id, im["filename"], im["content_type"], im["data"], im["width"], im["height"], by)) return broadcast_id def delete_broadcast(self, broadcast_id: int) -> None: with self._pool.connection() as conn: if not conn.execute("DELETE FROM live_broadcasts WHERE id=%s RETURNING id", (broadcast_id,)).fetchone(): raise LiveError("방송을 찾을 수 없습니다.") def move_broadcast(self, broadcast_id: int, day: date, start: time, *, by: str) -> None: """달력에서 빈 칸으로 옮기기 — 방송 길이는 그대로.""" with self._pool.connection() as conn, conn.transaction(): row = conn.execute("SELECT start_time, end_time FROM live_broadcasts WHERE id=%s FOR UPDATE", (broadcast_id,)).fetchone() if not row: raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).") conn.execute("UPDATE live_broadcasts SET broadcast_date=%s, start_time=%s, end_time=%s, updated_by=%s WHERE id=%s", (day, start, store.moved_end(row["start_time"], row["end_time"], start), by, broadcast_id)) def swap_broadcasts(self, first_id: int, second_id: int, *, by: str) -> None: """달력에서 다른 방송 위로 놓기 — 두 방송의 날짜·시간을 맞바꾼다(id 순서로 잠가 교착 방지).""" if first_id == second_id: return with self._pool.connection() as conn, conn.transaction(): rows = conn.execute("SELECT id, broadcast_date, start_time, end_time FROM live_broadcasts WHERE id = ANY(%s) ORDER BY id FOR UPDATE", ([first_id, second_id],)).fetchall() if len(rows) != 2: raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).") for mine, other in ((rows[0], rows[1]), (rows[1], rows[0])): conn.execute("UPDATE live_broadcasts SET broadcast_date=%s, start_time=%s, end_time=%s, updated_by=%s WHERE id=%s", (other["broadcast_date"], other["start_time"], other["end_time"], by, mine["id"])) # ── 날짜별 광고비(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: return conn.execute("SELECT content_type, data FROM live_broadcast_images WHERE id=%s", (image_id,)).fetchone() def delete_image(self, image_id: int) -> None: with self._pool.connection() as conn: if not conn.execute("DELETE FROM live_broadcast_images WHERE id=%s RETURNING id", (image_id,)).fetchone(): raise LiveError("이미지를 찾을 수 없습니다.")