From 42fdf9856056ffcfb778cfe32051726058c9d70d Mon Sep 17 00:00:00 2001 From: king Date: Thu, 5 Nov 2026 18:03:50 +0900 Subject: [PATCH] =?UTF-8?q?feat(=EB=9D=BC=EC=9D=B4=EB=B8=8C):=20=ED=8B=B1?= =?UTF-8?q?=ED=86=A1=20=EA=B3=84=EC=A0=95=EC=9D=84=20=ED=98=B8=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=EC=97=90=EC=84=9C=20=EB=B0=A9=EC=86=A1=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EC=98=AE=EA=B9=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 호스트가 메인 계정 외 다른 계정에서도 방송하므로 호스트 설정에서 틱톡 핸들을 빼고 방송 추가·고치기 창에서 방송마다 입력한다. 쓴 적 있는 계정을 입력 제안으로 보여 준다. 마이그레이션 003: live_broadcasts.tiktok_handle 추가, 기존 방송에 호스트의 지금 계정 복사. Co-Authored-By: Claude Opus 5.5 --- app/modules/live/CLAUDE.md | 7 +-- app/modules/live/db.py | 27 +++++++----- app/modules/live/router.py | 14 +++--- app/modules/live/store.py | 17 +++++--- app/modules/live/templates/live/_dialog.html | 6 ++- app/modules/live/templates/live/settings.html | 10 ++--- docs/DATABASES.md | 4 +- scripts/sql/live_db_003_broadcast_account.sql | 26 +++++++++++ scripts/sql/live_db_init.sql | 3 +- tests/test_live.py | 43 +++++++++++++------ 10 files changed, 105 insertions(+), 52 deletions(-) create mode 100644 scripts/sql/live_db_003_broadcast_account.sql diff --git a/app/modules/live/CLAUDE.md b/app/modules/live/CLAUDE.md index fc57f3f..cc1bc76 100644 --- a/app/modules/live/CLAUDE.md +++ b/app/modules/live/CLAUDE.md @@ -5,9 +5,10 @@ > 다른 모듈과 연결: 이미지 검사 = 자산 모듈 `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`(이름·틱톡·사용 여부)만 넘긴다. - **`live_host` 칩**(+ `live` 칩 필요) = 새 호스트 **등록만**: 설정 화면에 이름·틱톡·상태만 보이고, 입력한 계좌 등은 저장 후 못 봄. 고치기·지우기 불가, 사용 여부 못 고름(항상 사용). +- **호스트 설정** `/live/settings` — 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` 칩**(+ `live` 칩 필요) = 새 호스트 **등록만**: 설정 화면에 이름·상태만 보이고, 입력한 계좌 등은 저장 후 못 봄. 고치기·지우기 불가, 사용 여부 못 고름(항상 사용). 사용 안 함 = 새 방송에서 못 고름(그 호스트로 이미 등록된 방송을 고칠 때만 보임). 방송 기록이 있는 호스트는 못 지움(FK RESTRICT). - **스케줄표** `/live/?month=YYYY-MM`(`live` 권한자 모두) — 호스트·날짜·시작/끝 시간·방송 장소·판매금액·커미션·호스트 비용·결과 이미지. 호스트·날짜·시작·끝 시간 필수(판매금액은 방송 후 입력). 시간은 입력한 말레이시아 시간 그대로(시간대 변환 없음, DATE·TIME). 판매금액 단위 RM(`NUMERIC(14,2)`, `store.parse_money`). 끝 시간이 시작보다 이르면 자정을 넘긴 방송. diff --git a/app/modules/live/db.py b/app/modules/live/db.py index 7ff80f5..9450197 100644 --- a/app/modules/live/db.py +++ b/app/modules/live/db.py @@ -18,7 +18,7 @@ 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 = ("full_name", "phone", "email", "address", "bank_name", "bank_account") class LiveDBStore: @@ -39,21 +39,26 @@ 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, full_name, is_active FROM live_hosts ORDER BY full_name, id").fetchall() + + 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 (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) 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", + "is_active=%s, updated_by=%s WHERE id=%s RETURNING id", (*cols, is_active, by, host_id)).fetchone() if not row: raise LiveError("호스트를 찾을 수 없습니다.") @@ -73,7 +78,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.*, h.full_name AS host_name 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( @@ -98,14 +103,14 @@ class LiveDBStore: 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) + values["tiktok_handle"], 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"]) + "INSERT INTO live_broadcasts (host_id, broadcast_date, start_time, end_time, venue, tiktok_handle, sales_amount, updated_by, created_by) " + "VALUES (%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)) + "tiktok_handle=%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) diff --git a/app/modules/live/router.py b/app/modules/live/router.py index 35cd035..60aa047 100644 --- a/app/modules/live/router.py +++ b/app/modules/live/router.py @@ -140,7 +140,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) @@ -153,7 +153,7 @@ def calendar(request: Request, month: str = "") -> Any: 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) 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}) @router.post("/broadcasts/{broadcast_id}/move") @@ -203,14 +203,14 @@ 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(""), - images: list[UploadFile] = File(default=[])) -> JSONResponse: + start_time: str = Form(""), end_time: str = Form(""), venue: str = Form(""), tiktok_handle: 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}) + "end_time": end_time, "venue": venue, "tiktok_handle": tiktok_handle, "sales_amount": sales_amount}) st.save_broadcast(broadcast_id, values, _read_images(images), by=user.get("email", "")) except ValueError as exc: return _fail(request, exc) @@ -269,7 +269,7 @@ def settings(request: Request) -> Any: @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(""), + address: str = Form(""), bank_name: str = Form(""), bank_account: str = Form(""), is_active: str = Form("")) -> JSONResponse: from app.store import is_admin # noqa: WPS433 @@ -280,7 +280,7 @@ def host_save(request: Request, id: str = Form(""), full_name: str = Form(""), p 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}) + "bank_account": bank_account}) # 칩 권한자 화면엔 사용 여부 칸이 없다 — 항상 사용(사용 안 함으로 만들면 본인이 되돌릴 수 없음) st.save_host(_opt_id(id), values, is_active=bool(is_active) or not is_admin(user), by=user.get("email", "")) except ValueError as exc: diff --git a/app/modules/live/store.py b/app/modules/live/store.py index 25340fa..7e8365f 100644 --- a/app/modules/live/store.py +++ b/app/modules/live/store.py @@ -25,9 +25,10 @@ _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} +HOST_LIMITS = {"full_name": 200, "phone": 40, "email": 254, "address": 500, "bank_name": 100, "bank_account": 40} +HANDLE_LIMIT = 64 _LABELS = {"full_name": "이름 (IC 기준)", "phone": "전화번호", "email": "이메일", "address": "주소", "bank_name": "은행명", - "bank_account": "계좌번호", "tiktok_handle": "틱톡 핸들"} + "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]+$") @@ -46,7 +47,6 @@ def clean_handle(raw: Any) -> str: def clean_host(values: dict[str, Any]) -> dict[str, str]: """호스트 입력 검사 — 이름만 필수, 나머지는 있으면 형식 확인. 틀리면 ValueError.""" out = {k: str(values.get(k) or "").strip() for k in HOST_LIMITS} - out["tiktok_handle"] = clean_handle(values.get("tiktok_handle")) if not out["full_name"]: raise LiveError("이름 (IC 기준)을 입력하세요.") for key, limit in HOST_LIMITS.items(): @@ -58,8 +58,6 @@ 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 @@ -107,8 +105,13 @@ def clean_broadcast(values: dict[str, Any]) -> dict[str, Any]: end = _parse_time(values.get("end_time"), label="끝 시간", required=True) if start == end: raise LiveError("끝 시간이 시작 시간과 같습니다.") + handle = clean_handle(values.get("tiktok_handle")) + if len(handle) > HANDLE_LIMIT: + raise LiveError("{label} 이(가) 너무 깁니다({limit}자까지).", label="틱톡 핸들", limit=HANDLE_LIMIT) + if handle and not _HANDLE_RE.match(handle): + raise LiveError("틱톡 핸들은 영문·숫자·밑줄·점만 입력하세요.") return {"host_id": int(host), "broadcast_date": day, "start_time": start, "end_time": end, - "venue": venue, "sales_amount": parse_money(values.get("sales_amount"))} + "venue": venue, "tiktok_handle": handle, "sales_amount": parse_money(values.get("sales_amount"))} def parse_move(day: Any, start: Any) -> tuple[date, time]: @@ -158,7 +161,7 @@ def broadcast_view(b: dict[str, Any], lang: str = "ko") -> dict[str, Any]: "card_fee": fmt_short(pay["fee"]), "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 "", + "venue": b["venue"], "tiktok_handle": b["tiktok_handle"], "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"]]}, } diff --git a/app/modules/live/templates/live/_dialog.html b/app/modules/live/templates/live/_dialog.html index 01ea2da..3c0ed48 100644 --- a/app/modules/live/templates/live/_dialog.html +++ b/app/modules/live/templates/live/_dialog.html @@ -1,4 +1,4 @@ -{#- 방송 추가·고치기 창 — 스케줄표·달력 공통(live.js). 호스트 고르기엔 이름·틱톡만(계좌 등은 설정 화면). -#} +{#- 방송 추가·고치기 창 — 스케줄표·달력 공통(live.js). 호스트 고르기엔 이름만(계좌 등은 설정 화면). 틱톡 계정은 방송마다 — 쓴 적 있는 계정을 제안(새 계정도 입력 가능). -#}

@@ -6,9 +6,11 @@ + + {% for a in accounts %}{% endfor %}
diff --git a/app/modules/live/templates/live/settings.html b/app/modules/live/templates/live/settings.html index 35e0c0f..f8f3581 100644 --- a/app/modules/live/templates/live/settings.html +++ b/app/modules/live/templates/live/settings.html @@ -1,5 +1,5 @@ {% extends "erp_base.html" %} -{#- 라이브 커머스 설정(2026-11-04) — 호스트 정보. 계좌 등 개인정보·고치기·지우기는 ERP 관리자만(router.settings), `live_host` 칩은 이름·틱톡·상태 + 새 등록만. 추가·고치기는 같은 창(live.js). 문구 = t()(i18n.py). -#} +{#- 라이브 커머스 설정(2026-11-04) — 호스트 정보. 계좌 등 개인정보·고치기·지우기는 ERP 관리자만(router.settings), `live_host` 칩은 이름·상태 + 새 등록만. 추가·고치기는 같은 창(live.js). 문구 = t()(i18n.py). -#} {% block head_extra %}{% endblock %} {% block content %} @@ -15,7 +15,7 @@
- {% if is_admin %}{% endif %}{% if is_admin %}{% endif %} + {% if is_admin %}{% endif %}{% if is_admin %}{% endif %} {% for h in hosts %} @@ -27,17 +27,16 @@ {% endif %} - {% if is_admin %} {% endif %} {% else %} - + {% endfor %}
{{ t('이름 (IC 기준)') }}{{ t('전화번호') }}{{ t('이메일') }}{{ t('주소') }}{{ t('은행명') }}{{ t('계좌번호') }}{{ t('틱톡 핸들') }}{{ t('상태') }}
{{ t('이름 (IC 기준)') }}{{ t('전화번호') }}{{ t('이메일') }}{{ t('주소') }}{{ t('은행명') }}{{ t('계좌번호') }}{{ t('상태') }}
{{ h.bank_name }} {{ h.bank_account }}{% if h.tiktok_handle %}@{{ h.tiktok_handle }}{% endif %} {{ t('사용') if h.is_active else t('사용 안 함') }} - +
{{ t('등록한 호스트가 없습니다.') }}
{{ t('등록한 호스트가 없습니다.') }}
@@ -57,7 +56,6 @@
- {% if is_admin %}{% endif %}
diff --git a/docs/DATABASES.md b/docs/DATABASES.md index 98aa304..00e28f0 100644 --- a/docs/DATABASES.md +++ b/docs/DATABASES.md @@ -312,8 +312,8 @@ 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` | 호스트 — 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`·`tiktok_handle`(그 방송의 계정, @ 없이, 마이그레이션 `live_db_003_broadcast_account.sql`)·`sales_amount`(RM, NULL = 미입력) | | `live_broadcast_images` | 방송 결과 이미지(메타데이터 제거 후 BYTEA, 방송을 지우면 CASCADE) — 방송당 최대 10장(앱에서 확인) | | `live_daily_ad_spend` | 날짜별 광고비(RM) — 달력 보기 AD SPEND·ROAS. 마이그레이션 `live_db_002_ad_spend.sql`(init 에도 포함) | diff --git a/scripts/sql/live_db_003_broadcast_account.sql b/scripts/sql/live_db_003_broadcast_account.sql new file mode 100644 index 0000000..75cd26b --- /dev/null +++ b/scripts/sql/live_db_003_broadcast_account.sql @@ -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; diff --git a/scripts/sql/live_db_init.sql b/scripts/sql/live_db_init.sql index e8d71d4..73b167a 100644 --- a/scripts/sql/live_db_init.sql +++ b/scripts/sql/live_db_init.sql @@ -52,7 +52,7 @@ 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 '', -- @ 없이 + tiktok_handle TEXT NOT NULL DEFAULT '', -- 쓰지 않음(003 부터 방송별 live_broadcasts.tiktok_handle) is_active BOOLEAN NOT NULL DEFAULT TRUE, -- FALSE = 새 방송에서 못 고름 created_by TEXT NOT NULL DEFAULT '', updated_by TEXT NOT NULL DEFAULT '', @@ -74,6 +74,7 @@ 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 '', updated_by TEXT NOT NULL DEFAULT '', diff --git a/tests/test_live.py b/tests/test_live.py index 567c5d1..e6a26c4 100644 --- a/tests/test_live.py +++ b/tests/test_live.py @@ -62,14 +62,28 @@ 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(got["full_name"], "Siti Aisyah") + self.assertNotIn("tiktok_handle", got) # 계정은 방송마다 — 호스트에는 저장 안 함 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}): + {"full_name": "A", "bank_account": "12a"}, {"full_name": "x" * 201}): 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", "tiktok_handle": "alt.acc", "broadcast_date": date(2026, 11, 4), + "start_time": time(20, 0), "end_time": time(22, 0), "venue": "", "sales_amount": None, "images": []}) + self.assertEqual((view["tiktok_handle"], view["edit"]["tiktok_handle"], view["label"]), ("alt.acc", "alt.acc", "alt.acc")) + 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) @@ -86,7 +100,7 @@ class StoreTests(unittest.TestCase): 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"}) 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")}) + "venue": "Studio", "tiktok_handle": "", "sales_amount": Decimal("100.00")}) 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"}): @@ -226,12 +240,14 @@ assert "live_host" in MODULE_KEYS and "live_host" in main.MODULE_LABELS class Fake: saved = [] def host_choices(self): - return [{"id": 1, "full_name": "Siti", "tiktok_handle": "siti", "is_active": True}] + return [{"id": 1, "full_name": "Siti", "is_active": True}] def list_hosts(self): return [{"id": 1, "full_name": "Siti", "phone": "012", "email": "s@e.my", "address": "KL", "bank_name": "Maybank", - "bank_account": "998877", "tiktok_handle": "siti", "is_active": True}] + "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 @@ -245,10 +261,11 @@ new = {"full_name": "New Host", "bank_account": "111"} def body(c): who["u"] = adder - assert 'href="/live/settings"' in c.get("/live/").text + sched = c.get("/live/").text + assert 'href="/live/settings"' in sched and 'name="tiktok_handle"' in sched and '