diff --git a/app/main.py b/app/main.py index 08d3dd6..342f495 100644 --- a/app/main.py +++ b/app/main.py @@ -469,7 +469,8 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]: { "key": "live", "title": "라이브 커머스", - "subtitle": "Live Commerce", + "card_title": "라이브 커머스 · Live Commerce", # 메인 카드만 한글·영문 둘 다(사이드바는 짧게) + "subtitle": "Malaysia", "description": "말레이시아 라이브 방송의 호스트 정보와 방송 스케줄·판매금액·결과 이미지를 관리합니다.", "url": "/live/", "health_url": "/live/health", diff --git a/app/modules/live/CLAUDE.md b/app/modules/live/CLAUDE.md index e375dc8..755a5cd 100644 --- a/app/modules/live/CLAUDE.md +++ b/app/modules/live/CLAUDE.md @@ -17,3 +17,6 @@ - **결과 이미지** — 방송 저장과 한 트랜잭션, JPG·PNG·WebP, 한 장 8MB, 방송당 10장(`store.MAX_IMAGES`). `prepare_photo` 가 실제 이미지 확인·긴 변 2400px·EXIF(GPS 등) 제거. BYTEA 저장. `GET /live/images/{id}`(권한 필요, 하루 private 캐시), `?thumb=1` = 160px JPEG(그때그때 만듦). 올린 뒤 내용이 안 바뀐다는 전제 — 이미지를 고치는 기능을 넣으면 캐시도 바꿀 것. - 저장은 `live.js` 가 fetch → JSON `{ok, message}`(틀려도 창의 입력값 유지). 창 하나로 추가·고치기(`data-edit` JSON). +- **한글·영문 전환**(`i18n.py`) — 위 막대 [한글|EN], 쿠키 `live_lang`(브라우저마다, path=/live, 기본 한글). 한글 문구가 키, 템플릿 `t('…')`, 오류 `LiveError(틀, 값)`(라우터가 언어에 맞게), JS `LV_T`(`JS_KEYS`). + **새 문구는 `i18n.EN` 에도 넣는다** — `tests/test_live.py` 가 빠진 문구와 영문 화면의 한글을 잡는다. 입력한 데이터(이름·장소 등)·ERP 공용 사이드바는 번역하지 않는다. +- 메인 카드 제목 = `main.py` `card_title`(한글·영문), 사이드바는 `title` 그대로. diff --git a/app/modules/live/db.py b/app/modules/live/db.py index 21f48df..7ff80f5 100644 --- a/app/modules/live/db.py +++ b/app/modules/live/db.py @@ -16,6 +16,7 @@ from psycopg.rows import dict_row from psycopg_pool import ConnectionPool from . import store +from .i18n import LiveError _HOST_COLUMNS = ("full_name", "phone", "email", "address", "bank_name", "bank_account", "tiktok_handle") @@ -55,7 +56,7 @@ class LiveDBStore: "tiktok_handle=%s, is_active=%s, updated_by=%s WHERE id=%s RETURNING id", (*cols, is_active, by, host_id)).fetchone() if not row: - raise ValueError("호스트를 찾을 수 없습니다.") + raise LiveError("호스트를 찾을 수 없습니다.") return int(row["id"]) def delete_host(self, host_id: int) -> None: @@ -63,9 +64,9 @@ class LiveDBStore: with self._pool.connection() as conn: row = conn.execute("DELETE FROM live_hosts WHERE id=%s RETURNING id", (host_id,)).fetchone() except ForeignKeyViolation: - raise ValueError("방송 기록이 있는 호스트는 지울 수 없습니다 — 사용 안 함으로 바꾸세요.") from None + raise LiveError("방송 기록이 있는 호스트는 지울 수 없습니다 — 사용 안 함으로 바꾸세요.") from None if not row: - raise ValueError("호스트를 찾을 수 없습니다.") + raise LiveError("호스트를 찾을 수 없습니다.") # ── 방송 스케줄 ───────────────────────────────────────── def list_broadcasts(self, start: date, end: date) -> list[dict[str, Any]]: @@ -89,13 +90,13 @@ class LiveDBStore: if broadcast_id is not None: found = conn.execute("SELECT host_id FROM live_broadcasts WHERE id=%s FOR UPDATE", (broadcast_id,)).fetchone() if not found: - raise ValueError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).") + raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).") current = found["host_id"] host = conn.execute("SELECT is_active FROM live_hosts WHERE id=%s", (values["host_id"],)).fetchone() if not host: - raise ValueError("호스트를 찾을 수 없습니다.") + raise LiveError("호스트를 찾을 수 없습니다.") if not host["is_active"] and values["host_id"] != current: - raise ValueError("사용 안 함으로 바뀐 호스트입니다 — 다른 호스트를 고르세요.") + raise LiveError("사용 안 함으로 바뀐 호스트입니다 — 다른 호스트를 고르세요.") args = (values["host_id"], values["broadcast_date"], values["start_time"], values["end_time"], values["venue"], values["sales_amount"], by) if broadcast_id is None: @@ -107,7 +108,7 @@ class LiveDBStore: "sales_amount=%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 ValueError(f"방송 한 건에 이미지는 {store.MAX_IMAGES}장까지입니다(지금 {have}장).") + raise LiveError("방송 한 건에 이미지는 {max}장까지입니다(지금 {have}장).", max=store.MAX_IMAGES, have=have) for im in images: conn.execute("INSERT INTO live_broadcast_images (broadcast_id, filename, content_type, data, width, height, created_by) " "VALUES (%s,%s,%s,%s,%s,%s,%s)", @@ -117,14 +118,14 @@ class LiveDBStore: def delete_broadcast(self, broadcast_id: int) -> None: with self._pool.connection() as conn: if not conn.execute("DELETE FROM live_broadcasts WHERE id=%s RETURNING id", (broadcast_id,)).fetchone(): - raise ValueError("방송을 찾을 수 없습니다.") + raise LiveError("방송을 찾을 수 없습니다.") def move_broadcast(self, broadcast_id: int, day: date, start: time, *, by: str) -> None: """달력에서 빈 칸으로 옮기기 — 방송 길이는 그대로.""" with self._pool.connection() as conn, conn.transaction(): row = conn.execute("SELECT start_time, end_time FROM live_broadcasts WHERE id=%s FOR UPDATE", (broadcast_id,)).fetchone() if not row: - raise ValueError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).") + raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).") conn.execute("UPDATE live_broadcasts SET broadcast_date=%s, start_time=%s, end_time=%s, updated_by=%s WHERE id=%s", (day, start, store.moved_end(row["start_time"], row["end_time"], start), by, broadcast_id)) @@ -136,7 +137,7 @@ class LiveDBStore: rows = conn.execute("SELECT id, broadcast_date, start_time, end_time FROM live_broadcasts WHERE id = ANY(%s) ORDER BY id FOR UPDATE", ([first_id, second_id],)).fetchall() if len(rows) != 2: - raise ValueError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).") + raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).") for mine, other in ((rows[0], rows[1]), (rows[1], rows[0])): conn.execute("UPDATE live_broadcasts SET broadcast_date=%s, start_time=%s, end_time=%s, updated_by=%s WHERE id=%s", (other["broadcast_date"], other["start_time"], other["end_time"], by, mine["id"])) @@ -161,7 +162,7 @@ class LiveDBStore: "ON CONFLICT (ad_date) DO UPDATE SET ad_spend=EXCLUDED.ad_spend, updated_by=EXCLUDED.updated_by, updated_at=now()", (day, amount, by)) except UndefinedTable: - raise ValueError("DB 마이그레이션 live_db 002(광고비)가 아직 적용되지 않았습니다.") from None + raise LiveError("DB 마이그레이션 live_db 002(광고비)가 아직 적용되지 않았습니다.") from None # ── 결과 이미지 ───────────────────────────────────────── def get_image(self, image_id: int) -> dict[str, Any] | None: @@ -171,4 +172,4 @@ class LiveDBStore: def delete_image(self, image_id: int) -> None: with self._pool.connection() as conn: if not conn.execute("DELETE FROM live_broadcast_images WHERE id=%s RETURNING id", (image_id,)).fetchone(): - raise ValueError("이미지를 찾을 수 없습니다.") + raise LiveError("이미지를 찾을 수 없습니다.") diff --git a/app/modules/live/i18n.py b/app/modules/live/i18n.py new file mode 100644 index 0000000..dc23c97 --- /dev/null +++ b/app/modules/live/i18n.py @@ -0,0 +1,112 @@ +"""라이브 커머스 한글·영문 전환(2026-11-04) — 한글 문구가 키, 없으면 한글 그대로. 언어는 쿠키 `live_lang`(브라우저마다). + +새 문구는 여기에도 넣는다 — tests/test_live.py 가 템플릿·오류 문구가 모두 있는지, 영문 화면에 한글이 없는지 확인한다. +""" + +from __future__ import annotations + +from typing import Any + +LANG_COOKIE = "live_lang" + +EN: dict[str, str] = { + # 위 막대·보기 + "이전 달": "Previous month", "다음 달": "Next month", "보기 방식": "View", "표": "Table", "달력": "Calendar", + "호스트 설정": "Host Settings", "+ 방송 추가": "+ Add Broadcast", "언어": "Language", + "방송을 추가하려면 먼저 호스트를 등록해야 합니다.": "Register a host before adding a broadcast.", + "ERP 관리자에게 등록을 요청하세요.": "Ask an ERP admin to register one.", + # 방송 창 + "방송 추가": "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 after the broadcast", + "방송 결과 이미지 (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}", + "{date} {host} 방송을 지울까요? 결과 이미지도 함께 지워집니다.": "Delete the {date} broadcast by {host}? Its result images will be deleted too.", + "이 달에 등록한 방송이 없습니다.": "No broadcasts this month.", + # 달력 + "판매금액": "Sales", "커미션": "Com", "비용": "Fee", "광고비": "Ad Spend", "호스트 비용": "Host Fee", "총 판매금액": "Total Sales", + "ROAS": "ROAS", "합계 & ROAS": "Total & ROAS", "날짜로 이동": "Jump to Date", + "팁: 카드 머리를 끌어 옮기거나 맞바꿀 수 있습니다. 오른쪽으로 스크롤하면 이달 {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}", + # 호스트 설정 + "◀ 스케줄표": "◀ Schedule", "+ 호스트 등록": "+ Add Host", "호스트 등록": "Add Host", "호스트 고치기": "Edit Host", + "이름 (IC 기준)": "Full Name (as per IC)", "전화번호": "Phone Number", "이메일": "Email", "주소": "Address", "은행명": "Bank Name", + "계좌번호": "Bank Account Number", "틱톡 핸들": "Tiktok Handle", "상태": "Status", "사용": "Active", + "{name} 호스트를 지울까요?": "Delete host {name}?", "등록한 호스트가 없습니다.": "No hosts registered.", + "사용 (끄면 새 방송에서 고를 수 없습니다)": "Active (when off, the host can't be selected for new broadcasts)", + # 화면 스크립트(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", + # 저장 결과·입력 오류 + "저장했습니다.": "Saved.", "옮겼습니다.": "Moved.", "광고비를 저장했습니다.": "Ad spend saved.", "방송을 지웠습니다.": "Broadcast deleted.", + "이미지를 지웠습니다.": "Image deleted.", "호스트를 저장했습니다.": "Host saved.", "호스트를 지웠습니다.": "Host deleted.", + "잘못된 요청입니다.": "Invalid request.", + "이름 (IC 기준)을 입력하세요.": "Enter the Full Name (as per IC).", "{label} 이(가) 너무 깁니다({limit}자까지).": "{label} is too long (up to {limit} characters).", + "이메일 형식이 올바르지 않습니다.": "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}을 입력하세요.": "Enter the {label}.", "{label}이 올바르지 않습니다.": "The {label} is invalid.", + "호스트를 고르세요.": "Select a host.", "방송 날짜를 입력하세요.": "Enter the broadcast date.", "방송 장소가 너무 깁니다(200자까지).": "Venue is too long (up to 200 characters).", + "끝 시간이 시작 시간과 같습니다.": "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.", + "{name}: {detail}": "{name}: {detail}", + # 권한·설정 + "로그인이 필요합니다.": "Please sign in.", "라이브 커머스 모듈 권한이 없습니다.": "You don't have access to the Live Commerce module.", + "호스트 정보는 ERP 관리자만 볼 수 있습니다.": "Only ERP admins can view host information.", "라이브 커머스 DB(LIVE_DB_URL)가 설정되지 않았습니다.": "The Live Commerce DB (LIVE_DB_URL) is not configured.", + "라이브 커머스 모듈 접근 권한이 없습니다.": "You don't have access to the Live Commerce module.", + "라이브 커머스 모듈이 아직 설정되지 않았습니다. scripts/sql/live_db_init.sql 로 live_db 를 만들고 .env 에 LIVE_DB_URL 을 넣은 뒤 컨테이너를 다시 시작하세요.": + "The Live Commerce module is not set up yet. Create live_db with scripts/sql/live_db_init.sql, add LIVE_DB_URL to .env and restart the container.", + # 자산 모듈 prepare_photo 오류(이미지 검사를 함께 쓴다) + "사진은 비어 있지 않은 8 MB 이하 파일이어야 합니다.": "The image must be a non-empty file of 8 MB or less.", "JPG, PNG, WebP 사진만 등록할 수 있습니다.": "Only JPG, PNG and WebP images are allowed.", + "사진은 2천만 화소 이하로 등록하세요.": "The image must be 20 megapixels or less.", "사진을 압축해 다시 등록하세요. 저장 크기는 5 MB 이하입니다.": "Please compress the image and try again (5 MB or less once stored).", + "사진을 읽을 수 없습니다. 정상적인 JPG, PNG, WebP 파일을 선택하세요.": "The image can't be read. Please choose a valid JPG, PNG or WebP file.", +} + +# 화면 스크립트에 넘기는 문구(window.LV_T) +JS_KEYS = ("확인", "취소", "지우기", "서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.", "이 이미지", "{name} 를 지울까요?", + "{day} 광고비 (RM) — 비우면 지웁니다") + +_MONTH_NAMES = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") + + +def norm_lang(raw: Any) -> str: + return "en" if raw == "en" else "ko" + + +def t(text: str, lang: str = "ko") -> str: + return EN.get(text, text) if lang == "en" else text + + +def js_text(lang: str) -> dict[str, str]: + return {k: t(k, lang) for k in JS_KEYS} + + +def month_label(year: int, month: int, lang: str = "ko") -> str: + return f"{_MONTH_NAMES[month - 1]} {year}" if lang == "en" else f"{year}년 {month}월" + + +class LiveError(ValueError): + """입력·저장 오류 — 언어에 맞게 다시 쓸 수 있게 문구 틀과 값을 따로 둔다. str() = 한글.""" + + def __init__(self, template: str, **params: Any): + self.template, self.params = template, params + super().__init__(template.format(**params)) + + def text(self, lang: str) -> str: + return t(self.template, lang).format(**{k: t(v, lang) if isinstance(v, str) else v for k, v in self.params.items()}) + + +def error_text(exc: Exception, lang: str) -> str: + return exc.text(lang) if isinstance(exc, LiveError) else t(str(exc), lang) diff --git a/app/modules/live/router.py b/app/modules/live/router.py index 3130660..fa4fe66 100644 --- a/app/modules/live/router.py +++ b/app/modules/live/router.py @@ -23,7 +23,7 @@ from fastapi.responses import HTMLResponse, JSONResponse, Response from app.modules.asset.media import MAX_PHOTO_BYTES, prepare_photo from app.timezone import today_kst -from . import store +from . import i18n, store router = APIRouter(prefix="/live", tags=["live"]) @@ -32,15 +32,23 @@ def _store(request: Request) -> Any: return getattr(request.app.state, "live_store", None) +def _lang(request: Request) -> str: + return i18n.norm_lang(request.cookies.get(i18n.LANG_COOKIE)) + + +def _t(request: Request, text: str) -> str: + return i18n.t(text, _lang(request)) + + def _user(request: Request) -> dict[str, Any]: from app.main import get_current_user_record # noqa: WPS433 from app.store import has_module # noqa: WPS433 user = get_current_user_record(request) if user is None: - raise HTTPException(status_code=401, detail="로그인이 필요합니다.") + raise HTTPException(status_code=401, detail=_t(request, "로그인이 필요합니다.")) if not has_module(user, "live"): - raise HTTPException(status_code=403, detail="라이브 커머스 모듈 권한이 없습니다.") + raise HTTPException(status_code=403, detail=_t(request, "라이브 커머스 모듈 권한이 없습니다.")) return user @@ -49,14 +57,14 @@ def _admin(request: Request) -> dict[str, Any]: user = _user(request) if not is_admin(user): - raise HTTPException(status_code=403, detail="호스트 정보는 ERP 관리자만 볼 수 있습니다.") + raise HTTPException(status_code=403, detail=_t(request, "호스트 정보는 ERP 관리자만 볼 수 있습니다.")) return user def _db(request: Request) -> Any: st = _store(request) if st is None: - raise HTTPException(status_code=503, detail="라이브 커머스 DB(LIVE_DB_URL)가 설정되지 않았습니다.") + raise HTTPException(status_code=503, detail=_t(request, "라이브 커머스 DB(LIVE_DB_URL)가 설정되지 않았습니다.")) return st @@ -69,13 +77,13 @@ def _page(request: Request) -> Any: if user is None: return login_redirect(request) if not has_module(user, "live"): - return render_template(request, "denied.html", {"reason": "라이브 커머스 모듈 접근 권한이 없습니다.", + return render_template(request, "denied.html", {"reason": _t(request, "라이브 커머스 모듈 접근 권한이 없습니다."), "is_admin": is_admin(user)}, status_code=403) st = _store(request) if st is None: return render_template(request, "denied.html", { - "reason": "라이브 커머스 모듈이 아직 설정되지 않았습니다. scripts/sql/live_db_init.sql 로 live_db 를 만들고 " - ".env 에 LIVE_DB_URL 을 넣은 뒤 컨테이너를 다시 시작하세요.", + "reason": _t(request, "라이브 커머스 모듈이 아직 설정되지 않았습니다. scripts/sql/live_db_init.sql 로 live_db 를 만들고 " + ".env 에 LIVE_DB_URL 을 넣은 뒤 컨테이너를 다시 시작하세요."), "user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active="live")}, status_code=503) return st, user @@ -84,16 +92,18 @@ def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, An from app.main import build_erp_nav, render_template # noqa: WPS433 from app.store import is_admin # noqa: WPS433 - return render_template(request, name, {"user": user, "is_admin": is_admin(user), + lang = _lang(request) + return render_template(request, name, {"user": user, "is_admin": is_admin(user), "lang": lang, + "t": lambda text: i18n.t(text, lang), "js_text": i18n.js_text(lang), "nav_items": build_erp_nav(user, active="live"), **ctx}) -def _ok(message: str) -> JSONResponse: - return JSONResponse({"ok": True, "message": message}) +def _ok(request: Request, message: str) -> JSONResponse: + return JSONResponse({"ok": True, "message": _t(request, message)}) -def _fail(exc: Exception) -> JSONResponse: - return JSONResponse({"ok": False, "message": str(exc)}, status_code=400) +def _fail(request: Request, exc: Exception) -> JSONResponse: + return JSONResponse({"ok": False, "message": i18n.error_text(exc, _lang(request))}, status_code=400) def _opt_id(raw: str) -> int | None: @@ -119,8 +129,9 @@ def index(request: Request, month: str = "") -> Any: if not isinstance(got, tuple): return got st, user = got - span = store.month_range(month, today_kst()) - rows = [store.broadcast_view(b) for b in st.list_broadcasts(span["start"], span["end"])] + lang = _lang(request) + span = store.month_range(month, today_kst(), lang) + rows = [store.broadcast_view(b, lang) for b in st.list_broadcasts(span["start"], span["end"])] return _render(request, "live/index.html", user, {"view": "table", "span": span, "rows": rows, "hosts": st.host_choices(), "max_images": store.MAX_IMAGES}) @@ -131,9 +142,9 @@ def calendar(request: Request, month: str = "") -> Any: if not isinstance(got, tuple): return got st, user = got - today = today_kst() - span = store.month_range(month, today) - cal = store.build_calendar(span, st.list_broadcasts(span["start"], span["end"]), st.ad_spends(span["start"], span["end"]), today) + 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) return _render(request, "live/calendar.html", user, {"view": "calendar", "span": span, "cal": cal, "hosts": st.host_choices(), "max_images": store.MAX_IMAGES}) @@ -151,8 +162,8 @@ def broadcast_move(request: Request, broadcast_id: int, broadcast_date: str = Fo day, start = store.parse_move(broadcast_date, start_time) st.move_broadcast(broadcast_id, day, start, by=user.get("email", "")) except ValueError as exc: - return _fail(exc) - return _ok("옮겼습니다.") + return _fail(request, exc) + return _ok(request, "옮겼습니다.") @router.post("/ad-spend") @@ -163,22 +174,22 @@ def ad_spend_save(request: Request, day: str = Form(""), amount: str = Form("")) when, _ = store.parse_move(day, "00:00") st.save_ad_spend(when, store.parse_money(amount), by=user.get("email", "")) except ValueError as exc: - return _fail(exc) - return _ok("광고비를 저장했습니다.") + 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] if len(picked) > store.MAX_IMAGES: - raise ValueError(f"방송 한 건에 이미지는 {store.MAX_IMAGES}장까지입니다.") + raise i18n.LiveError("방송 한 건에 이미지는 {max}장까지입니다.", max=store.MAX_IMAGES) out = [] for f in picked: name = PurePath(f.filename.replace("\\", "/")).name[:200] try: data, ctype, width, height = prepare_photo(f.file.read(MAX_PHOTO_BYTES + 1)) except ValueError as exc: - raise ValueError(f"{name}: {exc}") from None + raise i18n.LiveError("{name}: {detail}", name=name, detail=str(exc)) from None out.append({"filename": name, "content_type": ctype, "data": data, "width": width, "height": height}) return out @@ -195,8 +206,8 @@ def broadcast_save(request: Request, id: str = Form(""), host_id: str = Form("") "end_time": end_time, "venue": venue, "sales_amount": sales_amount}) st.save_broadcast(broadcast_id, values, _read_images(images), by=user.get("email", "")) except ValueError as exc: - return _fail(exc) - return _ok("저장했습니다.") + return _fail(request, exc) + return _ok(request, "저장했습니다.") @router.post("/broadcasts/{broadcast_id}/delete") @@ -205,8 +216,8 @@ def broadcast_delete(request: Request, broadcast_id: int) -> JSONResponse: try: _db(request).delete_broadcast(broadcast_id) except ValueError as exc: - return _fail(exc) - return _ok("방송을 지웠습니다.") + return _fail(request, exc) + return _ok(request, "방송을 지웠습니다.") @router.get("/images/{image_id}") @@ -214,7 +225,7 @@ def image(request: Request, image_id: int, thumb: int = 0) -> Response: _user(request) row = _db(request).get_image(image_id) if not row: - raise HTTPException(status_code=404, detail="이미지를 찾을 수 없습니다.") + raise HTTPException(status_code=404, detail=_t(request, "이미지를 찾을 수 없습니다.")) data, ctype = (store.thumbnail(row["data"]), "image/jpeg") if thumb else (bytes(row["data"]), row["content_type"]) # 올린 뒤 내용이 바뀌지 않으므로 하루 캐시. 권한이 필요한 이미지라 private. return Response(data, media_type=ctype, headers={"Cache-Control": "private, max-age=86400", "X-Content-Type-Options": "nosniff"}) @@ -226,8 +237,8 @@ def image_delete(request: Request, image_id: int) -> JSONResponse: try: _db(request).delete_image(image_id) except ValueError as exc: - return _fail(exc) - return _ok("이미지를 지웠습니다.") + return _fail(request, exc) + return _ok(request, "이미지를 지웠습니다.") # ──────────────────────────────────────────────────────────── @@ -243,7 +254,7 @@ def settings(request: Request) -> Any: return got st, user = got if not is_admin(user): - return render_template(request, "denied.html", {"reason": "호스트 정보는 ERP 관리자만 볼 수 있습니다.", "is_admin": False}, + return render_template(request, "denied.html", {"reason": _t(request, "호스트 정보는 ERP 관리자만 볼 수 있습니다."), "is_admin": False}, status_code=403) return _render(request, "live/settings.html", user, {"hosts": st.list_hosts()}) @@ -259,8 +270,8 @@ def host_save(request: Request, id: str = Form(""), full_name: str = Form(""), p "bank_account": bank_account, "tiktok_handle": tiktok_handle}) st.save_host(_opt_id(id), values, is_active=bool(is_active), by=user.get("email", "")) except ValueError as exc: - return _fail(exc) - return _ok("호스트를 저장했습니다.") + return _fail(request, exc) + return _ok(request, "호스트를 저장했습니다.") @router.post("/settings/hosts/{host_id}/delete") @@ -269,5 +280,5 @@ def host_delete(request: Request, host_id: int) -> JSONResponse: try: _db(request).delete_host(host_id) except ValueError as exc: - return _fail(exc) - return _ok("호스트를 지웠습니다.") + return _fail(request, exc) + return _ok(request, "호스트를 지웠습니다.") diff --git a/app/modules/live/store.py b/app/modules/live/store.py index db597f9..25340fa 100644 --- a/app/modules/live/store.py +++ b/app/modules/live/store.py @@ -10,6 +10,8 @@ from typing import Any from PIL import Image +from .i18n import LiveError, month_label + MAX_IMAGES = 10 # 방송 한 건에 MAX_SALES = Decimal("999999999999.99") THUMB_SIZE = 160 @@ -24,14 +26,15 @@ _WEEKDAYS = ("MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", _MONTHS = ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC") HOST_LIMITS = {"full_name": 200, "phone": 40, "email": 254, "address": 500, "bank_name": 100, "bank_account": 40, "tiktok_handle": 64} -_LABELS = {"full_name": "Full Name", "phone": "Phone Number", "email": "Email", "address": "Address", "bank_name": "Bank Name", - "bank_account": "Bank Account Number", "tiktok_handle": "Tiktok Handle"} +_LABELS = {"full_name": "이름 (IC 기준)", "phone": "전화번호", "email": "이메일", "address": "주소", "bank_name": "은행명", + "bank_account": "계좌번호", "tiktok_handle": "틱톡 핸들"} _EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+\-']+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$") _PHONE_RE = re.compile(r"^\+?[0-9()\-\s]+$") _ACCOUNT_RE = re.compile(r"^[0-9\-\s]+$") _HANDLE_RE = re.compile(r"^[A-Za-z0-9._]+$") _HANDLE_URL_RE = re.compile(r"^(?:https?://)?(?:www\.|m\.)?tiktok\.com/@?", re.I) WEEKDAYS_KO = "월화수목금토일" +_WEEKDAYS_EN_SHORT = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") def clean_handle(raw: Any) -> str: @@ -41,22 +44,22 @@ def clean_handle(raw: Any) -> str: def clean_host(values: dict[str, Any]) -> dict[str, str]: - """호스트 입력 검사 — Full Name 만 필수, 나머지는 있으면 형식 확인. 틀리면 ValueError.""" + """호스트 입력 검사 — 이름만 필수, 나머지는 있으면 형식 확인. 틀리면 ValueError.""" out = {k: str(values.get(k) or "").strip() for k in HOST_LIMITS} out["tiktok_handle"] = clean_handle(values.get("tiktok_handle")) if not out["full_name"]: - raise ValueError("Full Name (as per IC) 을 입력하세요.") + raise LiveError("이름 (IC 기준)을 입력하세요.") for key, limit in HOST_LIMITS.items(): if len(out[key]) > limit: - raise ValueError(f"{_LABELS[key]} 이(가) 너무 깁니다({limit}자까지).") + raise LiveError("{label} 이(가) 너무 깁니다({limit}자까지).", label=_LABELS[key], limit=limit) if out["email"] and not _EMAIL_RE.match(out["email"]): - raise ValueError("Email 형식이 올바르지 않습니다.") + raise LiveError("이메일 형식이 올바르지 않습니다.") if out["phone"] and not _PHONE_RE.match(out["phone"]): - raise ValueError("Phone Number 는 숫자·+·-·괄호만 입력하세요.") + raise LiveError("전화번호는 숫자·+·-·괄호만 입력하세요.") if out["bank_account"] and not _ACCOUNT_RE.match(out["bank_account"]): - raise ValueError("Bank Account Number 는 숫자·-만 입력하세요.") + raise LiveError("계좌번호는 숫자·-만 입력하세요.") if out["tiktok_handle"] and not _HANDLE_RE.match(out["tiktok_handle"]): - raise ValueError("Tiktok Handle 은 영문·숫자·밑줄·점만 입력하세요.") + raise LiveError("틱톡 핸들은 영문·숫자·밑줄·점만 입력하세요.") return out @@ -68,11 +71,11 @@ def parse_money(raw: Any) -> Decimal | None: try: n = Decimal(s) except InvalidOperation: - raise ValueError("판매금액은 숫자로 입력하세요.") from None + raise LiveError("판매금액은 숫자로 입력하세요.") from None if not n.is_finite() or n < 0: - raise ValueError("판매금액은 0 이상 숫자로 입력하세요.") + raise LiveError("판매금액은 0 이상 숫자로 입력하세요.") if n > MAX_SALES: - raise ValueError("판매금액이 너무 큽니다.") + raise LiveError("판매금액이 너무 큽니다.") return n.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) @@ -80,30 +83,30 @@ def _parse_time(raw: Any, *, label: str, required: bool) -> time | None: s = str(raw or "").strip() if not s: if required: - raise ValueError(f"{label}을 입력하세요.") + raise LiveError("{label}을 입력하세요.", label=label) return None try: return time.fromisoformat(s).replace(second=0, microsecond=0, tzinfo=None) except ValueError: - raise ValueError(f"{label}이 올바르지 않습니다.") from None + raise LiveError("{label}이 올바르지 않습니다.", label=label) from None def clean_broadcast(values: dict[str, Any]) -> dict[str, Any]: """방송 입력 검사 — 호스트·날짜·시작·끝 시간 필수(끝 시간으로 시간 요금 계산). 끝이 시작보다 이르면 자정을 넘긴 방송. 틀리면 ValueError.""" host = str(values.get("host_id") or "").strip() if not host.isdigit(): - raise ValueError("호스트를 고르세요.") + raise LiveError("호스트를 고르세요.") try: day = date.fromisoformat(str(values.get("broadcast_date") or "").strip()) except ValueError: - raise ValueError("방송 날짜를 입력하세요.") from None + raise LiveError("방송 날짜를 입력하세요.") from None venue = str(values.get("venue") or "").strip() if len(venue) > 200: - raise ValueError("방송 장소가 너무 깁니다(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: - raise ValueError("끝 시간이 시작 시간과 같습니다.") + raise LiveError("끝 시간이 시작 시간과 같습니다.") return {"host_id": int(host), "broadcast_date": day, "start_time": start, "end_time": end, "venue": venue, "sales_amount": parse_money(values.get("sales_amount"))} @@ -113,7 +116,7 @@ def parse_move(day: Any, start: Any) -> tuple[date, time]: try: when = date.fromisoformat(str(day or "").strip()) except ValueError: - raise ValueError("날짜가 올바르지 않습니다.") from None + raise LiveError("날짜가 올바르지 않습니다.") from None return when, _parse_time(start, label="시간", required=True) @@ -142,11 +145,11 @@ def fmt_short(n: Decimal) -> str: return f"{n:,.2f}".removesuffix(".00") -def broadcast_view(b: dict[str, Any]) -> dict[str, Any]: +def broadcast_view(b: dict[str, Any], lang: str = "ko") -> dict[str, Any]: """방송 한 건 화면 값 — 표·달력 공통. b = db.list_broadcasts 한 줄.""" pay = session_pay(b["start_time"], b["end_time"], b["sales_amount"]) return { - "date": fmt_date(b["broadcast_date"]), "times": fmt_times(b["start_time"], b["end_time"]), + "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"], @@ -164,9 +167,9 @@ def _roas(sales: Decimal, ad_spend: Decimal) -> str: return f"{sales / ad_spend:.2f}" if ad_spend else "-" -def build_calendar(span: dict[str, Any], broadcasts: list[dict[str, Any]], ad_spend: dict[date, Decimal], today: date) -> dict[str, Any]: +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]: """달력 보기 값 — 날짜(열)·2시간 칸(줄)·날짜별 합계·달 합계. 칸은 시작 시간으로 정한다.""" - views = [(b, broadcast_view(b)) for b in broadcasts] + views = [(b, broadcast_view(b, lang)) for b in broadcasts] used = {b["start_time"].hour // SLOT_HOURS * SLOT_HOURS for b, _ in views} days = [] day = span["start"] @@ -175,8 +178,8 @@ def build_calendar(span: dict[str, Any], broadcasts: list[dict[str, Any]], ad_sp sales = sum((b["sales_amount"] or Decimal(0) for b, _ in mine), Decimal(0)) fee = sum((v["pay"]["fee"] for _, v in mine), Decimal(0)) spend = ad_spend.get(day, Decimal(0)) - days.append({"iso": day.isoformat(), "date": day, "day": day.day, "weekday": _WEEKDAYS[day.weekday()], - "label": f"{day.day} {_MONTHS[day.month - 1]}", "is_weekend": day.weekday() >= 5, "is_today": day == today, + 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, "sales_text": fmt_short(sales), "fee_text": fmt_short(fee), "spend_text": fmt_short(spend), "roas": _roas(sales, spend)}) day += timedelta(days=1) @@ -188,12 +191,12 @@ def build_calendar(span: dict[str, Any], broadcasts: list[dict[str, Any]], ad_sp for d in days] slots.append({"start": f"{hour:02d}:00", "end": f"{end_hour:02d}:00", "label": f"{hour:02d}:00 - {end_hour:02d}:00", "cells": cells}) sales, fee, spend = (sum((d[k] for d in days), Decimal(0)) for k in ("sales", "fee", "spend")) - return {"days": days, "slots": slots, "slot_note": f"{SLOT_HOURS} Hours (RM{fmt_short(HOURLY_RATE * SLOT_HOURS)} Base)", + return {"days": days, "slots": slots, "slot_note": f"{SLOT_HOURS} Hours (RM{fmt_short(HOURLY_RATE * SLOT_HOURS)} Base)" if lang == "en" else f"{SLOT_HOURS}시간 (기본 RM{fmt_short(HOURLY_RATE * SLOT_HOURS)})", "commission_percent": fmt_short(COMMISSION_PERCENT).split(".")[0], "totals": {"sales": fmt_short(sales), "fee": fmt_short(fee), "spend": fmt_short(spend), "roas": _roas(sales, spend)}} -def month_range(raw: Any, today: date) -> dict[str, Any]: +def month_range(raw: Any, today: date, lang: str = "ko") -> dict[str, Any]: """'YYYY-MM'(틀리거나 없으면 이번 달) → 그 달 첫날·다음 달 첫날·앞뒤 달 주소 값·제목.""" m = re.fullmatch(r"(\d{4})-(\d{2})", str(raw or "").strip()) year, month = (int(m[1]), int(m[2])) if m and 2000 <= int(m[1]) <= 2100 and 1 <= int(m[2]) <= 12 else (today.year, today.month) @@ -201,11 +204,11 @@ def month_range(raw: Any, today: date) -> dict[str, Any]: end = date(year + (month == 12), month % 12 + 1, 1) prev = date(year - (month == 1), (month - 2) % 12 + 1, 1) return {"start": start, "end": end, "prev": prev.strftime("%Y-%m"), "next": end.strftime("%Y-%m"), - "label": f"{year}년 {month}월"} + "label": month_label(year, month, lang)} -def fmt_date(d: date) -> str: - return f"{d:%Y.%m.%d}({WEEKDAYS_KO[d.weekday()]})" +def fmt_date(d: date, lang: str = "ko") -> str: + return f"{d:%Y.%m.%d} ({_WEEKDAYS_EN_SHORT[d.weekday()]})" if lang == "en" else f"{d:%Y.%m.%d}({WEEKDAYS_KO[d.weekday()]})" def fmt_times(start: time, end: time | None) -> str: diff --git a/app/modules/live/templates/live/_bar.html b/app/modules/live/templates/live/_bar.html index d005870..390fcd4 100644 --- a/app/modules/live/templates/live/_bar.html +++ b/app/modules/live/templates/live/_bar.html @@ -1,18 +1,19 @@ -{#- 스케줄표·달력 공통 위 막대 — 달 이동, 표/달력 전환, 호스트 설정, 방송 추가. view = table | calendar -#} +{#- 스케줄표·달력 공통 위 막대 — 달 이동, 표/달력 전환, 언어, 호스트 설정, 방송 추가. view = table | calendar -#} {% set here = '/live/calendar' if view == 'calendar' else '/live/' %} {% set can_add = hosts | selectattr('is_active') | list %}
- ◀ + ◀

{{ span.label }}

- ▶ -
{% if not can_add %} -

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

+

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

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

+

-
diff --git a/app/modules/live/templates/live/_lang.html b/app/modules/live/templates/live/_lang.html new file mode 100644 index 0000000..46704b7 --- /dev/null +++ b/app/modules/live/templates/live/_lang.html @@ -0,0 +1,5 @@ +{#- 한글·영문 전환 — 누르면 쿠키에 저장하고 다시 그린다(live.js). 언어 이름은 언어와 상관없이 그대로 보인다. -#} +
+ + +
diff --git a/app/modules/live/templates/live/_scripts.html b/app/modules/live/templates/live/_scripts.html new file mode 100644 index 0000000..95a5973 --- /dev/null +++ b/app/modules/live/templates/live/_scripts.html @@ -0,0 +1,2 @@ + + diff --git a/app/modules/live/templates/live/calendar.html b/app/modules/live/templates/live/calendar.html index 1dca65f..b4596ec 100644 --- a/app/modules/live/templates/live/calendar.html +++ b/app/modules/live/templates/live/calendar.html @@ -1,30 +1,30 @@ {% extends "erp_base.html" %} {#- 라이브 커머스 달력 보기(2026-11-04) — 줄 = 2시간 칸, 열 = 날짜, 맨 아래 = 날짜별 합계. 카드 머리 = Tiktok Handle(없으면 이름). - 카드 머리를 끌어 빈 칸으로 옮기거나 다른 카드 위에 놓아 맞바꾼다(live.js). 글자는 사용자가 준 화면 그대로 영어. -#} -{% block head_extra %}{% endblock %} + 카드 머리를 끌어 빈 칸으로 옮기거나 다른 카드 위에 놓아 맞바꾼다(live.js). 문구 = t()(i18n.py), 영문은 CSS 로 대문자(받은 화면과 같게). -#} +{% block head_extra %}{% endblock %} {% block content %} -
+
{% include "live/_bar.html" %}
-
TOTAL SALESRM {{ cal.totals.sales }}
-
AD SPENDRM {{ cal.totals.spend }}
-
HOST FEERM {{ cal.totals.fee }}
+
{{ t('총 판매금액') }}RM {{ cal.totals.sales }}
+
{{ t('광고비') }}RM {{ cal.totals.spend }}
+
{{ t('호스트 비용') }}RM {{ cal.totals.fee }}
ROAS{{ cal.totals.roas }}
-