From ecc76ae4d83acba501a3fdf101b146b40c3974a6 Mon Sep 17 00:00:00 2001 From: king Date: Fri, 6 Nov 2026 15:16:32 +0900 Subject: [PATCH] =?UTF-8?q?feat(=EB=9D=BC=EC=9D=B4=EB=B8=8C):=20=EB=B0=A9?= =?UTF-8?q?=EC=86=A1=20=EC=B0=BD=EC=97=90=20Fee=C2=B7=EC=BB=A4=EB=AF=B8?= =?UTF-8?q?=EC=85=98=20=EC=9E=90=EB=8F=99=20=EA=B3=84=EC=82=B0,=20?= =?UTF-8?q?=EA=B4=91=EA=B3=A0=EB=B9=84=C2=B7=ED=98=B8=EC=8A=A4=ED=8A=B8=20?= =?UTF-8?q?=EB=B9=84=EC=9A=A9=20=EC=9E=85=EB=A0=A5,=20=EB=B0=A9=EC=86=A1?= =?UTF-8?q?=20=EC=9E=A5=EC=86=8C=20=EB=BA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fee = 시간 x RM25, 커미션 = 판매금액 x 10% (저장 안 함, 이미지에서 매출을 읽으면 다시 계산) - 광고비·호스트 비용(수기) = 방송마다 저장 (마이그레이션 live_db_006_broadcast_fees.sql) - 달력 날짜 광고비 = 그날 방송 광고비 합, 호스트 비용 = host_fee 합 (날짜별 광고비 입력 버튼·/live/ad-spend 없앰) - 방송 장소는 창·표에서 뺌 (예전 값은 DB 에 그대로) Co-Authored-By: Claude Opus 5.5 --- app/modules/live/CLAUDE.md | 10 ++- app/modules/live/db.py | 38 ++------- app/modules/live/i18n.py | 20 ++--- app/modules/live/router.py | 24 ++---- app/modules/live/store.py | 42 +++++----- app/modules/live/templates/live/_dialog.html | 12 ++- app/modules/live/templates/live/_scripts.html | 2 +- app/modules/live/templates/live/calendar.html | 4 +- app/modules/live/templates/live/index.html | 11 +-- app/modules/live/templates/live/settings.html | 2 +- app/static/live.css | 2 +- app/static/live.js | 36 +++++---- docs/DATABASES.md | 4 +- scripts/sql/live_db_006_broadcast_fees.sql | 21 +++++ scripts/sql/live_db_init.sql | 6 +- tests/js/live_calendar.browser.test.js | 10 +++ tests/js/render_live.py | 7 +- tests/test_live.py | 81 ++++++++++--------- 18 files changed, 176 insertions(+), 156 deletions(-) create mode 100644 scripts/sql/live_db_006_broadcast_fees.sql diff --git a/app/modules/live/CLAUDE.md b/app/modules/live/CLAUDE.md index 7eee7a9..fa86b84 100644 --- a/app/modules/live/CLAUDE.md +++ b/app/modules/live/CLAUDE.md @@ -13,12 +13,14 @@ **쇼핑몰**(2026-11-06, 마이그레이션 005 `live_hosts.platform`, `store.PLATFORMS` = tiktok·shopee) — 창 맨 위 라디오 + 로고(같은 상자 88×26, 안 고르면 흑백·고르면 컬러), 저장 때 필수. 목록 첫 열 = 로고. 예전 호스트는 빈 값(고치기에서 고르면 저장). **목록의 사용 토글**(`POST /live/settings/hosts/{id}/active`, `db.set_host_active`) = 고치기 권한(관리자·`live_host_edit` 칩)만, 바로 저장·실패하면 되돌림. 권한 없으면 글자(사용/사용 안 함). 사용 안 함 = 새 방송에서 못 고름(그 호스트로 이미 등록된 방송을 고칠 때만 보임). 방송 기록이 있는 호스트는 못 지움(FK RESTRICT). -- **스케줄표** `/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/?month=YYYY-MM`(`live` 권한자 모두) — 호스트·날짜·시작/끝 시간·판매금액·시간 요금(Fee)·커미션·광고비·호스트 비용·결과 이미지. 호스트·날짜·시작·끝 시간 필수(판매금액은 방송 후 입력). + 시간은 입력한 말레이시아 시간 그대로(시간대 변환 없음, DATE·TIME). 금액 단위 RM(`NUMERIC(14,2)`, `store.parse_money(값, 이름)`). 끝 시간이 시작보다 이르면 자정을 넘긴 방송. + **방송 장소는 2026-11-06 에 창·표에서 뺌**(`venue` 열은 예전 값만 남고 저장 때 건드리지 않음, 달력 카드 말풍선에만 예전 값). +- **방송 창 금액**(2026-11-06, 마이그레이션 006) — **Fee**(시간 × RM 25 `HOURLY_RATE`)·**커미션**(판매금액 × 10% `COMMISSION_PERCENT`) = 자동, 저장 안 함(`store.session_pay`, 창에서는 `live.js recalc` 가 같은 계산 — 시간·판매금액을 바꾸거나 결과 이미지에서 매출을 읽으면 다시 계산). 요율이 코드 상수라 바꾸면 지난 방송 값도 바뀐다. + **광고비**(`live_broadcasts.ad_spend`)·**호스트 비용**(`host_fee`, 일단 수기 입력) = 입력·저장. 달력 카드 Fee·날짜/달 합계 호스트 비용 = `host_fee` 합(비우면 0). - **달력 보기** `/live/calendar?month=`(`store.build_calendar`, 사용자가 준 화면 참고, 글자도 영어 그대로) — 줄 = 1시간 칸(2026-11-06 `store.SLOT_HOURS` 2 → 1, 06:00~24:00 늘 보임, 그보다 이른 칸은 방송이 있을 때만, 칸은 시작 시간으로 정함), 열 = 날짜, 주말 노랑, 위 달 합계, 맨 아래 날짜별 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 으로 보이고 저장만 안내. + **AD SPEND** = 그날 방송 광고비(`ad_spend`) 합(2026-11-06 — 예전 날짜별 입력 `live_daily_ad_spend`·✎ 버튼·`/live/ad-spend` 없앰, 표는 값만 남김), ROAS = 판매금액 ÷ 광고비(광고비 없으면 `-`). - **한 화면 맞춤**(2026-11-05) — 달력 보기는 넓은 화면(1101px 이상)에서 페이지 세로 스크롤 없음: `.lv-cal-wrap` 이 남은 높이를 쓰고, 풀HD 브라우저(세로 880px 이상)면 방송이 없는 달은 18개 시간 칸·합계 줄이 표 안 스크롤 없이 들어간다(카드가 있는 줄은 카드 높이만큼 커져서 방송이 많으면 표 안에서 스크롤, 페이지는 안 움직임). **방송이 걸친 칸은 합친다**(2026-11-06, `store._covered_slots` → `rowspan`, 가려진 칸 `skip`) — 2시간 방송 = 두 칸, 끝이 정각이 아니면 그 칸까지, 자정 넘김은 그날 마지막 칸까지. 합친 칸 안에서 시작하는 다른 방송은 같은 칸에 들어가고 칸이 더 늘어난다(겹친 방송). 끌어 놓기는 합친 칸의 첫 시간으로. 카드·표 글자·칸 크기를 늘리면 `live_calendar.browser.test.js` 로 다시 확인. - **오른쪽 달력**(2026-11-05, 달력 보기만, 세로 2분할 `.lv-split`, 240px = 공용 달력의 80%, 예전 날짜로 이동 줄 대신, 공용 `erp-datepop` `mountRange` + `locale` 옵션으로 영문) — 날짜를 누르면 그 날이 표 맨 왼쪽(마지막 날까지 — `endGap` 이 표 끝에 여백), 다른 달이면 그 달 화면으로 가서 맨 왼쪽(sessionStorage `lv_cal_jump`). 표시만 하고 요금·일수에 안 씀. 글자 굵게, **방송 있는 날 = 숫자 오른쪽 위 초록 점**(2026-11-06, `db.broadcast_days` 보는 달 ±1년 → `#lv-live-days`, 공용 `mountRange` 의 `dayClass` 옵션 → `has-live`). 테스트 `tests/js/live_calendar.browser.test.js`(`render_live.py`). **말레이시아 공휴일 표 = `holidays.py`**(쿠알라룸푸르 기준, 2026·2027, 대체휴일 포함) — 이슬람 명절은 달 관측으로 바뀔 수 있고, 2028 은 공고되면 손으로 추가. diff --git a/app/modules/live/db.py b/app/modules/live/db.py index 6334a40..6bc81db 100644 --- a/app/modules/live/db.py +++ b/app/modules/live/db.py @@ -8,10 +8,9 @@ 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.errors import ForeignKeyViolation from psycopg.rows import dict_row from psycopg_pool import ConnectionPool @@ -120,15 +119,16 @@ class LiveDBStore: 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["tiktok_handle"], values["sales_amount"], by) + # 방송 장소(venue)는 2026-11-06 부터 입력 안 받음 — 예전 값은 그대로 둔다 + args = (values["host_id"], values["broadcast_date"], values["start_time"], values["end_time"], + values["tiktok_handle"], values["sales_amount"], values["ad_spend"], values["host_fee"], by) if broadcast_id is None: broadcast_id = int(conn.execute( - "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"]) + "INSERT INTO live_broadcasts (host_id, broadcast_date, start_time, end_time, tiktok_handle, sales_amount, ad_spend, host_fee, updated_by, created_by) " + "VALUES (%s,%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, " - "tiktok_handle=%s, sales_amount=%s, updated_by=%s WHERE id=%s", (*args, broadcast_id)) + conn.execute("UPDATE live_broadcasts SET host_id=%s, broadcast_date=%s, start_time=%s, end_time=%s, " + "tiktok_handle=%s, sales_amount=%s, ad_spend=%s, host_fee=%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) @@ -165,28 +165,6 @@ class LiveDBStore: 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: diff --git a/app/modules/live/i18n.py b/app/modules/live/i18n.py index c9e6048..e43e28e 100644 --- a/app/modules/live/i18n.py +++ b/app/modules/live/i18n.py @@ -18,14 +18,16 @@ EN: dict[str, str] = { # 방송 창 "방송 추가": "Add Broadcast", "방송 고치기": "Edit Broadcast", "호스트": "Host", "호스트를 고르세요": "Select a host", "사용 안 함": "Inactive", "방송 날짜": "Broadcast Date", "시작 시간": "Start Time", "끝 시간": "End Time", - "시간은 말레이시아 시간으로 입력합니다.": "Enter times in Malaysia time.", "방송 장소": "Venue", "판매금액 (RM)": "Sales (RM)", + "시간은 말레이시아 시간으로 입력합니다.": "Enter times in Malaysia time.", "판매금액 (RM)": "Sales (RM)", "방송 후 입력": "Enter after the broadcast", + "시간 요금 (RM)": "Fee (RM)", "커미션 (RM)": "Commission (RM)", "광고비 (RM)": "Ad Spend (RM)", "호스트 비용 (RM)": "Host Fee (RM)", + "시간 × RM {rate} — 자동": "Hours × RM {rate} — auto", "판매금액 × {percent}% — 자동": "Sales × {percent}% — auto", "직접 입력": "Enter manually", "방송 결과 이미지 (JPG·PNG·WebP, 한 장 8MB, 방송당 {n}장까지)": "Result images (JPG, PNG, WebP, 8 MB each, up to {n} per broadcast)", "취소": "Cancel", "저장": "Save", "확인": "OK", # 표 "날짜": "Date", "시간": "Time", "판매금액(RM)": "Sales (RM)", "커미션 10%(RM)": "Commission 10% (RM)", "호스트 비용(RM)": "Host Fee (RM)", "방송 결과": "Result", "고치기": "Edit", "지우기": "Delete", - "기본 요금 RM {base} + 커미션 RM {commission}": "Base RM {base} + commission RM {commission}", + "시간 요금(RM)": "Fee (RM)", "광고비(RM)": "Ad Spend (RM)", "{date} {host} 방송을 지울까요? 결과 이미지도 함께 지워집니다.": "Delete the {date} broadcast by {host}? Its result images will be deleted too.", "이 달에 등록한 방송이 없습니다.": "No broadcasts this month.", # 달력 @@ -34,7 +36,7 @@ EN: dict[str, str] = { "팁: 카드 머리를 끌어 옮기거나 맞바꿀 수 있습니다. 오른쪽으로 스크롤하면 이달 {n}일을 모두 볼 수 있습니다.": "Tip: Drag & drop any host header to move or swap dates. Scroll right to see all {n} days of the month.", "{date} {slot} 방송 추가": "Add broadcast on {date} {slot}", "{name} {date} {times} 고치기": "Edit {name} {date} {times}", - "{date} 광고비 고치기": "Edit ad spend for {date}", "방송 결과 이미지": "Result images", "이미지 {n}": "IMG {n}", + "방송 결과 이미지": "Result images", "이미지 {n}": "IMG {n}", # 호스트 설정 "◀ 스케줄표": "◀ Schedule", "+ 호스트 등록": "+ Add Host", "호스트 등록": "Add Host", "호스트 고치기": "Edit Host", "간단한 이름": "Short Name", "이름 (IC 기준)": "Full Name (as per IC)", "전화번호": "Phone Number", "이메일": "Email", "주소": "Address", "은행명": "Bank Name", @@ -53,9 +55,9 @@ EN: dict[str, str] = { "사용으로 바꿨습니다.": "Set to active.", "사용 안 함으로 바꿨습니다.": "Set to inactive.", # 화면 스크립트(live.js) "서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.": "Could not reach the server. Your entries are kept — please try saving again.", - "이 이미지": "this image", "{name} 를 지울까요?": "Delete {name}?", "{day} 광고비 (RM) — 비우면 지웁니다": "{day} ad spend (RM) — leave empty to clear", + "이 이미지": "this image", "{name} 를 지울까요?": "Delete {name}?", # 저장 결과·입력 오류 - "저장했습니다.": "Saved.", "옮겼습니다.": "Moved.", "광고비를 저장했습니다.": "Ad spend saved.", "방송을 지웠습니다.": "Broadcast deleted.", + "저장했습니다.": "Saved.", "옮겼습니다.": "Moved.","방송을 지웠습니다.": "Broadcast deleted.", "이미지를 지웠습니다.": "Image deleted.", "호스트를 저장했습니다.": "Host saved.", "호스트를 지웠습니다.": "Host deleted.", "잘못된 요청입니다.": "Invalid request.", "간단한 이름을 입력하세요.": "Enter the Short Name.", "이름 (IC 기준)을 입력하세요.": "Enter the Full Name (as per IC).", @@ -63,15 +65,15 @@ EN: dict[str, str] = { "이메일 형식이 올바르지 않습니다.": "The email format is invalid.", "전화번호는 숫자·+·-·괄호만 입력하세요.": "Phone Number may contain only digits, +, - and brackets.", "계좌번호는 숫자·-만 입력하세요.": "Bank Account Number may contain only digits and -.", "틱톡 핸들은 영문·숫자·밑줄·점만 입력하세요.": "Tiktok Handle may contain only letters, digits, underscores and dots.", - "판매금액은 숫자로 입력하세요.": "Sales must be a number.", "판매금액은 0 이상 숫자로 입력하세요.": "Sales must be a number of 0 or more.", "판매금액이 너무 큽니다.": "Sales is too large.", + "{label}은(는) 숫자로 입력하세요.": "{label} must be a number.", "{label}은(는) 0 이상 숫자로 입력하세요.": "{label} must be a number of 0 or more.", "{label}이(가) 너무 큽니다.": "{label} is too large.", "{label}을 입력하세요.": "Enter the {label}.", "{label}이 올바르지 않습니다.": "The {label} is invalid.", - "호스트를 고르세요.": "Select a host.", "방송 날짜를 입력하세요.": "Enter the broadcast date.", "방송 장소가 너무 깁니다(200자까지).": "Venue is too long (up to 200 characters).", + "호스트를 고르세요.": "Select a host.", "방송 날짜를 입력하세요.": "Enter the broadcast date.", "끝 시간이 시작 시간과 같습니다.": "End time is the same as start time.", "날짜가 올바르지 않습니다.": "The date is invalid.", "호스트를 찾을 수 없습니다.": "Host not found.", "방송 기록이 있는 호스트는 지울 수 없습니다 — 사용 안 함으로 바꾸세요.": "A host with broadcasts can't be deleted — set the host to Inactive instead.", "방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).": "Broadcast not found (someone may have deleted it).", "방송을 찾을 수 없습니다.": "Broadcast not found.", "사용 안 함으로 바뀐 호스트입니다 — 다른 호스트를 고르세요.": "This host is Inactive — select another host.", "방송 한 건에 이미지는 {max}장까지입니다(지금 {have}장).": "Up to {max} images per broadcast (currently {have}).", "방송 한 건에 이미지는 {max}장까지입니다.": "Up to {max} images per broadcast.", - "DB 마이그레이션 live_db 002(광고비)가 아직 적용되지 않았습니다.": "DB migration live_db 002 (ad spend) has not been applied yet.", "이미지를 찾을 수 없습니다.": "Image not found.", + "이미지를 찾을 수 없습니다.": "Image not found.", "{name}: {detail}": "{name}: {detail}", # 권한·설정 "로그인이 필요합니다.": "Please sign in.", "라이브 커머스 모듈 권한이 없습니다.": "You don't have access to the Live Commerce module.", @@ -87,7 +89,7 @@ EN: dict[str, str] = { # 화면 스크립트에 넘기는 문구(window.LV_T) JS_KEYS = ("확인", "취소", "지우기", "서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.", "이 이미지", "{name} 를 지울까요?", - "{day} 광고비 (RM) — 비우면 지웁니다", "이미지에서 매출을 읽는 중…") + "이미지에서 매출을 읽는 중…") _MONTH_NAMES = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") diff --git a/app/modules/live/router.py b/app/modules/live/router.py index 9d11370..a9d9a1c 100644 --- a/app/modules/live/router.py +++ b/app/modules/live/router.py @@ -110,6 +110,7 @@ def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, An return render_template(request, name, {"user": user, "is_admin": is_admin(user), "can_add_host": _can_add_host(user), "can_edit_host": _can_edit_host(user), "lang": lang, "t": lambda text: i18n.t(text, lang), "js_text": i18n.js_text(lang), + "hourly_rate": store.fmt_short(store.HOURLY_RATE), "commission_percent": store.fmt_short(store.COMMISSION_PERCENT), "nav_items": build_erp_nav(user, active="live"), **ctx}) @@ -159,7 +160,7 @@ def calendar(request: Request, month: str = "") -> Any: st, user = got today, lang = today_kst(), _lang(request) 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) + cal = store.build_calendar(span, st.list_broadcasts(span["start"], span["end"]), today, lang) return _render(request, "live/calendar.html", user, {"view": "calendar", "span": span, "cal": cal, "hosts": st.host_choices(), "accounts": st.account_choices(), "max_images": store.MAX_IMAGES, "my_holidays": holidays.holiday_names(lang), @@ -184,18 +185,6 @@ def broadcast_move(request: Request, broadcast_id: int, broadcast_date: str = Fo return _ok(request, "옮겼습니다.") -@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(request, exc) - return _ok(request, "광고비를 저장했습니다.") - - def _read_images(files: list[UploadFile]) -> list[dict[str, Any]]: """고른 파일을 실제 이미지로 확인·메타데이터 제거(GPS 등). 틀리면 ValueError — 아무것도 저장하지 않게 DB 전에.""" picked = [f for f in files if f.filename] @@ -214,14 +203,15 @@ 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(""), tiktok_handle: str = Form(""), - sales_amount: str = Form(""), images: list[UploadFile] = File(default=[])) -> JSONResponse: + start_time: str = Form(""), end_time: str = Form(""), tiktok_handle: str = Form(""), + sales_amount: str = Form(""), ad_spend: str = Form(""), host_fee: 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, "tiktok_handle": tiktok_handle, "sales_amount": sales_amount}) + values = store.clean_broadcast({"host_id": host_id, "broadcast_date": broadcast_date, "start_time": start_time, "end_time": end_time, + "tiktok_handle": tiktok_handle, "sales_amount": sales_amount, "ad_spend": ad_spend, "host_fee": host_fee}) st.save_broadcast(broadcast_id, values, _read_images(images), by=user.get("email", "")) except ValueError as exc: return _fail(request, exc) diff --git a/app/modules/live/store.py b/app/modules/live/store.py index 00b16c2..df102e6 100644 --- a/app/modules/live/store.py +++ b/app/modules/live/store.py @@ -68,19 +68,19 @@ def clean_host(values: dict[str, Any]) -> dict[str, str]: return out -def parse_money(raw: Any) -> Decimal | None: - """판매금액(RM) — 빈칸은 None(아직 입력 안 함), 0 이상, 소수 둘째 자리까지. 쉼표·RM 허용.""" +def parse_money(raw: Any, label: str = "판매금액") -> 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 LiveError("판매금액은 숫자로 입력하세요.") from None + raise LiveError("{label}은(는) 숫자로 입력하세요.", label=label) from None if not n.is_finite() or n < 0: - raise LiveError("판매금액은 0 이상 숫자로 입력하세요.") + raise LiveError("{label}은(는) 0 이상 숫자로 입력하세요.", label=label) if n > MAX_SALES: - raise LiveError("판매금액이 너무 큽니다.") + raise LiveError("{label}이(가) 너무 큽니다.", label=label) return n.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) @@ -105,9 +105,6 @@ def clean_broadcast(values: dict[str, Any]) -> dict[str, Any]: day = date.fromisoformat(str(values.get("broadcast_date") or "").strip()) except ValueError: raise LiveError("방송 날짜를 입력하세요.") from None - venue = str(values.get("venue") or "").strip() - if len(venue) > 200: - raise LiveError("방송 장소가 너무 깁니다(200자까지).") start = _parse_time(values.get("start_time"), label="시작 시간", required=True) end = _parse_time(values.get("end_time"), label="끝 시간", required=True) if start == end: @@ -117,8 +114,9 @@ def clean_broadcast(values: dict[str, Any]) -> dict[str, Any]: 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, "tiktok_handle": handle, "sales_amount": parse_money(values.get("sales_amount"))} + return {"host_id": int(host), "broadcast_date": day, "start_time": start, "end_time": end, "tiktok_handle": handle, + "sales_amount": parse_money(values.get("sales_amount")), "ad_spend": parse_money(values.get("ad_spend"), "광고비"), + "host_fee": parse_money(values.get("host_fee"), "호스트 비용")} def parse_move(day: Any, start: Any) -> tuple[date, time]: @@ -143,11 +141,12 @@ def _duration(start: time, end: time) -> timedelta: def session_pay(start: time, end: time | None, sales: Decimal | None) -> dict[str, Decimal]: - """호스트 비용 — 기본 요금(시간 × 시간당 요금) + 커미션(판매금액 × %).""" + """참고 금액(저장 안 함) — Fee = 시간 × 시간당 요금, 커미션 = 판매금액 × %. 같은 계산이 방송 창에도(live.js recalc). + 호스트 비용은 2026-11-06 부터 수기 입력(live_broadcasts.host_fee).""" 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} + return {"hours": hours, "base": base, "commission": commission} def fmt_short(n: Decimal) -> str: @@ -161,14 +160,16 @@ def broadcast_view(b: dict[str, Any], lang: str = "ko") -> dict[str, Any]: return { "date": fmt_date(b["broadcast_date"], lang), "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"], + "sales": fmt_money(b["sales_amount"]), "base": fmt_money(pay["base"]), "commission": fmt_money(pay["commission"]), + "ad_spend": fmt_money(b["ad_spend"]), "host_fee": fmt_money(b["host_fee"]), + "images": b["images"], "id": b["id"], "label": 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"]), + "card_fee": fmt_short(b["host_fee"] or Decimal(0)), "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"], "tiktok_handle": b["tiktok_handle"], "sales_amount": f"{b['sales_amount']:.2f}" if b["sales_amount"] is not None else "", + "tiktok_handle": b["tiktok_handle"], + **{k: f"{b[k]:.2f}" if b[k] is not None else "" for k in ("sales_amount", "ad_spend", "host_fee")}, "images": [{"id": i["id"], "filename": i["filename"]} for i in b["images"]]}, } @@ -188,8 +189,9 @@ def _covered_slots(b: dict[str, Any]) -> list[int]: return sorted({_slot_of(h) for h in range(s.hour, max(end, s.hour + 1))}) -def build_calendar(span: dict[str, Any], broadcasts: list[dict[str, Any]], ad_spend: dict[date, Decimal], today: date, lang: str = "ko") -> dict[str, Any]: - """달력 보기 값 — 날짜(열)·SLOT_HOURS 칸(줄)·날짜별 합계·달 합계. 카드는 시작 칸에, 그 칸은 방송이 걸친 칸만큼 아래로 합친다 +def build_calendar(span: dict[str, Any], broadcasts: list[dict[str, Any]], today: date, lang: str = "ko") -> dict[str, Any]: + """달력 보기 값 — 날짜(열)·SLOT_HOURS 칸(줄)·날짜별 합계(판매금액·광고비·호스트 비용 = 그날 방송 값 합, 2026-11-06)·달 합계. + 카드는 시작 칸에, 그 칸은 방송이 걸친 칸만큼 아래로 합친다 (rowspan, 2026-11-06). 합친 칸 안에서 시작하는 다른 방송도 같은 칸에 들어가고 더 길면 칸이 더 늘어난다. 가려진 칸 = {"skip": True}.""" views = [(b, broadcast_view(b, lang)) for b in broadcasts] used = {h for b, _ in views for h in _covered_slots(b)} @@ -197,9 +199,7 @@ def build_calendar(span: dict[str, Any], broadcasts: list[dict[str, Any]], ad_sp 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)) + sales, fee, spend = (sum((b[k] or Decimal(0) for b, _ in mine), Decimal(0)) for k in ("sales_amount", "host_fee", "ad_spend")) days.append({"iso": day.isoformat(), "date": day, "day": day.day, "weekday": _WEEKDAYS[day.weekday()] if lang == "en" else WEEKDAYS_KO[day.weekday()] + "요일", "label": f"{day.day} {_MONTHS[day.month - 1]}" if lang == "en" else f"{day.month}월 {day.day}일", "is_weekend": day.weekday() >= 5, "is_today": day == today, "count": len(mine), "sales": sales, "fee": fee, "spend": spend, diff --git a/app/modules/live/templates/live/_dialog.html b/app/modules/live/templates/live/_dialog.html index 5fec8ff..3086234 100644 --- a/app/modules/live/templates/live/_dialog.html +++ b/app/modules/live/templates/live/_dialog.html @@ -17,8 +17,18 @@

{{ t('시간은 말레이시아 시간으로 입력합니다.') }}

- + {#- Fee·커미션 = 자동 계산(저장 안 함, live.js recalc — store.session_pay 와 같은 계산). 광고비·호스트 비용 = 입력(2026-11-06) -#} +
+ + +
+
+ + +
diff --git a/app/modules/live/templates/live/_scripts.html b/app/modules/live/templates/live/_scripts.html index 95daa39..c1cd6b8 100644 --- a/app/modules/live/templates/live/_scripts.html +++ b/app/modules/live/templates/live/_scripts.html @@ -1,2 +1,2 @@ - + diff --git a/app/modules/live/templates/live/calendar.html b/app/modules/live/templates/live/calendar.html index f8a2d83..c80552b 100644 --- a/app/modules/live/templates/live/calendar.html +++ b/app/modules/live/templates/live/calendar.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {#- 라이브 커머스 달력 보기(2026-11-04) — 줄 = 2시간 칸, 열 = 날짜, 맨 아래 = 날짜별 합계. 카드 머리 = 호스트 간단한 이름 + 그 방송의 틱톡 계정. 카드 머리를 끌어 빈 칸으로 옮기거나 다른 카드 위에 놓아 맞바꾼다(live.js). 문구 = t()(i18n.py), 영문은 CSS 로 대문자(받은 화면과 같게). -#} -{% block head_extra %} +{% block head_extra %} {% endblock %} @@ -69,7 +69,7 @@
{{ t('총 판매금액') }}:
RM {{ d.sales_text }}
-
{{ t('광고비') }}:
RM {{ d.spend_text }}
+
{{ t('광고비') }}:
RM {{ d.spend_text }}
{{ t('호스트 비용') }}:
RM {{ d.fee_text }}
ROAS:
{{ d.roas }}
diff --git a/app/modules/live/templates/live/index.html b/app/modules/live/templates/live/index.html index 83b77e5..46535b5 100644 --- a/app/modules/live/templates/live/index.html +++ b/app/modules/live/templates/live/index.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} {#- 라이브 커머스 스케줄표(2026-11-04) — 달마다 방송 목록. 추가·고치기 창은 달력과 공용(_dialog.html, live.js). 문구 = t()(i18n.py). -#} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
@@ -9,17 +9,18 @@
- + {% for r in rows %} - + - + + {% else %} - + {% endfor %}
{{ t('날짜') }}{{ t('시간') }}{{ t('호스트') }}{{ t('방송 장소') }}{{ t('판매금액(RM)') }}{{ t('커미션 10%(RM)') }}{{ t('호스트 비용(RM)') }}{{ t('방송 결과') }}
{{ t('날짜') }}{{ t('시간') }}{{ t('호스트') }}{{ t('판매금액(RM)') }}{{ t('시간 요금(RM)') }}{{ t('커미션 10%(RM)') }}{{ t('광고비(RM)') }}{{ t('호스트 비용(RM)') }}{{ t('방송 결과') }}
{{ r.date }} {{ r.times }} {{ r.host_name }}{% if r.tiktok_handle %}
@{{ r.tiktok_handle }}
{% endif %}
{{ r.venue }} {{ r.sales }}{{ r.base }} {{ r.commission }}{{ r.fee }}{{ r.ad_spend }}{{ r.host_fee }}
{% for im in r.images %}{{ im.filename }}{% endfor %}
@@ -27,7 +28,7 @@
{{ t('이 달에 등록한 방송이 없습니다.') }}
{{ t('이 달에 등록한 방송이 없습니다.') }}
diff --git a/app/modules/live/templates/live/settings.html b/app/modules/live/templates/live/settings.html index 7f582df..d473cd2 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_host` = 새 등록, `live_host_edit` = 고치기(개인정보는 빈칸으로 열림, 비워 두면 그대로). 추가·고치기는 같은 창(live.js). 문구 = t()(i18n.py). -#} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %} {#- 쇼핑몰(005, store.PLATFORMS) — 로고는 말레이시아 배송 모듈 이미지 -#} diff --git a/app/static/live.css b/app/static/live.css index 6a3dfe8..10a75f6 100644 --- a/app/static/live.css +++ b/app/static/live.css @@ -135,7 +135,7 @@ .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: 9.5px; line-height: 1; cursor: pointer; } +.lv-dlg input[readonly] { background: #f1f5f9; color: #475569; } .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); } diff --git a/app/static/live.js b/app/static/live.js index 2ce7938..92de600 100644 --- a/app/static/live.js +++ b/app/static/live.js @@ -1,5 +1,5 @@ /* 라이브 커머스(2026-11-04) — 스케줄표·달력·호스트 설정 공용: 추가·고치기 창, 저장·지우기(fetch → JSON {ok, message}, 틀려도 입력한 값이 창에 남음). - 달력: 오른쪽 달력으로 날짜 이동, 카드 끌어 옮기기·맞바꾸기, 날짜별 광고비. 다시 그린 뒤에도 보던 가로 위치 유지. */ + 달력: 오른쪽 달력으로 날짜 이동, 카드 끌어 옮기기·맞바꾸기. 다시 그린 뒤에도 보던 가로 위치 유지. */ (function () { "use strict"; const calWrap = document.getElementById("lv-cal-wrap"); @@ -91,9 +91,28 @@ showHosts(editing && row.host_id); if (editing && hostSelect) hostSelect.value = String(row.host_id); // 위에서 보이게 한 뒤 다시 고름 showSaved(editing && row.images); + recalc(); dlg.showModal(); } + // Fee(시간 × 시간당 요금)·커미션(판매금액 × %) 자동 계산 — 보기만(저장 안 함), store.session_pay 와 같게 센트 반올림 + const feeOut = form.querySelector("[data-fee]"); + const comOut = form.querySelector("[data-commission]"); + function money(cents) { return (cents / 100).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 }); } + function minutesOf(v) { const m = /^(\d{1,2}):(\d{2})/.exec(v || ""); return m ? Number(m[1]) * 60 + Number(m[2]) : null; } + function recalc() { + if (!feeOut || !comOut) return; + const s = minutesOf(form.elements.start_time.value), en = minutesOf(form.elements.end_time.value); + const mins = s === null || en === null || s === en ? null : (en - s + 1440) % 1440; // 끝이 더 이르면 자정을 넘긴 방송 + feeOut.value = mins === null ? "" : money(Math.round(mins * Number(feeOut.dataset.fee) * 100 / 60)); + const sales = Number(String(form.elements.sales_amount.value).replace(/^\s*rm/i, "").replace(/[,\s]/g, "")); + const raw = form.elements.sales_amount.value.trim(); + comOut.value = !raw || !isFinite(sales) || sales < 0 ? "" : money(Math.round(Math.round(sales * 100) * Number(comOut.dataset.commission) / 100)); + } + form.addEventListener("input", function (e) { + if (["start_time", "end_time", "sales_amount"].indexOf(e.target.name) >= 0) recalc(); + }); + const addBtn = document.getElementById("lv-add"); if (addBtn) addBtn.addEventListener("click", function () { open(null); }); dlg.addEventListener("click", function (e) { @@ -145,7 +164,7 @@ if (!r.ok || r.data.amount) break; } save.disabled = false; - if (r.ok && r.data.amount) salesInput.value = r.data.amount; + if (r.ok && r.data.amount) { salesInput.value = r.data.amount; recalc(); } say(r.message, r.ok); }); @@ -274,19 +293,6 @@ }); } - // ── 달력: 날짜별 광고비 ── - document.addEventListener("click", async function (e) { - const b = e.target.closest("button[data-spend]"); - if (!b) return; - const value = await window.erpPrompt(tr("{day} 광고비 (RM) — 비우면 지웁니다").replace("{day}", b.dataset.spend), b.dataset.value || "", dialogText()); - 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, dialogText()); - }); - // ── 달력: 카드 머리를 끌어 빈 칸으로 옮기기, 다른 카드 위에 놓아 맞바꾸기 ── let dragging = null; calWrap.addEventListener("dragstart", function (e) { diff --git a/docs/DATABASES.md b/docs/DATABASES.md index 8271501..cd1eb06 100644 --- a/docs/DATABASES.md +++ b/docs/DATABASES.md @@ -313,9 +313,9 @@ DDL: `scripts/sql/live_db_init.sql` (멱등). DB·역할(`live_app`)·테이블 | 테이블 | 용도 | | --- | --- | | `live_hosts` | 호스트 — `platform`(쇼핑몰 `tiktok`·`shopee`, `''` = 예전 호스트, 마이그레이션 `live_db_005_host_platform.sql`)·`display_name`(간단한 이름, 마이그레이션 `live_db_004_host_display_name.sql`)·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_broadcasts` | 방송 스케줄 — `host_id`(FK RESTRICT)·`broadcast_date`·`start_time`·`end_time`(말레이시아 시간 그대로)·`venue`(2026-11-06 부터 입력 안 받음, 예전 값만)·`tiktok_handle`(그 방송의 계정, @ 없이, 마이그레이션 `live_db_003_broadcast_account.sql`)·`sales_amount`(RM, NULL = 미입력)·`ad_spend`(방송별 광고비)·`host_fee`(호스트 비용, 수기 입력) — 둘 다 RM·NULL = 미입력, 마이그레이션 `live_db_006_broadcast_fees.sql` | | `live_broadcast_images` | 방송 결과 이미지(메타데이터 제거 후 BYTEA, 방송을 지우면 CASCADE) — 방송당 최대 10장(앱에서 확인) | -| `live_daily_ad_spend` | 날짜별 광고비(RM) — 달력 보기 AD SPEND·ROAS. 마이그레이션 `live_db_002_ad_spend.sql`(init 에도 포함) | +| `live_daily_ad_spend` | 날짜별 광고비(RM) — 마이그레이션 `live_db_002_ad_spend.sql`(init 에도 포함). **006 부터 안 씀**(달력 AD SPEND = 그날 방송 `ad_spend` 합), 값만 남김 | ## malaysia_stock_db 스키마 / 초기화 diff --git a/scripts/sql/live_db_006_broadcast_fees.sql b/scripts/sql/live_db_006_broadcast_fees.sql new file mode 100644 index 0000000..aceebda --- /dev/null +++ b/scripts/sql/live_db_006_broadcast_fees.sql @@ -0,0 +1,21 @@ +-- ===================================================================== +-- live_db 마이그레이션 006 — 방송별 광고비·호스트 비용(2026-11-06) +-- ===================================================================== +-- 왜: 방송 창에서 Ad Spend(방송별 광고비)와 Host fee(호스트 비용, 수기 입력)를 받는다. +-- 달력 날짜별 광고비 = 그날 방송 Ad Spend 합계(live_daily_ad_spend 는 더 안 씀 — 값은 남김). +-- Fee(시간 × RM25)·Commission(판매금액 × 10%)은 저장 안 함(화면에서 계산). +-- 멱등(idempotent). 열 두 개만 추가(기존 값 변경 없음). 예전 방송은 NULL(= 0 으로 보임). +-- 운영: /opt/www/main 에서 기존 live_db 에 앱 배포 전에 적용(백업 먼저, 005 다음). +-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d live_db < scripts/sql/live_db_006_broadcast_fees.sql +-- 되돌리기: ALTER TABLE live_broadcasts DROP COLUMN ad_spend, DROP COLUMN host_fee; (입력한 값만 사라짐 — 실행 전 백업) +-- ===================================================================== +\set ON_ERROR_STOP on +BEGIN; + +ALTER TABLE live_broadcasts ADD COLUMN IF NOT EXISTS ad_spend NUMERIC(14,2) CHECK (ad_spend IS NULL OR ad_spend >= 0); +ALTER TABLE live_broadcasts ADD COLUMN IF NOT EXISTS host_fee NUMERIC(14,2) CHECK (host_fee IS NULL OR host_fee >= 0); +COMMENT ON COLUMN live_broadcasts.ad_spend IS '방송별 광고비(RM) — NULL = 입력 안 함'; +COMMENT ON COLUMN live_broadcasts.host_fee IS '호스트 비용(RM, 수기 입력) — NULL = 입력 안 함'; + +COMMIT; +SELECT 'live_db 006 broadcast fees ready' AS status, count(*) AS broadcasts FROM live_broadcasts; diff --git a/scripts/sql/live_db_init.sql b/scripts/sql/live_db_init.sql index efd8e44..353e938 100644 --- a/scripts/sql/live_db_init.sql +++ b/scripts/sql/live_db_init.sql @@ -78,7 +78,9 @@ CREATE TABLE IF NOT EXISTS live_broadcasts ( 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 '', + ad_spend NUMERIC(14,2) CHECK (ad_spend IS NULL OR ad_spend >= 0), -- 방송별 광고비, 마이그레이션 006 + host_fee NUMERIC(14,2) CHECK (host_fee IS NULL OR host_fee >= 0), -- 호스트 비용(수기 입력), 마이그레이션 006 + 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() @@ -108,7 +110,7 @@ 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) +-- 3-1) 날짜별 광고비 — 마이그레이션 002 와 같음. 006 부터 안 씀(방송별 live_broadcasts.ad_spend 합계로 바뀜, 값은 남김) -- ════════════════════════════════════════════════════════════ CREATE TABLE IF NOT EXISTS live_daily_ad_spend ( ad_date DATE PRIMARY KEY, diff --git a/tests/js/live_calendar.browser.test.js b/tests/js/live_calendar.browser.test.js index c6fab9f..0ecd068 100644 --- a/tests/js/live_calendar.browser.test.js +++ b/tests/js/live_calendar.browser.test.js @@ -204,6 +204,16 @@ function check(name, cond, extra) { await p.locator("#lv-dlg [data-close]").click(); await p.locator(".lv-card-edit").first().click(); check("고치기 창 애니메이션", (await anim()) === "lv-dlg-in|0.2s", await anim()); + // Fee(시간 × 25)·커미션(판매금액 10%) 자동, 광고비·호스트 비용 = 저장한 값, 방송 장소 없음(2026-11-06) + const fees = function () { return p.locator("#lv-dlg").evaluate(function (d) { + const q = function (s) { return d.querySelector(s).value; }; + return [q("[data-fee]"), q("[data-commission]"), q('[name="ad_spend"]'), q('[name="host_fee"]'), !!d.querySelector('[name="venue"]')].join("|"); + }); }; + check("고치기 창 금액", (await fees()) === "50.00|50.00|100.00|50.00|false", await fees()); + await p.locator('#lv-dlg [name="sales_amount"]').fill("RM 1,234.5"); + await p.locator('#lv-dlg [name="end_time"]').fill("08:30"); + check("판매금액·끝 시간 바꾸면 다시 계산", (await fees()) === "62.50|123.45|100.00|50.00|false", await fees()); + await p.screenshot({ path: path.join(__dirname, ".out", "live_dialog_fees.png") }); await p.locator("#lv-dlg [data-close]").click(); await p.emulateMedia({ reducedMotion: "reduce" }); await p.locator("#lv-add").click(); diff --git a/tests/js/render_live.py b/tests/js/render_live.py index b3fa9b8..12255a9 100644 --- a/tests/js/render_live.py +++ b/tests/js/render_live.py @@ -36,13 +36,10 @@ class Fake: return [] # 운영 화면처럼 — 6·8·16시 칸에 카드(세 줄 모두 카드가 있으면 그 줄이 가장 높다), 모든 시간 칸을 채워 높이 최악으로 return [{"id": h, "host_id": 1, "host_name": "Nabella", "tiktok_handle": "MainAccount", "broadcast_date": date(2026, 11, 5), "start_time": time(h), - "end_time": time(h + 2), "venue": "", "sales_amount": Decimal("500"), + "end_time": time(h + 2), "venue": "", "sales_amount": Decimal("500"), "ad_spend": Decimal("100"), "host_fee": Decimal("50"), "images": [{"id": 7, "filename": "r.png"}, {"id": 8, "filename": "s.png"}] if h == 6 else []} for h in range(6, 24, 2) if h < 22] + \ [{"id": 22, "host_id": 1, "host_name": "Nabella", "tiktok_handle": "MainAccount", "broadcast_date": date(2026, 11, 5), "start_time": time(22), - "end_time": time(23, 30), "venue": "", "sales_amount": Decimal("500"), "images": []}] - - def ad_spends(self, start, end): - return {} + "end_time": time(23, 30), "venue": "", "sales_amount": Decimal("500"), "ad_spend": None, "host_fee": None, "images": []}] def broadcast_days(self, start, end): return ["2026-10-30", "2026-11-05", "2026-11-20", "2026-12-03"] # 오른쪽 달력 점 — 다른 달 날짜도 diff --git a/tests/test_live.py b/tests/test_live.py index a4711b6..de2dd5d 100644 --- a/tests/test_live.py +++ b/tests/test_live.py @@ -82,7 +82,10 @@ class StoreTests(unittest.TestCase): 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": []}) + "start_time": time(20, 0), "end_time": time(22, 0), "venue": "", "sales_amount": None, "ad_spend": None, + "host_fee": Decimal("40"), "images": []}) + self.assertEqual((view["edit"]["sales_amount"], view["edit"]["ad_spend"], view["edit"]["host_fee"], view["base"]), ("", "", "40.00", "50.00")) + self.assertNotIn("venue", view["edit"]) # 방송 장소는 창에서 뺌(2026-11-06) self.assertEqual((view["tiktok_handle"], view["edit"]["tiktok_handle"], view["label"]), ("alt.acc", "alt.acc", "Yaya")) # 카드 머리 = 호스트, 계정은 아래 def test_my_holidays(self): @@ -111,15 +114,19 @@ class StoreTests(unittest.TestCase): for bad in ("-1", "abc", "NaN", "Infinity", "1e20"): with self.assertRaises(ValueError, msg=bad): store.parse_money(bad) + with self.assertRaises(store.LiveError) as err: + store.parse_money("x", "호스트 비용") + self.assertEqual(err.exception.text("en"), "Host Fee must be a number.") def test_clean_broadcast(self): 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"}) + "venue": " Studio ", "sales_amount": "100", "ad_spend": "RM 20", "host_fee": ""}) self.assertEqual(got, {"host_id": 3, "broadcast_date": date(2026, 11, 4), "start_time": time(20, 0), "end_time": time(22, 0), - "venue": "Studio", "tiktok_handle": "", "sales_amount": Decimal("100.00")}) + "tiktok_handle": "", "sales_amount": Decimal("100.00"), "ad_spend": Decimal("20.00"), "host_fee": None}) 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"}): + {"start_time": "25:00"}, {"end_time": ""}, {"end_time": "nope"}, {"end_time": "20:00"}, {"sales_amount": "-5"}, + {"ad_spend": "-1"}, {"host_fee": "abc"}): with self.assertRaises(ValueError, msg=over): store.clean_broadcast({**good, **over}) @@ -143,12 +150,12 @@ class StoreTests(unittest.TestCase): self.assertEqual(store.fmt_money(None), "") def test_session_pay(self): - """호스트 비용 = 시간 × RM 25 + 판매금액 10%. 받은 화면의 예: 2시간·판매 48 → 50 + 4.8.""" + """Fee = 시간 × 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((p["base"], p["commission"]), (Decimal("50.00"), Decimal("4.80"))) + self.assertEqual(store.session_pay(time(22, 0), time(0, 0), None)["base"], 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), None, Decimal("10"))["base"], Decimal("0.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")) @@ -162,15 +169,15 @@ class StoreTests(unittest.TestCase): store.parse_move(*bad) def test_build_calendar(self): - def b(id, day, start, end, sales=None, host=1, handle="yaya"): + def b(id, day, start, end, sales=None, host=1, handle="yaya", ad=None, fee=None): 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": []} + "end_time": end, "venue": "", "sales_amount": sales, "ad_spend": ad, "host_fee": fee, "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=""), + cal = store.build_calendar(span, [b(1, date(2026, 11, 4), time(12, 0), time(14, 0), Decimal("48"), ad=Decimal("20"), fee=Decimal("54.8")), + b(2, date(2026, 11, 4), time(22, 0), time(0, 0), handle="", ad=Decimal("4"), fee=Decimal("50")), b(3, date(2026, 11, 7), time(13, 30), time(15, 0))], - {date(2026, 11, 4): Decimal("24")}, date(2026, 11, 4), "en") - ko = store.build_calendar(span, [], {}, date(2026, 11, 4)) + date(2026, 11, 4), "en") + ko = store.build_calendar(span, [], date(2026, 11, 4)) self.assertEqual((ko["days"][3]["weekday"], ko["days"][3]["label"], ko["slot_note"]), ("수요일", "11월 4일", "1시간 (기본 RM25)")) self.assertEqual(len(cal["days"]), 30) self.assertEqual([s["label"] for s in cal["slots"]][0], "06:00 - 07:00") @@ -191,7 +198,7 @@ class StoreTests(unittest.TestCase): self.assertEqual(next(s for s in cal["slots"] if s["start"] == "13:00")["cells"][6]["cards"][0]["id"], 3) # 13:30 = 13~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)) + early = store.build_calendar(span, [b(9, date(2026, 11, 1), time(3, 0), time(5, 0))], date(2026, 11, 4)) self.assertEqual([s["label"] for s in early["slots"]][:3], ["03:00 - 04:00", "04:00 - 05:00", "06:00 - 07:00"]) # 걸친 칸은 늘 있음 self.assertEqual(len(early["slots"]), 20) @@ -205,7 +212,7 @@ class StoreTests(unittest.TestCase): self.assertEqual(sum(1 for s in cal["slots"] if s["cells"][3].get("skip")), 2) m = store.build_calendar(span, [b(5, date(2026, 11, 2), time(6, 0), time(8, 0)), b(6, date(2026, 11, 2), time(7, 0), time(10, 0)), b(7, date(2026, 11, 2), time(23, 0), time(1, 0)), b(8, date(2026, 11, 2), time(20, 0), time(20, 30))], - {}, date(2026, 11, 4)) + date(2026, 11, 4)) self.assertEqual(col(m, 1)[0], ("06:00", 4, [5, 6])) # 6~8 + 7~10 = 6·7·8·9 self.assertEqual(col(m, 1)[1][0], "10:00") self.assertIn(("20:00", 1, [8]), col(m, 1)) # 30분 = 한 칸 @@ -449,8 +456,6 @@ class Fake: return [] def list_broadcasts(self, start, end): return [] - def ad_spends(self, start, end): - return {} def broadcast_days(self, start, end): assert (start.isoformat(), end.isoformat()) == ("2025-10-31", "2027-12-02"), (start, end) # 보는 달 ±1년 return ["2026-11-05"] @@ -577,18 +582,19 @@ def body(c): page = c.get("/live/?month=2031-03").text assert 'value="%d"' % hid 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", "tiktok_handle": "@siti.%s" % tag, "sales_amount": "1,234.5"} + show = {"host_id": hid, "broadcast_date": "2031-03-05", "start_time": "20:00", "end_time": "22:30", "tiktok_handle": "@siti.%s" % tag, "sales_amount": "1,234.5", + "ad_spend": "30", "host_fee": "77.7"} 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 # 이미지가 틀리면 방송도 저장 안 됨 + assert "1,234.50" 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 ">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 + assert "2031.03.05(수)" in page and "20:00 ~ 22:30" in page and "1,234.50" in page and 'name="venue"' not in page + assert ">62.50" in page and ">123.45" in page and ">30.00" in page and ">77.70" in page # Fee 2.5시간 × 25·커미션 10%·광고비·호스트 비용(수기) + assert "1,234.50" 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] @@ -607,10 +613,10 @@ def body(c): who["u"] = staff # ── 고치기: 값 바뀜, 이미지 유지 + 더하기, 판매금액 지우기, 10장 제한 ── - r = c.post("/live/broadcasts", data={**show, "id": bid, "venue": "PJ Studio", "sales_amount": "", "end_time": "21:00"}) + r = c.post("/live/broadcasts", data={**show, "id": bid, "host_fee": "", "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 ~ 21:00" in page + assert ">77.70" not in page and "1,234.50" not in page and "20:00 ~ 21:00" in page and ">25.00" in page assert c.post("/live/broadcasts", data={**show, "end_time": ""}).status_code == 400 # 끝 시간 필수 # ── 달력: 카드 머리 = Tiktok Handle, Fee, 옮기기(길이 유지)·맞바꾸기, 광고비·ROAS, 권한 ── @@ -618,7 +624,8 @@ def body(c): cal = c.get("/live/calendar?month=2031-03").text assert "날짜로 이동" not in cal and "토요일" in cal and "12:00 - 13:00" in cal and "1시간 (기본 RM25)" in cal assert '"2031-03-05"' in cal.split('id="lv-live-days">')[1].split("")[0] # 오른쪽 달력 점 - assert 'S%s@siti.%s' % (tag, tag) in cal and "RM54.80" in cal and ">4.80" in cal + assert 'S%s@siti.%s' % (tag, tag) in cal and "RM77.70" in cal and ">4.80" in cal # 카드 Fee = 호스트 비용(수기) + assert 'data-spend=' not in cal and "
RM 30
" in cal # 날짜 광고비 = 방송 Ad Spend 합 # ── 영문: 화면 세 개 모두 한글 없음(입력한 데이터 제외)·날짜·오류·권한 문구 ── def no_korean(url): @@ -632,15 +639,14 @@ def body(c): page = no_korean("/live/?month=2031-03") assert 'lang="en"' in page and "March 2031" in page and "2031.03.05 (Wed)" in page and "Commission 10% (RM)" in page cal = no_korean("/live/calendar?month=2031-03") - assert "SATURDAY" in cal and "1 MAR" in cal and "1 Hour (RM25 Base)" in cal and ">Sales<" in cal and "Com (10%)" in cal and "Fee: RM54.80" in cal + assert "SATURDAY" in cal and "1 MAR" in cal and "1 Hour (RM25 Base)" in cal and ">Sales<" in cal and "Com (10%)" in cal and "Fee: RM77.70" in cal assert "Total Sales:" in cal and "Ad Spend:" in cal and "Host Fee:" in cal and "Total & ROAS" in cal assert c.post("/live/broadcasts", data={**show, "id": bid, "sales_amount": "abc"}).json()["message"] == "Sales must be a number." + assert c.post("/live/broadcasts", data={**show, "id": bid, "ad_spend": "-1"}).json()["message"] == "Ad Spend must be a number of 0 or more." assert c.post("/live/broadcasts", data={**show, "id": bid, "end_time": ""}).json()["message"] == "Enter the End Time." junk = c.post("/live/broadcasts", data=show, files=[("images", ("x.jpg", b"not an image", "image/jpeg"))]).json()["message"] assert junk == "x.jpg: The image can't be read. Please choose a valid JPG, PNG or WebP file.", junk assert c.post("/live/settings/hosts", data=host).json()["detail"] == "Only ERP admins can view host information." - assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "1"}).json()["message"] == "Ad spend saved." - assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": ""}).json()["ok"] who["u"] = admin page = no_korean("/live/settings") for field in ("Full Name (as per IC)", "Phone Number", "Email", "Address", "Bank Name", "Bank Account Number", "Platform"): @@ -658,28 +664,23 @@ def body(c): 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") + c.post("/live/broadcasts", data={**show, "broadcast_date": "2031-03-09", "start_time": "08:00", "end_time": "09:00"}) + other = next(b["id"] for b in st.list_broadcasts(day(2031, 3, 9), day(2031, 3, 10)) if b["id"] != bid) 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", data={**show, "id": bid, "sales_amount": "48", "ad_spend": "12", "broadcast_date": "2031-03-09", + "start_time": "08:00", "end_time": "09:00"}).json()["ok"] + cal = c.get("/live/calendar?month=2031-03").text + assert "
RM 12
" in cal and "
4.00
" in cal and "RM 42" in cal # 날짜 광고비 = 방송 합, ROAS 48 ÷ 12, 달 합 12 + 30 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)