feat(라이브커머스): 한글·영문 전환 버튼과 메인 카드 제목 표기

스케줄표·달력·호스트 설정 위에 한글/EN 버튼을 두고 화면·창·오류·확인
문구를 모두 전환한다(쿠키 live_lang, 브라우저마다 기억). 메인 카드 제목은
"라이브 커머스 · Live Commerce"로 표기한다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-04 17:35:16 +09:00
parent 25c885d5dd
commit 15dcabc538
17 changed files with 414 additions and 182 deletions
+83 -5
View File
@@ -6,6 +6,7 @@
"""
import io
import os
import re
import subprocess
import sys
import tempfile
@@ -20,7 +21,7 @@ from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from app.modules.live import store # noqa: E402
from app.modules.live import i18n, store # noqa: E402
DSN = os.getenv("LIVE_TEST_DB_URL", "")
DB_ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
@@ -95,6 +96,7 @@ class StoreTests(unittest.TestCase):
def test_month_range(self):
today = date(2026, 11, 4)
self.assertEqual(store.month_range("", today)["label"], "2026년 11월")
self.assertEqual(store.month_range("", today, "en")["label"], "November 2026")
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)
@@ -104,6 +106,7 @@ class StoreTests(unittest.TestCase):
def test_format(self):
self.assertEqual(store.fmt_date(date(2026, 11, 4)), "2026.11.04(수)")
self.assertEqual(store.fmt_date(date(2026, 11, 4), "en"), "2026.11.04 (Wed)")
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")
@@ -136,7 +139,9 @@ class StoreTests(unittest.TestCase):
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))
{date(2026, 11, 4): Decimal("24")}, 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일", "2시간 (기본 RM50)"))
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")
@@ -168,7 +173,50 @@ class StoreTests(unittest.TestCase):
self.assertEqual((im.format, im.size), ("JPEG", (160, 80)))
class I18nTests(unittest.TestCase):
def test_every_text_has_english(self):
"""템플릿·오류·권한 문구가 모두 영문 표에 있다 — 새 문구를 넣고 빠뜨리면 여기서 걸린다."""
live = ROOT / "app" / "modules" / "live"
keys = set(i18n.JS_KEYS) | set(store._LABELS.values()) | {"시작 시간", "끝 시간"}
for path in (live / "templates" / "live").glob("*.html"):
keys |= set(re.findall(r"\bt\('([^']+)'\)", path.read_text(encoding="utf-8")))
for name in ("store.py", "db.py", "router.py"):
text = (live / name).read_text(encoding="utf-8")
keys |= set(re.findall(r'LiveError\("([^"]+)"', text))
keys |= set(re.findall(r'_t\(request, "([^"]+)"\)', text))
keys |= set(re.findall(r'_ok\(request, "([^"]+)"\)', text))
keys |= set(re.findall(r'raise ValueError\("([^"]+)"', text))
keys |= set(re.findall(r'ValueError\("([^"]+)"', (ROOT / "app" / "modules" / "asset" / "media.py").read_text(encoding="utf-8")))
self.assertGreater(len(keys), 80)
self.assertEqual(sorted(k for k in keys if k not in i18n.EN), [])
self.assertEqual(sorted(k for k, v in i18n.EN.items() if re.search("[가-힣]", v)), [])
def test_error_text(self):
err = i18n.LiveError("{label} 이(가) 너무 깁니다({limit}자까지).", label="이메일", limit=254)
self.assertEqual(str(err), "이메일 이(가) 너무 깁니다(254자까지).")
self.assertEqual(i18n.error_text(err, "en"), "Email is too long (up to 254 characters).")
self.assertEqual(i18n.error_text(err, "ko"), str(err))
self.assertEqual(i18n.error_text(ValueError("잘못된 요청입니다."), "en"), "Invalid request.")
nested = i18n.LiveError("{name}: {detail}", name="a{b}.jpg", detail="JPG, PNG, WebP 사진만 등록할 수 있습니다.")
self.assertEqual(nested.text("en"), "a{b}.jpg: Only JPG, PNG and WebP images are allowed.")
self.assertEqual((i18n.norm_lang("en"), i18n.norm_lang("ko"), i18n.norm_lang("<x>"), i18n.norm_lang(None)), ("en", "ko", "ko", "ko"))
class WebTests(unittest.TestCase):
def test_main_card_title_both_languages(self):
res = _run('''
def body(c):
who["u"] = U("a@test.local", role="admin")
page = c.get("/modules").text # 카드 화면(수퍼관리자 홈과 같은 main.html)
assert "라이브 커머스 · Live Commerce" in page, page[:300]
nav = [i for i in main.build_erp_nav(who["u"], active="live") if i["key"] == "live"]
assert nav and nav[0]["label"] == "라이브 커머스" # 사이드바는 짧게
print("OK")
run(body)
''')
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
def test_registered_and_unconfigured(self):
res = _run('''
from app.store import MODULE_KEYS
@@ -220,12 +268,12 @@ def body(c):
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"]
assert bad.status_code == 400 and "이메일" 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"):
for field in ("이름 (IC 기준)", "전화번호", "이메일", "주소", "은행명", "계좌번호", "틱톡 핸들"):
assert field in page, field
assert ACCOUNT in page and "Siti &lt;b&gt;" 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
@@ -274,8 +322,38 @@ def body(c):
# ── 달력: 카드 머리 = 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 "날짜로 이동" in cal and "토요일" in cal and "12:00 - 14:00" in cal and "2시간 (기본 RM50)" in cal
assert '<span class="lv-card-name">siti.%s</span>' % tag in cal and "RM54.80" in cal and ">4.80</b>" in cal
# ── 영문: 화면 세 개 모두 한글 없음(입력한 데이터 제외)·날짜·오류·권한 문구 ──
def no_korean(url):
page = c.get(url).text
assert 'class="lv-lang"' in page and "window.LV_T" in page
part = page[page.index('<section class="lv"'):page.index("</dialog>")].replace(">한글<", "><") # 화면 + 창(공용 셸 제외)
left = re.findall("[가-힣][^<>\\"]*", part)
assert not left, (url, left[:5])
return page
c.cookies.set("live_lang", "en")
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 "Jump to Date" in cal and "SATURDAY" in cal and "1 MAR" in cal and "2 Hours (RM50 Base)" in cal and ">Sales<" in cal and "Com (10%)" in cal and "Fee: <b>RM54.80" 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, "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", "Tiktok Handle"):
assert field in page, field
who["u"] = staff
c.cookies.set("live_lang", "<bad>") # 모르는 값 = 한글
assert "2031년 3월" in c.get("/live/?month=2031-03").text
c.cookies.delete("live_lang")
assert ACCOUNT not in cal and "Maybank" not in cal
day = __import__("datetime").date
def one(i):