feat(라이브커머스): 라이브 커머스 모듈 추가
말레이시아 라이브 방송의 호스트 정보와 방송 스케줄을 관리하는 새 모듈. 호스트 설정(이름·연락처·주소·계좌·틱톡)은 ERP 관리자만 다루고, 스케줄표에서 등록된 호스트를 골라 날짜·시간·장소·판매금액(RM)·결과 이미지를 저장한다. 권한키 live, DB live_db(LIVE_DB_URL), 미설정이면 설정 필요 안내만 표시한다. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,254 @@
|
||||
"""라이브 커머스(live, 2026-11-04).
|
||||
|
||||
1) store — 호스트·방송 입력 검사, 판매금액, 달 범위, 표시 형식, 작은 그림.
|
||||
2) 실제 앱(격리된 하위 프로세스) — 메뉴·권한 칩·"설정 필요" 안내(DB 없이 늘 실행).
|
||||
3) 전체 흐름(LIVE_TEST_DB_URL 이 localhost 일 때만) — 호스트 등록·권한·스케줄·이미지·지우기.
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import date, time
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from app.modules.live import store # noqa: E402
|
||||
|
||||
DSN = os.getenv("LIVE_TEST_DB_URL", "")
|
||||
DB_ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
|
||||
|
||||
PRELUDE = '''
|
||||
from unittest.mock import patch
|
||||
from fastapi.testclient import TestClient
|
||||
import app.main as main
|
||||
|
||||
def U(email, role="user", live=True):
|
||||
return {"email": email, "name": email.split("@")[0], "role": role, "is_super_admin": False, "modules": {"live": live}}
|
||||
|
||||
who = {"u": None}
|
||||
|
||||
def run(body):
|
||||
with patch.object(main, "get_current_user_record", side_effect=lambda r: who["u"]), \\
|
||||
patch.object(main, "get_session_user", side_effect=lambda r: who["u"]), \\
|
||||
patch.object(main.user_store, "get", side_effect=lambda e: who["u"]), \\
|
||||
patch.object(main.user_store, "list_all", side_effect=lambda: [who["u"]]):
|
||||
body(TestClient(main.app))
|
||||
'''
|
||||
|
||||
|
||||
def _run(code: str, extra_env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
|
||||
env = dict(os.environ)
|
||||
for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE", "MALAYSIA_STOCK",
|
||||
"ITEMCODE", "EXPENSE", "INOUT", "OUTREACH", "LIVE"):
|
||||
env[key + "_DB_URL"] = ""
|
||||
env.update(SESSION_SECRET_KEY="local-live-test-only", SESSION_COOKIE_SECURE="false", PERFORMANCE_AUTO_SYNC="false")
|
||||
env.update(extra_env or {})
|
||||
with tempfile.TemporaryDirectory(prefix="live-web-") as directory:
|
||||
env["DATA_DIR"] = directory
|
||||
return subprocess.run([sys.executable, "-c", PRELUDE + code], cwd=ROOT, env=env, capture_output=True,
|
||||
text=True, encoding="utf-8", timeout=90)
|
||||
|
||||
|
||||
class StoreTests(unittest.TestCase):
|
||||
def test_clean_host(self):
|
||||
got = store.clean_host({"full_name": " Siti Aisyah ", "phone": "+60 12-345 6789", "email": "siti@example.my", "address": "KL",
|
||||
"bank_name": "Maybank", "bank_account": "1234-5678", "tiktok_handle": "@siti.live"})
|
||||
self.assertEqual((got["full_name"], got["tiktok_handle"]), ("Siti Aisyah", "siti.live"))
|
||||
self.assertEqual(store.clean_host({"full_name": "A"})["phone"], "") # Full Name 만 필수
|
||||
for bad in ({}, {"full_name": " "}, {"full_name": "A", "email": "nope"}, {"full_name": "A", "phone": "abc"},
|
||||
{"full_name": "A", "bank_account": "12a"}, {"full_name": "A", "tiktok_handle": "한글"},
|
||||
{"full_name": "x" * 201}):
|
||||
with self.assertRaises(ValueError, msg=bad):
|
||||
store.clean_host(bad)
|
||||
|
||||
def test_clean_handle(self):
|
||||
for raw in ("@siti.live", "siti.live", "https://www.tiktok.com/@siti.live?lang=en", "tiktok.com/@siti.live/video/1"):
|
||||
self.assertEqual(store.clean_handle(raw), "siti.live", raw)
|
||||
|
||||
def test_parse_money(self):
|
||||
self.assertIsNone(store.parse_money(""))
|
||||
self.assertEqual(store.parse_money("RM 1,234.5"), Decimal("1234.50"))
|
||||
self.assertEqual(store.parse_money("0"), Decimal("0.00"))
|
||||
for bad in ("-1", "abc", "NaN", "Infinity", "1e20"):
|
||||
with self.assertRaises(ValueError, msg=bad):
|
||||
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": "",
|
||||
"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,
|
||||
"venue": "Studio", "sales_amount": Decimal("100.00")})
|
||||
good = {"host_id": "3", "broadcast_date": "2026-11-04", "start_time": "20: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"}):
|
||||
with self.assertRaises(ValueError, msg=over):
|
||||
store.clean_broadcast({**good, **over})
|
||||
|
||||
def test_month_range(self):
|
||||
today = date(2026, 11, 4)
|
||||
self.assertEqual(store.month_range("", today)["label"], "2026년 11월")
|
||||
self.assertEqual(store.month_range("bad", today)["start"], date(2026, 11, 1))
|
||||
self.assertEqual(store.month_range("2026-13", today)["start"], date(2026, 11, 1))
|
||||
dec = store.month_range("2026-12", today)
|
||||
self.assertEqual((dec["start"], dec["end"], dec["prev"], dec["next"]), (date(2026, 12, 1), date(2027, 1, 1), "2026-11", "2027-01"))
|
||||
jan = store.month_range("2027-01", today)
|
||||
self.assertEqual((jan["end"], jan["prev"], jan["next"]), (date(2027, 2, 1), "2026-12", "2027-02"))
|
||||
|
||||
def test_format(self):
|
||||
self.assertEqual(store.fmt_date(date(2026, 11, 4)), "2026.11.04(수)")
|
||||
self.assertEqual(store.fmt_times(time(20, 0), time(22, 30)), "20:00 ~ 22:30")
|
||||
self.assertEqual(store.fmt_times(time(20, 0), None), "20:00")
|
||||
self.assertEqual(store.fmt_money(Decimal("1234.5")), "1,234.50")
|
||||
self.assertEqual(store.fmt_money(None), "")
|
||||
|
||||
def test_thumbnail(self):
|
||||
for mode, fmt in (("RGB", "JPEG"), ("RGBA", "PNG")):
|
||||
raw = io.BytesIO()
|
||||
Image.new(mode, (800, 400)).save(raw, format=fmt)
|
||||
with Image.open(io.BytesIO(store.thumbnail(raw.getvalue()))) as im:
|
||||
self.assertEqual((im.format, im.size), ("JPEG", (160, 80)))
|
||||
|
||||
|
||||
class WebTests(unittest.TestCase):
|
||||
def test_registered_and_unconfigured(self):
|
||||
res = _run('''
|
||||
from app.store import MODULE_KEYS
|
||||
assert "live" in MODULE_KEYS and main.MODULE_LABELS["live"] == "라이브 커머스"
|
||||
|
||||
def body(c):
|
||||
who["u"] = U("a@test.local", role="admin")
|
||||
assert c.get("/live/health").json() == {"status": "not_configured"}
|
||||
r = c.get("/live/")
|
||||
assert r.status_code == 503 and "LIVE_DB_URL" in r.text and "라이브 커머스" in r.text, r.status_code
|
||||
assert c.post("/live/broadcasts", data={}).status_code == 503
|
||||
who["u"] = U("b@test.local", live=False)
|
||||
assert c.get("/live/").status_code == 403
|
||||
assert c.post("/live/broadcasts", data={}).status_code == 403
|
||||
assert c.get("/live/images/1").status_code == 403
|
||||
print("OK")
|
||||
run(body)
|
||||
''')
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
@unittest.skipUnless(DB_ENABLED, "LIVE_TEST_DB_URL(localhost) not set")
|
||||
def test_full_flow(self):
|
||||
res = _run('''
|
||||
import io, re, uuid
|
||||
from PIL import Image
|
||||
from app.modules.live.db import LiveDBStore
|
||||
st = LiveDBStore(__import__("os").environ["LIVE_TEST_DB_URL"])
|
||||
main.app.state.live_store = st
|
||||
tag = uuid.uuid4().hex[:8]
|
||||
admin, staff, outsider = U("admin-%s@t.local" % tag, role="admin"), U("staff-%s@t.local" % tag), U("out-%s@t.local" % tag, live=False)
|
||||
ACCOUNT = "9988%s" % int(tag, 16)
|
||||
NAME = "Siti <b>" + tag
|
||||
|
||||
def jpeg():
|
||||
raw = io.BytesIO()
|
||||
exif = Image.Exif(); exif[0x010F] = "SECRET-CAMERA"
|
||||
Image.new("RGB", (3000, 1500), "red").save(raw, format="JPEG", exif=exif)
|
||||
return raw.getvalue()
|
||||
|
||||
def body(c):
|
||||
host = {"full_name": NAME, "phone": "+60 12-345", "email": "siti@example.my", "address": "Kuala Lumpur",
|
||||
"bank_name": "Maybank", "bank_account": ACCOUNT, "tiktok_handle": "@siti.%s" % tag, "is_active": "1"}
|
||||
# ── 호스트 설정 = ERP 관리자만 ──
|
||||
who["u"] = staff
|
||||
assert c.get("/live/settings").status_code == 403
|
||||
assert c.post("/live/settings/hosts", data=host).status_code == 403
|
||||
assert c.post("/live/settings/hosts/1/delete").status_code == 403
|
||||
assert 'href="/live/settings"' not in c.get("/live/").text
|
||||
who["u"] = admin
|
||||
bad = c.post("/live/settings/hosts", data={**host, "email": "nope"})
|
||||
assert bad.status_code == 400 and "Email" in bad.json()["message"]
|
||||
r = c.post("/live/settings/hosts", data=host)
|
||||
assert r.json()["ok"], r.text
|
||||
hid = next(h["id"] for h in st.list_hosts() if h["full_name"] == NAME)
|
||||
page = c.get("/live/settings").text
|
||||
for field in ("Full Name (as per IC)", "Phone Number", "Email", "Address", "Bank Name", "Bank Account Number", "Tiktok Handle"):
|
||||
assert field in page, field
|
||||
assert ACCOUNT in page and "Siti <b>" in page and "<b>" + tag not in page
|
||||
assert st.list_hosts() and next(h for h in st.list_hosts() if h["id"] == hid)["tiktok_handle"] == "siti." + tag
|
||||
|
||||
# ── 스케줄: 일반 권한자도 추가·고치기, 화면에 계좌·주소 없음 ──
|
||||
who["u"] = staff
|
||||
page = c.get("/live/?month=2031-03").text
|
||||
assert 'value="%d"' % hid in page and "@siti." + tag 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", "sales_amount": "1,234.5"}
|
||||
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 # 이미지가 틀리면 방송도 저장 안 됨
|
||||
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 "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)
|
||||
bid, img = row["id"], row["images"][0]
|
||||
assert img["filename"] == "evil.jpg" and len(row["images"]) == 1 # 파일 이름의 경로 제거
|
||||
|
||||
# ── 이미지: 크기 줄임·EXIF 제거·권한 ──
|
||||
r = c.get("/live/images/%d" % img["id"])
|
||||
assert r.status_code == 200 and r.headers["content-type"] == "image/jpeg" and "private" in r.headers["cache-control"]
|
||||
assert b"SECRET-CAMERA" not in r.content
|
||||
assert Image.open(io.BytesIO(r.content)).size == (2400, 1200)
|
||||
assert Image.open(io.BytesIO(c.get("/live/images/%d?thumb=1" % img["id"]).content)).size == (160, 80)
|
||||
assert c.get("/live/images/99999999").status_code == 404
|
||||
who["u"] = outsider
|
||||
assert c.get("/live/images/%d" % img["id"]).status_code == 403
|
||||
assert c.post("/live/images/%d/delete" % img["id"]).status_code == 403
|
||||
who["u"] = staff
|
||||
|
||||
# ── 고치기: 값 바뀜, 이미지 유지 + 더하기, 판매금액 지우기, 10장 제한 ──
|
||||
r = c.post("/live/broadcasts", data={**show, "id": bid, "venue": "PJ Studio", "sales_amount": "", "end_time": ""})
|
||||
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
|
||||
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장
|
||||
assert c.post("/live/broadcasts", data={**show, "id": 99999999}).status_code == 400
|
||||
assert c.post("/live/broadcasts", data={**show, "id": "x"}).status_code == 400
|
||||
|
||||
# ── 호스트: 방송이 있으면 못 지움, 사용 안 함이면 새 방송 불가·기존 방송 고치기는 가능 ──
|
||||
who["u"] = admin
|
||||
r = c.post("/live/settings/hosts/%d/delete" % hid)
|
||||
assert r.status_code == 400 and "사용 안 함" in r.json()["message"]
|
||||
assert c.post("/live/settings/hosts", data={**host, "id": hid, "is_active": ""}).json()["ok"]
|
||||
who["u"] = staff
|
||||
assert 'data-inactive="1"' in c.get("/live/?month=2031-03").text
|
||||
r = c.post("/live/broadcasts", data=show)
|
||||
assert r.status_code == 400 and "사용 안 함" in r.json()["message"]
|
||||
assert c.post("/live/broadcasts", data={**show, "id": bid}).json()["ok"]
|
||||
|
||||
# ── 지우기: 이미지 하나, 방송(이미지도), 그 뒤 호스트 ──
|
||||
assert c.post("/live/images/%d/delete" % img["id"]).json()["ok"]
|
||||
assert c.get("/live/images/%d" % img["id"]).status_code == 404
|
||||
assert c.post("/live/broadcasts", data={**show, "id": bid}, files=[("images", ("a.png", jpeg(), "image/jpeg"))]).json()["ok"]
|
||||
assert c.post("/live/broadcasts/%d/delete" % bid).json()["ok"]
|
||||
assert c.post("/live/broadcasts/%d/delete" % bid).status_code == 400
|
||||
who["u"] = admin
|
||||
assert c.post("/live/settings/hosts/%d/delete" % hid).json()["ok"]
|
||||
assert c.post("/live/settings/hosts/%d/delete" % hid).status_code == 400
|
||||
print("OK")
|
||||
run(body)
|
||||
''', {"LIVE_TEST_DB_URL": DSN})
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user