From 61f5b3c3201d339de42ed4137c57640e52deb3d5 Mon Sep 17 00:00:00 2001 From: king Date: Wed, 4 Nov 2026 16:58:07 +0900 Subject: [PATCH] =?UTF-8?q?feat(=EB=9D=BC=EC=9D=B4=EB=B8=8C=EC=BB=A4?= =?UTF-8?q?=EB=A8=B8=EC=8A=A4):=20=EB=8B=AC=EB=A0=A5=20=EB=B3=B4=EA=B8=B0?= =?UTF-8?q?=EC=99=80=20=ED=98=B8=EC=8A=A4=ED=8A=B8=20=EB=B9=84=EC=9A=A9=20?= =?UTF-8?q?=EA=B3=84=EC=82=B0=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 2시간 칸 × 날짜 달력(카드 머리 = Tiktok Handle, SALES·COM·Fee), 끌어 옮기기· 맞바꾸기, Jump to Date, 날짜별 합계·광고비·ROAS 를 넣는다. 호스트 비용 = 시간 × RM 25 + 판매금액 10%, 표 보기에도 표시한다. 끝 시간을 필수로 바꾸고 광고비 표는 마이그레이션 002 로 추가한다. Co-Authored-By: Claude Opus 5.5 --- app/modules/live/CLAUDE.md | 6 +- app/modules/live/db.py | 49 +++++++- app/modules/live/router.py | 60 +++++++--- app/modules/live/store.py | 106 +++++++++++++++++- app/modules/live/templates/live/_bar.html | 18 +++ app/modules/live/templates/live/_dialog.html | 30 +++++ app/modules/live/templates/live/calendar.html | 86 ++++++++++++++ app/modules/live/templates/live/index.html | 56 ++------- app/modules/live/templates/live/settings.html | 4 +- app/static/live.css | 55 +++++++++ app/static/live.js | 93 +++++++++++++-- docs/DATABASES.md | 1 + docs/DEPLOYMENT.md | 5 +- scripts/sql/live_db_002_ad_spend.sql | 21 ++++ scripts/sql/live_db_init.sql | 13 ++- tests/test_live.py | 103 ++++++++++++++++- 16 files changed, 621 insertions(+), 85 deletions(-) create mode 100644 app/modules/live/templates/live/_bar.html create mode 100644 app/modules/live/templates/live/_dialog.html create mode 100644 app/modules/live/templates/live/calendar.html create mode 100644 scripts/sql/live_db_002_ad_spend.sql diff --git a/app/modules/live/CLAUDE.md b/app/modules/live/CLAUDE.md index 230bf19..e375dc8 100644 --- a/app/modules/live/CLAUDE.md +++ b/app/modules/live/CLAUDE.md @@ -8,8 +8,12 @@ - **호스트 설정** `/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` 권한자 모두) — 호스트·날짜·시작/끝 시간·방송 장소·판매금액·결과 이미지. 호스트·날짜·시작 시간만 필수(판매금액은 방송 후 입력). +- **스케줄표** `/live/?month=YYYY-MM`(`live` 권한자 모두) — 호스트·날짜·시작/끝 시간·방송 장소·판매금액·커미션·호스트 비용·결과 이미지. 호스트·날짜·시작·끝 시간 필수(판매금액은 방송 후 입력). 시간은 입력한 말레이시아 시간 그대로(시간대 변환 없음, DATE·TIME). 판매금액 단위 RM(`NUMERIC(14,2)`, `store.parse_money`). 끝 시간이 시작보다 이르면 자정을 넘긴 방송. +- **호스트 비용**(`store.session_pay`, 저장 안 함 — 화면마다 계산) = 시간 × RM 25(`HOURLY_RATE`) + 판매금액 × 10%(`COMMISSION_PERCENT`). 요율이 코드 상수라 바꾸면 지난 방송 금액도 바뀐다. +- **달력 보기** `/live/calendar?month=`(`store.build_calendar`, 사용자가 준 화면 참고, 글자도 영어 그대로) — 줄 = 2시간 칸(06:00~24:00 늘 보임, 그보다 이른 칸은 방송이 있을 때만, 칸은 시작 시간으로 정함), 열 = 날짜, 주말 노랑, Jump to Date, 위 달 합계, 맨 아래 날짜별 TOTAL SALES·AD SPEND·HOST FEE·ROAS. + 카드 머리 = **Tiktok Handle**(없으면 이름, 색 = 호스트 id 순 `HOST_COLORS`), SALES·COM·Fee. 카드 머리를 끌어 빈 칸으로 = 옮기기(`move`, 방송 길이 유지) · 다른 카드 위 = 맞바꾸기(`swap_with`, 날짜·시간 교환). 다시 그린 뒤 가로 위치 유지(sessionStorage). 빈 칸 + = 그 날짜·시간이 채워진 추가 창. + **AD SPEND** = 날짜별 광고비 `live_daily_ad_spend`(마이그레이션 002, `POST /live/ad-spend`, 빈칸 = 지우기), ROAS = 판매금액 ÷ 광고비(광고비 없으면 `-`). 002 미적용이면 0 으로 보이고 저장만 안내. - **결과 이미지** — 방송 저장과 한 트랜잭션, 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). diff --git a/app/modules/live/db.py b/app/modules/live/db.py index 2c1baca..21f48df 100644 --- a/app/modules/live/db.py +++ b/app/modules/live/db.py @@ -7,10 +7,11 @@ from __future__ import annotations -from datetime import date +from datetime import date, time +from decimal import Decimal from typing import Any -from psycopg.errors import ForeignKeyViolation +from psycopg.errors import ForeignKeyViolation, UndefinedTable from psycopg.rows import dict_row from psycopg_pool import ConnectionPool @@ -118,6 +119,50 @@ class LiveDBStore: if not conn.execute("DELETE FROM live_broadcasts WHERE id=%s RETURNING id", (broadcast_id,)).fetchone(): raise ValueError("방송을 찾을 수 없습니다.") + 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 ValueError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).") + 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 ValueError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).") + 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 ValueError("DB 마이그레이션 live_db 002(광고비)가 아직 적용되지 않았습니다.") from None + # ── 결과 이미지 ───────────────────────────────────────── def get_image(self, image_id: int) -> dict[str, Any] | None: with self._pool.connection() as conn: diff --git a/app/modules/live/router.py b/app/modules/live/router.py index 19f4ac7..3130660 100644 --- a/app/modules/live/router.py +++ b/app/modules/live/router.py @@ -1,8 +1,10 @@ """라이브 커머스(live) 라우터 — 말레이시아 라이브 방송의 호스트 정보·방송 스케줄(2026-11-04). - GET /live/ 스케줄표(?month=YYYY-MM) + GET /live/ 스케줄표(?month=YYYY-MM) · GET /live/calendar 달력 보기(같은 달 값) POST /live/broadcasts 방송 추가·고치기(id 칸이 있으면 고치기) + 결과 이미지 올리기 POST /live/broadcasts/{id}/delete 방송 지우기(이미지도 함께) + POST /live/broadcasts/{id}/move 달력에서 끌어 옮기기(broadcast_date·start_time) 또는 맞바꾸기(swap_with) + POST /live/ad-spend 날짜별 광고비(빈칸 = 지우기) GET /live/images/{id} 결과 이미지(?thumb=1 = 작은 그림) · POST /live/images/{id}/delete GET /live/settings 설정 — 호스트 정보(ERP 관리자만, 계좌 등 개인정보) POST /live/settings/hosts 호스트 추가·고치기 · POST /live/settings/hosts/{id}/delete @@ -118,21 +120,53 @@ def index(request: Request, month: str = "") -> Any: 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(), + rows = [store.broadcast_view(b) 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}) +@router.get("/calendar", response_class=HTMLResponse) +def calendar(request: Request, month: str = "") -> Any: + got = _page(request) + if not isinstance(got, tuple): + return got + st, user = got + today = today_kst() + span = store.month_range(month, today) + cal = store.build_calendar(span, st.list_broadcasts(span["start"], span["end"]), st.ad_spends(span["start"], span["end"]), today) + return _render(request, "live/calendar.html", user, {"view": "calendar", "span": span, "cal": cal, "hosts": st.host_choices(), + "max_images": store.MAX_IMAGES}) + + +@router.post("/broadcasts/{broadcast_id}/move") +def broadcast_move(request: Request, broadcast_id: int, broadcast_date: str = Form(""), start_time: str = Form(""), + swap_with: str = Form("")) -> JSONResponse: + user = _user(request) + st = _db(request) + try: + other = _opt_id(swap_with) + if other is not None: + st.swap_broadcasts(broadcast_id, other, by=user.get("email", "")) + else: + day, start = store.parse_move(broadcast_date, start_time) + st.move_broadcast(broadcast_id, day, start, by=user.get("email", "")) + except ValueError as exc: + return _fail(exc) + return _ok("옮겼습니다.") + + +@router.post("/ad-spend") +def ad_spend_save(request: Request, day: str = Form(""), amount: str = Form("")) -> JSONResponse: + user = _user(request) + st = _db(request) + try: + when, _ = store.parse_move(day, "00:00") + st.save_ad_spend(when, store.parse_money(amount), by=user.get("email", "")) + except ValueError as exc: + return _fail(exc) + return _ok("광고비를 저장했습니다.") + + def _read_images(files: list[UploadFile]) -> list[dict[str, Any]]: """고른 파일을 실제 이미지로 확인·메타데이터 제거(GPS 등). 틀리면 ValueError — 아무것도 저장하지 않게 DB 전에.""" picked = [f for f in files if f.filename] diff --git a/app/modules/live/store.py b/app/modules/live/store.py index a7d1d6a..db597f9 100644 --- a/app/modules/live/store.py +++ b/app/modules/live/store.py @@ -4,7 +4,7 @@ from __future__ import annotations import io import re -from datetime import date, time +from datetime import date, datetime, time, timedelta from decimal import ROUND_HALF_UP, Decimal, InvalidOperation from typing import Any @@ -13,6 +13,15 @@ from PIL import Image MAX_IMAGES = 10 # 방송 한 건에 MAX_SALES = Decimal("999999999999.99") THUMB_SIZE = 160 +# shortcut: 요율이 코드 상수라 바꾸면 지난 방송 금액도 다시 계산된다 — 요율이 바뀌는 일이 생기면 방송마다 저장하도록 바꿀 것 +HOURLY_RATE = Decimal("25") # 호스트 시간당 요금(RM) +COMMISSION_PERCENT = Decimal("10") # 판매금액의 % +SLOT_HOURS = 2 # 달력 한 칸 +FIRST_SLOT_HOUR = 6 # 달력에 늘 보이는 첫 칸(이보다 이른 칸은 방송이 있을 때만) +HOST_COLORS = ("#66d4e6", "#6ee05a", "#d4f06a", "#e9cf7a", "#ec9d88", "#cdb9ea", "#f4a9c8", "#a9c4f5") +_CENT = Decimal("0.01") +_WEEKDAYS = ("MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY") +_MONTHS = ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC") HOST_LIMITS = {"full_name": 200, "phone": 40, "email": 254, "address": 500, "bank_name": 100, "bank_account": 40, "tiktok_handle": 64} _LABELS = {"full_name": "Full Name", "phone": "Phone Number", "email": "Email", "address": "Address", "bank_name": "Bank Name", @@ -80,7 +89,7 @@ def _parse_time(raw: Any, *, label: str, required: bool) -> time | None: def clean_broadcast(values: dict[str, Any]) -> dict[str, Any]: - """방송 입력 검사 — 호스트·날짜·시작 시간 필수. 끝 시간이 시작보다 이르면 자정을 넘긴 방송으로 본다. 틀리면 ValueError.""" + """방송 입력 검사 — 호스트·날짜·시작·끝 시간 필수(끝 시간으로 시간 요금 계산). 끝이 시작보다 이르면 자정을 넘긴 방송. 틀리면 ValueError.""" host = str(values.get("host_id") or "").strip() if not host.isdigit(): raise ValueError("호스트를 고르세요.") @@ -91,12 +100,99 @@ def clean_broadcast(values: dict[str, Any]) -> dict[str, Any]: 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), + start = _parse_time(values.get("start_time"), label="시작 시간", required=True) + end = _parse_time(values.get("end_time"), label="끝 시간", required=True) + if start == end: + raise ValueError("끝 시간이 시작 시간과 같습니다.") + return {"host_id": int(host), "broadcast_date": day, "start_time": start, "end_time": end, "venue": venue, "sales_amount": parse_money(values.get("sales_amount"))} +def parse_move(day: Any, start: Any) -> tuple[date, time]: + """달력 칸 — 날짜·시작 시간. 틀리면 ValueError.""" + try: + when = date.fromisoformat(str(day or "").strip()) + except ValueError: + raise ValueError("날짜가 올바르지 않습니다.") from None + return when, _parse_time(start, label="시간", required=True) + + +def moved_end(old_start: time, old_end: time | None, new_start: time) -> time | None: + """칸을 옮겨도 방송 길이는 그대로.""" + if old_end is None: + return None + return (datetime.combine(date.min, new_start) + _duration(old_start, old_end)).time() + + +def _duration(start: time, end: time) -> timedelta: + minutes = (end.hour * 60 + end.minute - start.hour * 60 - start.minute) % 1440 # 끝이 더 이르면 자정을 넘긴 방송 + return timedelta(minutes=minutes) + + +def session_pay(start: time, end: time | None, sales: Decimal | None) -> dict[str, Decimal]: + """호스트 비용 — 기본 요금(시간 × 시간당 요금) + 커미션(판매금액 × %).""" + hours = Decimal(_duration(start, end).seconds) / 3600 if end else Decimal(0) + base = (hours * HOURLY_RATE).quantize(_CENT, rounding=ROUND_HALF_UP) + commission = ((sales or Decimal(0)) * COMMISSION_PERCENT / 100).quantize(_CENT, rounding=ROUND_HALF_UP) + return {"hours": hours, "base": base, "commission": commission, "fee": base + commission} + + +def fmt_short(n: Decimal) -> str: + """카드·합계용 — 소수점 아래가 0 이면 뺀다(48, 4.80, 1,234.50).""" + return f"{n:,.2f}".removesuffix(".00") + + +def broadcast_view(b: dict[str, Any]) -> dict[str, Any]: + """방송 한 건 화면 값 — 표·달력 공통. b = db.list_broadcasts 한 줄.""" + pay = session_pay(b["start_time"], b["end_time"], b["sales_amount"]) + return { + "date": fmt_date(b["broadcast_date"]), "times": fmt_times(b["start_time"], b["end_time"]), + "host_name": b["host_name"], "tiktok_handle": b["tiktok_handle"], "venue": b["venue"], + "sales": fmt_money(b["sales_amount"]), "commission": fmt_money(pay["commission"]), "fee": fmt_money(pay["fee"]), + "images": b["images"], "pay": pay, "id": b["id"], + "label": b["tiktok_handle"] or b["host_name"], "color": HOST_COLORS[b["host_id"] % len(HOST_COLORS)], + "card_sales": fmt_short(b["sales_amount"] or Decimal(0)), "card_commission": fmt_short(pay["commission"]), + "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 "", + "images": [{"id": i["id"], "filename": i["filename"]} for i in b["images"]]}, + } + + +def _roas(sales: Decimal, ad_spend: Decimal) -> str: + return f"{sales / ad_spend:.2f}" if ad_spend else "-" + + +def build_calendar(span: dict[str, Any], broadcasts: list[dict[str, Any]], ad_spend: dict[date, Decimal], today: date) -> dict[str, Any]: + """달력 보기 값 — 날짜(열)·2시간 칸(줄)·날짜별 합계·달 합계. 칸은 시작 시간으로 정한다.""" + views = [(b, broadcast_view(b)) for b in broadcasts] + used = {b["start_time"].hour // SLOT_HOURS * SLOT_HOURS for b, _ in views} + days = [] + day = span["start"] + while day < span["end"]: + mine = [(b, v) for b, v in views if b["broadcast_date"] == day] + sales = sum((b["sales_amount"] or Decimal(0) for b, _ in mine), Decimal(0)) + fee = sum((v["pay"]["fee"] for _, v in mine), Decimal(0)) + spend = ad_spend.get(day, Decimal(0)) + days.append({"iso": day.isoformat(), "date": day, "day": day.day, "weekday": _WEEKDAYS[day.weekday()], + "label": f"{day.day} {_MONTHS[day.month - 1]}", "is_weekend": day.weekday() >= 5, "is_today": day == today, + "count": len(mine), "sales": sales, "fee": fee, "spend": spend, + "sales_text": fmt_short(sales), "fee_text": fmt_short(fee), "spend_text": fmt_short(spend), "roas": _roas(sales, spend)}) + day += timedelta(days=1) + slots = [] + for hour in sorted(set(range(FIRST_SLOT_HOUR, 24, SLOT_HOURS)) | used): + end_hour = (hour + SLOT_HOURS) % 24 + cells = [{"iso": d["iso"], "is_weekend": d["is_weekend"], + "cards": [v for b, v in views if b["broadcast_date"] == d["date"] and b["start_time"].hour // SLOT_HOURS * SLOT_HOURS == hour]} + for d in days] + slots.append({"start": f"{hour:02d}:00", "end": f"{end_hour:02d}:00", "label": f"{hour:02d}:00 - {end_hour:02d}:00", "cells": cells}) + sales, fee, spend = (sum((d[k] for d in days), Decimal(0)) for k in ("sales", "fee", "spend")) + return {"days": days, "slots": slots, "slot_note": f"{SLOT_HOURS} Hours (RM{fmt_short(HOURLY_RATE * SLOT_HOURS)} Base)", + "commission_percent": fmt_short(COMMISSION_PERCENT).split(".")[0], + "totals": {"sales": fmt_short(sales), "fee": fmt_short(fee), "spend": fmt_short(spend), "roas": _roas(sales, spend)}} + + def month_range(raw: Any, today: date) -> dict[str, Any]: """'YYYY-MM'(틀리거나 없으면 이번 달) → 그 달 첫날·다음 달 첫날·앞뒤 달 주소 값·제목.""" m = re.fullmatch(r"(\d{4})-(\d{2})", str(raw or "").strip()) diff --git a/app/modules/live/templates/live/_bar.html b/app/modules/live/templates/live/_bar.html new file mode 100644 index 0000000..d005870 --- /dev/null +++ b/app/modules/live/templates/live/_bar.html @@ -0,0 +1,18 @@ +{#- 스케줄표·달력 공통 위 막대 — 달 이동, 표/달력 전환, 호스트 설정, 방송 추가. view = table | calendar -#} +{% set here = '/live/calendar' if view == 'calendar' else '/live/' %} +{% set can_add = hosts | selectattr('is_active') | list %} +
+ ◀ +

{{ span.label }}

+ ▶ + + + {% if is_admin %}호스트 설정{% endif %} + +
+{% if not can_add %} +

방송을 추가하려면 먼저 {% if is_admin %}호스트 설정에서{% else %}ERP 관리자가 호스트 설정에서{% endif %} 호스트를 등록해야 합니다.

+{% endif %} diff --git a/app/modules/live/templates/live/_dialog.html b/app/modules/live/templates/live/_dialog.html new file mode 100644 index 0000000..35c34a7 --- /dev/null +++ b/app/modules/live/templates/live/_dialog.html @@ -0,0 +1,30 @@ +{#- 방송 추가·고치기 창 — 스케줄표·달력 공통(live.js). 호스트 고르기엔 이름·틱톡만(계좌 등은 설정 화면). -#} + +
+

+ + +
+ + + +
+

시간은 말레이시아 시간으로 입력합니다.

+ + + + + +
+ + +
+
+
diff --git a/app/modules/live/templates/live/calendar.html b/app/modules/live/templates/live/calendar.html new file mode 100644 index 0000000..1dca65f --- /dev/null +++ b/app/modules/live/templates/live/calendar.html @@ -0,0 +1,86 @@ +{% extends "erp_base.html" %} +{#- 라이브 커머스 달력 보기(2026-11-04) — 줄 = 2시간 칸, 열 = 날짜, 맨 아래 = 날짜별 합계. 카드 머리 = Tiktok Handle(없으면 이름). + 카드 머리를 끌어 빈 칸으로 옮기거나 다른 카드 위에 놓아 맞바꾼다(live.js). 글자는 사용자가 준 화면 그대로 영어. -#} +{% block head_extra %}{% endblock %} + +{% block content %} +
+ {% include "live/_bar.html" %} + +
+
TOTAL SALESRM {{ cal.totals.sales }}
+
AD SPENDRM {{ cal.totals.spend }}
+
HOST FEERM {{ cal.totals.fee }}
+
ROAS{{ cal.totals.roas }}
+
+ + +

Tip: Drag & drop any host header to move or swap dates. Scroll right → to see the entire {{ cal.days | length }} days of the month.

+ +
+ + + + + {% for d in cal.days %} + + {% endfor %} + + + + {% for slot in cal.slots %} + + + {% for cell in slot.cells %} + + {% endfor %} + + {% endfor %} + + + + + {% for d in cal.days %} + + {% endfor %} + + +
TIME +
{{ d.weekday }} {{ d.count }}
+
{{ d.label }}
+
{{ slot.label }}{{ cal.slot_note }} + {% for c in cell.cards %} +
+
+ + {{ c.label }} + +
+
+
SALES{{ c.card_sales }}
+
COM ({{ cal.commission_percent }}%){{ c.card_commission }}
+
+ +
+ {% endfor %} + {% if not cell.cards and hosts | selectattr('is_active') | list %} + + {% endif %} +
TOTAL & ROAS +
+
TOTAL SALES:
RM {{ d.sales_text }}
+
AD SPEND:
RM {{ d.spend_text }}
+
HOST FEE:
RM {{ d.fee_text }}
+
ROAS:
{{ d.roas }}
+
+
+
+
+ +{% include "live/_dialog.html" %} +{% endblock %} + +{% block scripts %}{% endblock %} diff --git a/app/modules/live/templates/live/index.html b/app/modules/live/templates/live/index.html index ace5e16..95a7253 100644 --- a/app/modules/live/templates/live/index.html +++ b/app/modules/live/templates/live/index.html @@ -1,25 +1,15 @@ {% extends "erp_base.html" %} -{#- 라이브 커머스 스케줄표(2026-11-04) — 달마다 방송 목록. 추가·고치기는 같은 창(live.js). 호스트 고르기엔 이름·틱톡만(계좌 등은 설정 화면). -#} -{% block head_extra %}{% endblock %} +{#- 라이브 커머스 스케줄표(2026-11-04) — 달마다 방송 목록. 추가·고치기 창은 달력과 공용(_dialog.html, live.js). -#} +{% block head_extra %}{% endblock %} {% block content %}
-
- ◀ -

{{ span.label }}

- ▶ - - {% if is_admin %}호스트 설정{% endif %} - -
- {% if not hosts | selectattr('is_active') | list %} -

방송을 추가하려면 먼저 {% if is_admin %}호스트 설정에서{% else %}ERP 관리자가 호스트 설정에서{% endif %} 호스트를 등록해야 합니다.

- {% endif %} + {% include "live/_bar.html" %}
- + {% for r in rows %} @@ -28,14 +18,16 @@ + + {% else %} - + {% endfor %}
날짜시간호스트방송 장소판매금액(RM)방송 결과
날짜시간호스트방송 장소판매금액(RM)커미션 10%(RM)호스트 비용(RM)방송 결과
{{ r.host_name }}{% if r.tiktok_handle %}
@{{ r.tiktok_handle }}
{% endif %}
{{ r.venue }} {{ r.sales }}{{ r.commission }}{{ r.fee }}
{% for im in r.images %}{{ im.filename }}{% endfor %}
- +
이 달에 등록한 방송이 없습니다.
이 달에 등록한 방송이 없습니다.
@@ -43,35 +35,7 @@
- -
-

- - -
- - - -
-

시간은 말레이시아 시간으로 입력합니다.

- - - - - -
- - -
-
-
+{% include "live/_dialog.html" %} {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/live/templates/live/settings.html b/app/modules/live/templates/live/settings.html index 83038a4..191be5b 100644 --- a/app/modules/live/templates/live/settings.html +++ b/app/modules/live/templates/live/settings.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} {#- 라이브 커머스 설정(2026-11-04) — 호스트 정보. 계좌 등 개인정보라 ERP 관리자만(router.settings). 추가·고치기는 같은 창(live.js). -#} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
@@ -63,4 +63,4 @@ {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/static/live.css b/app/static/live.css index ee7748d..ef41bb4 100644 --- a/app/static/live.css +++ b/app/static/live.css @@ -26,6 +26,61 @@ .lv-table td.lv-r { text-align: left; } } +.lv-views { display: inline-flex; gap: 4px; margin-left: 10px; } + +/* ── 달력 보기 ── */ +.lv-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; } +.lv-kpi { display: flex; flex-direction: column; gap: 2px; padding: 10px 14px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 10px; background: #fff; } +.lv-kpi span { font-size: 11px; font-weight: 600; letter-spacing: .04em; color: var(--color-midtone-gray, #666); } +.lv-kpi b { font-size: 18px; font-variant-numeric: tabular-nums; } +.lv-jump { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; padding: 8px 12px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 10px; background: #fff; } +.lv-jump-label { margin-right: 4px; font-size: 13px; font-weight: 600; color: #4b5563; } +.lv-jump-day { min-width: 28px; height: 28px; padding: 0 4px; border: 1px solid transparent; border-radius: 6px; background: #f1f3f6; color: #1f2937; font-size: 13px; font-weight: 600; cursor: pointer; } +.lv-jump-day:hover { background: #e2e6ec; } +.lv-jump-day.is-weekend { background: #fff6dc; border-color: #f3e2ae; color: #8a4b08; } +.lv-jump-day.is-today { outline: 2px solid #111; outline-offset: -2px; } +.lv-tip { margin: 0; padding: 8px 12px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 10px; background: #f6f8fb; font-size: 13px; color: #374151; } + +.lv-cal-wrap { overflow: auto; max-height: calc(100vh - 150px); border: 1px solid #cfd4dc; border-radius: 10px; background: #fff; } +.lv-cal { border-collapse: separate; border-spacing: 0; min-width: max-content; } +.lv-cal th, .lv-cal td { border-right: 1px solid #e3e6eb; border-bottom: 1px solid #e3e6eb; } +.lv-cal thead th { position: sticky; top: 0; z-index: 2; width: 182px; min-width: 182px; padding: 8px 6px; background: #e4e8ee; text-align: center; font-weight: 700; } +.lv-cal thead th.is-weekend { background: #f5efd3; color: #7a5c00; } +.lv-cal thead th.is-today { box-shadow: inset 0 -3px 0 #111; } +.lv-cal-weekday { font-size: 13px; letter-spacing: .03em; } +.lv-cal-count { display: inline-block; min-width: 18px; padding: 0 4px; margin-left: 2px; border: 1px solid #cfd4dc; border-radius: 4px; background: #fff; color: #374151; font-size: 11px; font-weight: 600; } +.lv-cal-date { margin-top: 2px; font-size: 11px; font-weight: 600; color: #6b7280; } +.lv-cal .lv-cal-time { position: sticky; left: 0; z-index: 1; width: 132px; min-width: 132px; padding: 8px; background: #f6f7f9; text-align: center; font-size: 13px; font-weight: 700; white-space: nowrap; } +.lv-cal thead .lv-cal-time { z-index: 3; background: #d9dee6; } +.lv-cal .lv-cal-time small { display: block; margin-top: 2px; font-size: 10.5px; font-weight: 600; color: #6b7280; } +.lv-cell { min-height: 100px; padding: 4px; vertical-align: top; background: #fff; } +.lv-cell.is-weekend { background: #fffdf3; } +.lv-cell.is-drop { background: #e8f1ff; box-shadow: inset 0 0 0 2px #3b82f6; } +.lv-cell-add { display: block; width: 100%; min-height: 88px; border: 1px dashed #d8dce3; border-radius: 6px; background: transparent; color: #b0b6c0; font-size: 16px; cursor: pointer; } +.lv-cell-add:hover, .lv-cell-add:focus-visible { border-color: #6b7280; color: #374151; } +.lv-card { margin-bottom: 4px; border: 1.5px solid #1f2937; border-radius: 6px; background: #fff; overflow: hidden; } +.lv-card-head { display: flex; align-items: center; gap: 4px; padding: 3px 6px; border-bottom: 1px solid #1f2937; cursor: grab; } +.lv-card-head:active { cursor: grabbing; } +.lv-card-grip { font-size: 12px; color: #374151; } +.lv-card-name { flex: 1 1 auto; min-width: 0; overflow: hidden; text-align: center; text-overflow: ellipsis; white-space: nowrap; text-transform: uppercase; font-size: 13px; font-weight: 800; letter-spacing: .03em; color: #111; } +.lv-card-edit { padding: 0 2px; border: 0; background: none; color: #374151; font-size: 13px; cursor: pointer; } +.lv-card-nums { display: grid; grid-template-columns: 1fr 1fr; } +.lv-card-nums div { display: flex; flex-direction: column; text-align: center; } +.lv-card-nums div + div { border-left: 1px solid #e3e6eb; } +.lv-card-nums span { padding: 2px 0; background: #f6f7f9; font-size: 10px; font-weight: 600; color: #4b5563; } +.lv-card-nums b { padding: 3px 0; font-size: 14px; font-variant-numeric: tabular-nums; } +.lv-card-foot { display: flex; justify-content: space-between; gap: 4px; padding: 2px 6px; border-top: 1px solid #e3e6eb; background: #f6f7f9; font-size: 10.5px; font-weight: 600; color: #4b5563; } +.lv-card-foot b { color: #8a2c0d; } +.lv-card-foot a { color: #1d4f91; } +.lv-cal tfoot th, .lv-cal tfoot td { position: sticky; bottom: 0; z-index: 2; padding: 8px; background: #101a33; color: #fff; border-color: #2a3550; } +.lv-cal tfoot .lv-cal-time { z-index: 3; background: #101a33; font-size: 12px; } +.lv-total { display: flex; flex-direction: column; gap: 2px; margin: 0; font-size: 11px; font-weight: 600; } +.lv-total div { display: flex; justify-content: space-between; gap: 6px; } +.lv-total dt { color: #aab3c5; } +.lv-total dd { margin: 0; font-variant-numeric: tabular-nums; color: #fbbf72; white-space: nowrap; } +.lv-total dd.is-sales { color: #6ee7a8; } +.lv-total-edit { padding: 0 2px; border: 0; background: none; color: #cbd5e1; font-size: 11px; cursor: pointer; } + .lv-dlg { 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; } diff --git a/app/static/live.js b/app/static/live.js index 90f4385..58e7688 100644 --- a/app/static/live.js +++ b/app/static/live.js @@ -1,6 +1,13 @@ -/* 라이브 커머스(2026-11-04) — 스케줄표·호스트 설정 공용: 추가·고치기 창, 저장·지우기(fetch → JSON {ok, message}, 틀려도 입력한 값이 창에 남음). */ +/* 라이브 커머스(2026-11-04) — 스케줄표·달력·호스트 설정 공용: 추가·고치기 창, 저장·지우기(fetch → JSON {ok, message}, 틀려도 입력한 값이 창에 남음). + 달력: Jump to Date, 카드 끌어 옮기기·맞바꾸기, 날짜별 광고비. 다시 그린 뒤에도 보던 가로 위치 유지. */ (function () { "use strict"; + const calWrap = document.getElementById("lv-cal-wrap"); + const CAL_POS = "lv_cal_left"; + function reload() { + if (calWrap) { try { sessionStorage.setItem(CAL_POS, String(calWrap.scrollLeft)); } catch (_) {} } + location.reload(); + } const dlg = document.getElementById("lv-dlg"); const form = document.getElementById("lv-form"); if (!dlg || !form) return; @@ -60,16 +67,17 @@ function open(row) { form.reset(); say(""); - title.textContent = row ? title.dataset.edit : title.dataset.add; + const editing = !!(row && row.id); + title.textContent = editing ? title.dataset.edit : title.dataset.add; + form.elements.id.value = ""; Array.from(form.elements).forEach(function (el) { if (!row || !el.name || !(el.name in row)) return; if (el.type === "checkbox") el.checked = !!row[el.name]; else if (el.type !== "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); + showHosts(editing && row.host_id); + if (editing && hostSelect) hostSelect.value = String(row.host_id); // 위에서 보이게 한 뒤 다시 고름 + showSaved(editing && row.images); dlg.showModal(); } @@ -82,11 +90,13 @@ 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 fresh = e.target.closest("button[data-new]"); + if (fresh) { open(JSON.parse(fresh.dataset.new)); 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 (r.ok) { reload(); return; } if (dlg.open) say(r.message); else window.erpAlert(r.message); }); @@ -98,8 +108,75 @@ save.disabled = true; say(""); const r = await post(form.getAttribute("action"), body); - if (r.ok) { location.reload(); return; } + if (r.ok) { reload(); return; } save.disabled = false; say(r.message); }); + + if (!calWrap) return; + + // ── 달력: 날짜로 가기(TIME 열이 고정이라 그 폭만큼 띄움) ── + function jumpTo(iso) { + const col = calWrap.querySelector('thead th[data-day="' + iso + '"]'); + const time = calWrap.querySelector("thead .lv-cal-time"); + if (col && time) calWrap.scrollLeft += col.getBoundingClientRect().left - time.getBoundingClientRect().right; + } + document.addEventListener("click", function (e) { + const b = e.target.closest("[data-jump]"); + if (b) jumpTo(b.dataset.jump); + }); + let left = null; + try { left = sessionStorage.getItem(CAL_POS); sessionStorage.removeItem(CAL_POS); } catch (_) {} + if (left !== null) calWrap.scrollLeft = Number(left); + else { + const today = calWrap.querySelector("thead th[data-today]"); + if (today) jumpTo(today.dataset.day); + } + + // ── 달력: 날짜별 광고비 ── + document.addEventListener("click", async function (e) { + const b = e.target.closest("button[data-spend]"); + if (!b) return; + const value = await window.erpPrompt(b.dataset.spend + " AD SPEND (RM) — 비우면 지웁니다", b.dataset.value || ""); + if (value === null || value === undefined) return; + const body = new FormData(); + body.set("day", b.dataset.spend); + body.set("amount", value); + const r = await post("/live/ad-spend", body); + if (r.ok) reload(); else window.erpAlert(r.message); + }); + + // ── 달력: 카드 머리를 끌어 빈 칸으로 옮기기, 다른 카드 위에 놓아 맞바꾸기 ── + let dragging = null; + calWrap.addEventListener("dragstart", function (e) { + const head = e.target.closest && e.target.closest(".lv-card-head"); + if (!head) return; + dragging = head.closest("[data-card]").dataset.card; + e.dataTransfer.effectAllowed = "move"; + e.dataTransfer.setData("text/plain", dragging); + }); + calWrap.addEventListener("dragend", function () { + dragging = null; + calWrap.querySelectorAll(".is-drop").forEach(function (c) { c.classList.remove("is-drop"); }); + }); + calWrap.addEventListener("dragover", function (e) { + const cell = dragging && e.target.closest("[data-drop]"); + if (!cell) return; + e.preventDefault(); + calWrap.querySelectorAll(".is-drop").forEach(function (c) { if (c !== cell) c.classList.remove("is-drop"); }); + cell.classList.add("is-drop"); + }); + calWrap.addEventListener("drop", async function (e) { + const cell = dragging && e.target.closest("[data-drop]"); + if (!cell) return; + e.preventDefault(); + const id = dragging; + const onto = e.target.closest("[data-card]"); + if (onto && onto.dataset.card === id) return; + const body = new FormData(); + if (onto) body.set("swap_with", onto.dataset.card); + else { body.set("broadcast_date", cell.dataset.day); body.set("start_time", cell.dataset.start); } + const r = await post("/live/broadcasts/" + id + "/move", body); + if (r.ok) reload(); else window.erpAlert(r.message); + }); })(); diff --git a/docs/DATABASES.md b/docs/DATABASES.md index d121444..98aa304 100644 --- a/docs/DATABASES.md +++ b/docs/DATABASES.md @@ -315,6 +315,7 @@ 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_broadcast_images` | 방송 결과 이미지(메타데이터 제거 후 BYTEA, 방송을 지우면 CASCADE) — 방송당 최대 10장(앱에서 확인) | +| `live_daily_ad_spend` | 날짜별 광고비(RM) — 달력 보기 AD SPEND·ROAS. 마이그레이션 `live_db_002_ad_spend.sql`(init 에도 포함) | ## malaysia_stock_db 스키마 / 초기화 diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index ebf05b0..7c5c152 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -381,7 +381,7 @@ docker exec dbx-main python -c "import os,psycopg; psycopg.connect(os.environ['O ```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 없음 — 새로 만든다" +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=''))") @@ -391,6 +391,9 @@ 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')" ``` +이미 만든 live_db 에는 `scripts/sql/live_db_002_ad_spend.sql`(날짜별 광고비 표 하나 추가, 다시 실행 가능)을 백업 뒤 적용한다 — 초기화 SQL 을 다시 돌리면 `live_app` 비밀번호를 다시 넣게 되므로 쓰지 않는다. +되돌리기 = `DROP TABLE live_daily_ad_spend;`(광고비 값만 사라짐). + 그다음 ERP 관리자 화면에서 쓸 사람에게 **라이브 커머스** 권한 → ERP 관리자가 라이브 커머스 → 호스트 설정에서 호스트 등록. 백업: 매일 `docker exec postgres-db pg_dump -U postgres live_db > /var/backups/postgres/live_db_$(date +%F).sql`. diff --git a/scripts/sql/live_db_002_ad_spend.sql b/scripts/sql/live_db_002_ad_spend.sql new file mode 100644 index 0000000..2ae6edf --- /dev/null +++ b/scripts/sql/live_db_002_ad_spend.sql @@ -0,0 +1,21 @@ +-- ===================================================================== +-- live_db 마이그레이션 002 — 날짜별 광고비(달력 보기 맨 아래 AD SPEND·ROAS)(2026-11-04) +-- ===================================================================== +-- 멱등(idempotent). 표 하나만 추가(기존 표·값 변경 없음). 운영: /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_002_ad_spend.sql +-- 되돌리기: DROP TABLE live_daily_ad_spend; (광고비 값만 사라짐 — 실행 전 백업) +-- ===================================================================== +\set ON_ERROR_STOP on +BEGIN; + +CREATE TABLE IF NOT EXISTS live_daily_ad_spend ( + ad_date DATE PRIMARY KEY, + ad_spend NUMERIC(14,2) NOT NULL CHECK (ad_spend >= 0), + updated_by TEXT NOT NULL DEFAULT '', + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +COMMENT ON TABLE live_daily_ad_spend IS '라이브 커머스 — 날짜별 광고비(RM)'; +GRANT SELECT, INSERT, UPDATE, DELETE ON live_daily_ad_spend TO live_app; + +COMMIT; +SELECT 'live_db 002 ad spend ready' AS status; diff --git a/scripts/sql/live_db_init.sql b/scripts/sql/live_db_init.sql index e184b37..e8d71d4 100644 --- a/scripts/sql/live_db_init.sql +++ b/scripts/sql/live_db_init.sql @@ -104,11 +104,22 @@ CREATE TABLE IF NOT EXISTS live_broadcast_images ( COMMENT ON TABLE live_broadcast_images IS '라이브 커머스 — 방송 결과 이미지'; CREATE INDEX IF NOT EXISTS idx_live_images_broadcast ON live_broadcast_images (broadcast_id, id); +-- ════════════════════════════════════════════════════════════ +-- 3-1) 날짜별 광고비 — 마이그레이션 002 와 같음(달력 보기 AD SPEND·ROAS) +-- ════════════════════════════════════════════════════════════ +CREATE TABLE IF NOT EXISTS live_daily_ad_spend ( + ad_date DATE PRIMARY KEY, + ad_spend NUMERIC(14,2) NOT NULL CHECK (ad_spend >= 0), + updated_by TEXT NOT NULL DEFAULT '', + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +COMMENT ON TABLE live_daily_ad_spend IS '라이브 커머스 — 날짜별 광고비(RM)'; + -- ════════════════════════════════════════════════════════════ -- 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 SELECT, INSERT, UPDATE, DELETE ON live_hosts, live_broadcasts, live_broadcast_images, live_daily_ad_spend 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; diff --git a/tests/test_live.py b/tests/test_live.py index 717c8cf..eacf6d8 100644 --- a/tests/test_live.py +++ b/tests/test_live.py @@ -82,13 +82,13 @@ class StoreTests(unittest.TestCase): 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": "", + 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": None, + 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")}) - good = {"host_id": "3", "broadcast_date": "2026-11-04", "start_time": "20: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": "nope"}, {"venue": "x" * 201}, {"sales_amount": "-5"}): + {"start_time": "25:00"}, {"end_time": ""}, {"end_time": "nope"}, {"end_time": "20:00"}, {"venue": "x" * 201}, {"sales_amount": "-5"}): with self.assertRaises(ValueError, msg=over): store.clean_broadcast({**good, **over}) @@ -109,6 +109,57 @@ class StoreTests(unittest.TestCase): self.assertEqual(store.fmt_money(Decimal("1234.5")), "1,234.50") self.assertEqual(store.fmt_money(None), "") + def test_session_pay(self): + """호스트 비용 = 시간 × RM 25 + 판매금액 10%. 받은 화면의 예: 2시간·판매 48 → 50 + 4.8.""" + p = store.session_pay(time(12, 0), time(14, 0), Decimal("48")) + self.assertEqual((p["base"], p["commission"], p["fee"]), (Decimal("50.00"), Decimal("4.80"), Decimal("54.80"))) + self.assertEqual(store.session_pay(time(22, 0), time(0, 0), None)["fee"], Decimal("50.00")) # 자정까지 + self.assertEqual(store.session_pay(time(23, 0), time(1, 30), None)["base"], Decimal("62.50")) # 자정 넘김·30분 + self.assertEqual(store.session_pay(time(12, 0), None, Decimal("10"))["fee"], Decimal("1.00")) # 끝 시간 없음 = 기본 요금 없음 + self.assertEqual(store.session_pay(time(12, 0), time(14, 0), Decimal("0.05"))["commission"], Decimal("0.01")) # 반올림 + self.assertEqual((store.fmt_short(Decimal("48")), store.fmt_short(Decimal("4.80")), store.fmt_short(Decimal("1234.5"))), ("48", "4.80", "1,234.50")) + + def test_moved_end(self): + self.assertEqual(store.moved_end(time(12, 0), time(14, 30), time(20, 0)), time(22, 30)) + self.assertEqual(store.moved_end(time(12, 0), time(14, 0), time(22, 0)), time(0, 0)) # 자정으로 넘어감 + self.assertIsNone(store.moved_end(time(12, 0), None, time(20, 0))) + self.assertEqual(store.parse_move("2026-11-04", "20:00"), (date(2026, 11, 4), time(20, 0))) + for bad in (("", "20:00"), ("2026-11-04", ""), ("nope", "20:00")): + with self.assertRaises(ValueError): + store.parse_move(*bad) + + def test_build_calendar(self): + def b(id, day, start, end, sales=None, host=1, handle="yaya"): + return {"id": id, "host_id": host, "host_name": "Yaya", "tiktok_handle": handle, "broadcast_date": day, "start_time": start, + "end_time": end, "venue": "", "sales_amount": sales, "images": []} + span = store.month_range("2026-11", date(2026, 11, 4)) + cal = store.build_calendar(span, [b(1, date(2026, 11, 4), time(12, 0), time(14, 0), Decimal("48")), + b(2, date(2026, 11, 4), time(22, 0), time(0, 0), handle=""), + b(3, date(2026, 11, 7), time(13, 30), time(15, 0))], + {date(2026, 11, 4): Decimal("24")}, date(2026, 11, 4)) + self.assertEqual(len(cal["days"]), 30) + self.assertEqual([s["label"] for s in cal["slots"]][0], "06:00 - 08:00") + self.assertEqual([s["label"] for s in cal["slots"]][-1], "22:00 - 00:00") + self.assertEqual(len(cal["slots"]), 9) + self.assertEqual(cal["slot_note"], "2 Hours (RM50 Base)") + d4 = cal["days"][3] + self.assertEqual((d4["weekday"], d4["label"], d4["count"], d4["is_today"], d4["is_weekend"]), ("WEDNESDAY", "4 NOV", 2, True, False)) + self.assertEqual((d4["sales_text"], d4["spend_text"], d4["fee_text"], d4["roas"]), ("48", "24", "104.80", "2.00")) + self.assertEqual(cal["days"][6]["is_weekend"], True) # 11-07 토 + self.assertEqual(cal["days"][0]["roas"], "-") # 광고비 없음 + noon = next(s for s in cal["slots"] if s["start"] == "12:00") + self.assertEqual(noon["cells"][3]["cards"][0]["label"], "yaya") # 카드 머리 = Tiktok Handle + self.assertEqual((noon["cells"][3]["cards"][0]["card_sales"], noon["cells"][3]["cards"][0]["card_commission"], noon["cells"][3]["cards"][0]["card_fee"]), + ("48", "4.80", "54.80")) + late = next(s for s in cal["slots"] if s["start"] == "22:00") + self.assertEqual((late["end"], late["cells"][3]["cards"][0]["label"]), ("00:00", "Yaya")) # 핸들 없으면 이름 + self.assertEqual(next(s for s in cal["slots"] if s["start"] == "12:00")["cells"][6]["cards"][0]["id"], 3) # 13:30 = 12~14 칸 + self.assertEqual(cal["totals"]["sales"], "48") + # 06시보다 이른 칸은 방송이 있을 때만 + early = store.build_calendar(span, [b(9, date(2026, 11, 1), time(3, 0), time(5, 0))], {}, date(2026, 11, 4)) + self.assertEqual(early["slots"][0]["label"], "02:00 - 04:00") + self.assertEqual(len(early["slots"]), 10) + def test_thumbnail(self): for mode, fmt in (("RGB", "JPEG"), ("RGBA", "PNG")): raw = io.BytesIO() @@ -194,6 +245,7 @@ def body(c): assert r.json()["ok"], r.text page = c.get("/live/?month=2031-03").text assert "2031.03.05(수)" in page and "20:00 ~ 22:30" in page and "KL Studio" in page and "1,234.50" in page + assert ">123.45" in page and ">185.95" in page # 커미션 10%·호스트 비용(2.5시간 × 25 + 123.45) 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) @@ -213,10 +265,49 @@ def body(c): who["u"] = staff # ── 고치기: 값 바뀜, 이미지 유지 + 더하기, 판매금액 지우기, 10장 제한 ── - r = c.post("/live/broadcasts", data={**show, "id": bid, "venue": "PJ Studio", "sales_amount": "", "end_time": ""}) + r = c.post("/live/broadcasts", data={**show, "id": bid, "venue": "PJ Studio", "sales_amount": "", "end_time": "21:00"}) assert r.json()["ok"], r.text page = c.get("/live/?month=2031-03").text - assert "PJ Studio" in page and "1,234.50" not in page and "20:00 ~" not in page + assert "PJ Studio" in page and "1,234.50" not in page and "20:00 ~ 21:00" in page + assert c.post("/live/broadcasts", data={**show, "end_time": ""}).status_code == 400 # 끝 시간 필수 + + # ── 달력: 카드 머리 = Tiktok Handle, Fee, 옮기기(길이 유지)·맞바꾸기, 광고비·ROAS, 권한 ── + c.post("/live/broadcasts", data={**show, "id": bid, "sales_amount": "48", "start_time": "12:00", "end_time": "14:00", "broadcast_date": "2031-03-05"}) + cal = c.get("/live/calendar?month=2031-03").text + assert "Jump to Date" in cal and "SATURDAY" in cal and "12:00 - 14:00" in cal and "2 Hours (RM50 Base)" in cal + assert 'siti.%s' % tag in cal and "RM54.80" in cal and ">4.80" in cal + assert ACCOUNT not in cal and "Maybank" not in cal + day = __import__("datetime").date + def one(i): + return next(b for b in st.list_broadcasts(day(2031, 3, 1), day(2031, 4, 1)) if b["id"] == i) + assert c.post("/live/broadcasts/%d/move" % bid, data={"broadcast_date": "2031-03-07", "start_time": "22:00"}).json()["ok"] + got = one(bid) + assert (got["broadcast_date"], str(got["start_time"]), str(got["end_time"])) == (day(2031, 3, 7), "22:00:00", "00:00:00") + assert c.post("/live/broadcasts/%d/move" % bid, data={"broadcast_date": "bad", "start_time": "22:00"}).status_code == 400 + assert c.post("/live/broadcasts/99999999/move", data={"broadcast_date": "2031-03-07", "start_time": "22:00"}).status_code == 400 + c.post("/live/broadcasts", data={**show, "broadcast_date": "2031-03-09", "start_time": "08:00", "end_time": "09:00", "venue": "Second"}) + other = next(b["id"] for b in st.list_broadcasts(day(2031, 3, 9), day(2031, 3, 10)) if b["venue"] == "Second") + assert c.post("/live/broadcasts/%d/move" % bid, data={"swap_with": other}).json()["ok"] + a, b2 = one(bid), one(other) + assert (a["broadcast_date"], str(a["start_time"]), str(a["end_time"])) == (day(2031, 3, 9), "08:00:00", "09:00:00") + assert (b2["broadcast_date"], str(b2["start_time"]), str(b2["end_time"])) == (day(2031, 3, 7), "22:00:00", "00:00:00") + assert c.post("/live/broadcasts/%d/move" % bid, data={"swap_with": 99999999}).status_code == 400 + assert c.post("/live/broadcasts/%d/move" % bid, data={"swap_with": bid}).json()["ok"] + assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "24"}).json()["ok"] + assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "12"}).json()["ok"] # 덮어쓰기 + assert st.ad_spends(day(2031, 3, 1), day(2031, 4, 1)) == {day(2031, 3, 9): __import__("decimal").Decimal("12.00")} + assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "-1"}).status_code == 400 + assert c.post("/live/ad-spend", data={"day": "bad", "amount": "1"}).status_code == 400 + assert "4.00" in c.get("/live/calendar?month=2031-03").text # ROAS 48 ÷ 12 + assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": ""}).json()["ok"] # 빈칸 = 지우기 + assert st.ad_spends(day(2031, 3, 1), day(2031, 4, 1)) == {} + assert c.post("/live/broadcasts/%d/delete" % other).json()["ok"] + c.post("/live/broadcasts", data={**show, "id": bid}) # 아래 시험을 위해 원래 값으로 + who["u"] = outsider + assert c.get("/live/calendar").status_code == 403 + assert c.post("/live/broadcasts/%d/move" % bid, data={"swap_with": bid}).status_code == 403 + assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "1"}).status_code == 403 + who["u"] = staff many = [("images", ("%d.jpg" % i, jpeg(), "image/jpeg")) for i in range(10)] r = c.post("/live/broadcasts", data={**show, "id": bid}, files=many) assert r.status_code == 400 and "10장" in r.json()["message"], r.text # 이미 1장 + 10장