feat(라이브): 방송 창에 Fee·커미션 자동 계산, 광고비·호스트 비용 입력, 방송 장소 뺌

- Fee = 시간 x RM25, 커미션 = 판매금액 x 10% (저장 안 함, 이미지에서 매출을 읽으면 다시 계산)
- 광고비·호스트 비용(수기) = 방송마다 저장 (마이그레이션 live_db_006_broadcast_fees.sql)
- 달력 날짜 광고비 = 그날 방송 광고비 합, 호스트 비용 = host_fee 합 (날짜별 광고비 입력 버튼·/live/ad-spend 없앰)
- 방송 장소는 창·표에서 뺌 (예전 값은 DB 에 그대로)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-06 15:16:32 +09:00
parent 3b44cf2985
commit ecc76ae4d8
18 changed files with 176 additions and 156 deletions
+10
View File
@@ -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();
+2 -5
View File
@@ -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"] # 오른쪽 달력 점 — 다른 달 날짜도
+41 -40
View File
@@ -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</td>" in page and ">185.95</td>" 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</td>" in page and ">123.45</td>" in page and ">30.00</td>" in page and ">77.70</td>" 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</td>" not in page and "1,234.50" not in page and "20:00 ~ 21:00" in page and ">25.00</td>" 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("</script>")[0] # 오른쪽 달력 점
assert '<span class="lv-card-name">S%s<small>@siti.%s</small></span>' % (tag, tag) in cal and "RM54.80" in cal and ">4.80</b>" in cal
assert '<span class="lv-card-name">S%s<small>@siti.%s</small></span>' % (tag, tag) in cal and "RM77.70" in cal and ">4.80</b>" in cal # 카드 Fee = 호스트 비용(수기)
assert 'data-spend=' not in cal and "<dd>RM 30</dd>" 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: <b>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: <b>RM77.70" in cal
assert "Total Sales:" in cal and "Ad Spend:" in cal and "Host Fee:" in cal and "Total &amp; 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 "<dd>RM 12</dd>" in cal and "<dd>4.00</dd>" in cal and "<b>RM 42</b>" 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)