diff --git a/app/main.py b/app/main.py index 9c430c4..d830569 100644 --- a/app/main.py +++ b/app/main.py @@ -69,6 +69,7 @@ MODULE_LABELS: dict[str, str] = { "outreach": "안내문 발송", "live": "라이브 커머스", "live_host": "라이브 호스트 등록", + "live_host_edit": "라이브 호스트 수정", "expense_approver": "개인경비", "vacation_approver": "휴가", } diff --git a/app/modules/live/CLAUDE.md b/app/modules/live/CLAUDE.md index cc1bc76..a489d68 100644 --- a/app/modules/live/CLAUDE.md +++ b/app/modules/live/CLAUDE.md @@ -5,9 +5,10 @@ > 다른 모듈과 연결: 이미지 검사 = 자산 모듈 `app/modules/asset/media.py prepare_photo` 재사용(바꾸면 양쪽 확인). - 말레이시아 라이브 커머스 방송의 호스트 정보·방송 스케줄. 권한키 `live`, DB `LIVE_DB_URL`(없으면 "설정 필요" 안내). -- **호스트 설정** `/live/settings` — Full Name (as per IC)(필수)·Phone Number·Email·Address·Bank Name·Bank Account Number. +- **호스트 설정** `/live/settings` — 간단한 이름(필수, `display_name`, 마이그레이션 004 — 말레이 이름은 끝이 아버지 이름이라 자동으로 줄이지 않고 사람이 입력, 빈 예전 호스트는 화면에 Full Name)·Full Name (as per IC)(필수)·Phone Number·Email·Address·Bank Name·Bank Account Number. **계좌 등 개인정보라 ERP 관리자만**(`is_admin`) — 화면·저장·지우기 모두. 스케줄 화면에는 `db.host_choices`(이름·사용 여부)만 넘긴다. - **틱톡 계정은 호스트가 아니라 방송마다**(2026-11-05, 마이그레이션 003 `live_broadcasts.tiktok_handle`) — 호스트가 여러 계정에서 방송하므로. 방송 창에서 입력(선택), `@`·주소를 붙여 넣어도 계정명만 저장, 쓴 적 있는 계정을 제안(`db.account_choices`). `live_hosts.tiktok_handle` 은 값만 남아 있고 안 씀. 달력에서 옮기거나 맞바꿔도 계정은 그 방송에 그대로. + **틱톡 계정은 호스트가 아니라 방송마다**(2026-11-05, 마이그레이션 003 `live_broadcasts.tiktok_handle`) — 호스트가 여러 계정에서 방송하므로. 방송 창에서 입력(선택), `@`·주소를 붙여 넣어도 계정명만 저장, 쓴 적 있는 계정을 제안(`db.account_choices`). `live_hosts.tiktok_handle` 은 값만 남아 있고 안 씀. 달력에서 옮기거나 맞바꿔도 계정은 그 방송에 그대로. 달력 카드 머리·스케줄표·방송 창의 호스트 = 간단한 이름, 카드 머리 아래 작은 글자 = 계정. + **`live_host_edit` 칩**(+ `live`, 관리자 페이지 토글) = 호스트 **고치기**(사용 여부 포함): 지우기 불가, 개인정보는 페이지에 싣지 않아 빈칸으로 열리고 비워 두면 그대로·입력하면 바뀜(이 칩으로는 지울 수 없음). **`live_host` 칩**(+ `live` 칩 필요) = 새 호스트 **등록만**: 설정 화면에 이름·상태만 보이고, 입력한 계좌 등은 저장 후 못 봄. 고치기·지우기 불가, 사용 여부 못 고름(항상 사용). 사용 안 함 = 새 방송에서 못 고름(그 호스트로 이미 등록된 방송을 고칠 때만 보임). 방송 기록이 있는 호스트는 못 지움(FK RESTRICT). - **스케줄표** `/live/?month=YYYY-MM`(`live` 권한자 모두) — 호스트·날짜·시작/끝 시간·방송 장소·판매금액·커미션·호스트 비용·결과 이미지. 호스트·날짜·시작·끝 시간 필수(판매금액은 방송 후 입력). diff --git a/app/modules/live/db.py b/app/modules/live/db.py index 9450197..75a91c5 100644 --- a/app/modules/live/db.py +++ b/app/modules/live/db.py @@ -18,7 +18,7 @@ from psycopg_pool import ConnectionPool from . import store from .i18n import LiveError -_HOST_COLUMNS = ("full_name", "phone", "email", "address", "bank_name", "bank_account") +_HOST_COLUMNS = ("display_name", "full_name", "phone", "email", "address", "bank_name", "bank_account") class LiveDBStore: @@ -39,7 +39,11 @@ class LiveDBStore: def host_choices(self) -> list[dict[str, Any]]: """스케줄 화면 호스트 고르기 — 개인정보·계좌는 뺀다.""" with self._pool.connection() as conn: - return conn.execute("SELECT id, full_name, is_active FROM live_hosts ORDER BY full_name, id").fetchall() + return conn.execute("SELECT id, display_name, full_name, is_active FROM live_hosts ORDER BY full_name, id").fetchall() + + def get_host(self, host_id: int) -> dict[str, Any] | None: + with self._pool.connection() as conn: + return conn.execute("SELECT * FROM live_hosts WHERE id=%s", (host_id,)).fetchone() def account_choices(self) -> list[str]: """방송 창 틱톡 계정 입력 제안 — 지금까지 방송에 쓴 계정.""" @@ -52,12 +56,12 @@ class LiveDBStore: with self._pool.connection() as conn: if host_id is None: row = conn.execute( - "INSERT INTO live_hosts (full_name, phone, email, address, bank_name, bank_account, " - "is_active, created_by, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id", + "INSERT INTO live_hosts (display_name, full_name, phone, email, address, bank_name, bank_account, " + "is_active, created_by, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id", (*cols, is_active, by, by)).fetchone() else: row = conn.execute( - "UPDATE live_hosts SET full_name=%s, phone=%s, email=%s, address=%s, bank_name=%s, bank_account=%s, " + "UPDATE live_hosts SET display_name=%s, full_name=%s, phone=%s, email=%s, address=%s, bank_name=%s, bank_account=%s, " "is_active=%s, updated_by=%s WHERE id=%s RETURNING id", (*cols, is_active, by, host_id)).fetchone() if not row: @@ -78,7 +82,7 @@ class LiveDBStore: """start 이상 end 미만, 날짜·시간 순. 줄마다 images = [{id, filename}](내용 제외).""" with self._pool.connection() as conn: rows = conn.execute( - "SELECT b.*, h.full_name AS host_name FROM live_broadcasts b JOIN live_hosts h ON h.id = b.host_id " + "SELECT b.*, COALESCE(NULLIF(h.display_name, ''), h.full_name) AS host_name FROM live_broadcasts b JOIN live_hosts h ON h.id = b.host_id " "WHERE b.broadcast_date >= %s AND b.broadcast_date < %s ORDER BY b.broadcast_date, b.start_time, b.id", (start, end)).fetchall() images = conn.execute( diff --git a/app/modules/live/i18n.py b/app/modules/live/i18n.py index dc23c97..0823a65 100644 --- a/app/modules/live/i18n.py +++ b/app/modules/live/i18n.py @@ -37,7 +37,7 @@ EN: dict[str, str] = { "{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", + "간단한 이름": "Short Name", "이름 (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)", @@ -48,7 +48,8 @@ EN: dict[str, str] = { "저장했습니다.": "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).", + "간단한 이름을 입력하세요.": "Enter the Short Name.", "이름 (IC 기준)을 입력하세요.": "Enter the Full Name (as per IC).", + "개인정보는 보이지 않습니다. 비워 두면 그대로 유지됩니다.": "Personal details are hidden. Leave them blank to keep the current values.", "{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.", diff --git a/app/modules/live/router.py b/app/modules/live/router.py index 60aa047..72d9f9e 100644 --- a/app/modules/live/router.py +++ b/app/modules/live/router.py @@ -8,7 +8,7 @@ GET /live/images/{id} 결과 이미지(?thumb=1 = 작은 그림) · POST /live/images/{id}/delete GET /live/settings 설정 — 호스트 정보(ERP 관리자만, 계좌 등 개인정보. `live_host` 칩은 이름·틱톡·상태만) POST /live/settings/hosts 호스트 추가·고치기 · POST /live/settings/hosts/{id}/delete -권한: 모듈 권한키 `live`(스케줄), 설정은 ERP 관리자, `live` + `live_host` 칩 = 새 호스트 등록만. +권한: 모듈 권한키 `live`(스케줄), 설정은 ERP 관리자, `live` + `live_host` 칩 = 새 호스트 등록, `live` + `live_host_edit` 칩 = 고치기(둘 다 개인정보는 안 보임). DB: LIVE_DB_URL(live_db) — 없으면 "설정 필요" 안내. 저장 요청은 live.js 가 fetch 로 보내고 JSON {ok, message} 를 받는다(틀려도 입력한 값이 창에 남게). """ @@ -68,6 +68,12 @@ def _can_add_host(user: dict[str, Any]) -> bool: return is_admin(user) or has_module(user, "live_host") +def _can_edit_host(user: dict[str, Any]) -> bool: + from app.store import has_module, is_admin # noqa: WPS433 + + return is_admin(user) or has_module(user, "live_host_edit") + + def _db(request: Request) -> Any: st = _store(request) if st is None: @@ -100,7 +106,8 @@ def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, An from app.store import is_admin # noqa: WPS433 lang = _lang(request) - return render_template(request, name, {"user": user, "is_admin": is_admin(user), "can_add_host": _can_add_host(user), "lang": lang, + 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), "nav_items": build_erp_nav(user, active="live"), **ctx}) @@ -260,29 +267,35 @@ def settings(request: Request) -> Any: if not isinstance(got, tuple): return got st, user = got - if not _can_add_host(user): + if not (_can_add_host(user) or _can_edit_host(user)): return render_template(request, "denied.html", {"reason": _t(request, "호스트 정보는 ERP 관리자만 볼 수 있습니다."), "is_admin": False}, status_code=403) - # host_choices = 이름·틱톡·상태뿐 — 계좌 등 개인정보는 관리자에게만 + # host_choices = 이름·상태뿐 — 계좌 등 개인정보는 칩이 있어도 관리자에게만 return _render(request, "live/settings.html", user, {"hosts": st.list_hosts() if is_admin(user) else st.host_choices()}) @router.post("/settings/hosts") -def host_save(request: Request, id: str = Form(""), full_name: str = Form(""), phone: str = Form(""), email: str = Form(""), +def host_save(request: Request, id: str = Form(""), display_name: str = Form(""), full_name: str = Form(""), phone: str = Form(""), email: str = Form(""), address: str = Form(""), bank_name: str = Form(""), bank_account: str = Form(""), is_active: str = Form("")) -> JSONResponse: from app.store import is_admin # noqa: WPS433 - # `live_host` 칩은 새 등록만 — id 가 있으면 고치기라 관리자 검사로 + # `live_host` 칩 = 새 등록, `live_host_edit` 칩 = 고치기(개인정보는 안 보이고, 비워 두면 그대로) user = _user(request) - if id.strip() or not _can_add_host(user): + if not (_can_edit_host(user) if id.strip() else _can_add_host(user)): _admin(request) st = _db(request) try: - values = store.clean_host({"full_name": full_name, "phone": phone, "email": email, "address": address, "bank_name": bank_name, + values = store.clean_host({"display_name": display_name, "full_name": full_name, "phone": phone, "email": email, "address": address, "bank_name": bank_name, "bank_account": bank_account}) - # 칩 권한자 화면엔 사용 여부 칸이 없다 — 항상 사용(사용 안 함으로 만들면 본인이 되돌릴 수 없음) - st.save_host(_opt_id(id), values, is_active=bool(is_active) or not is_admin(user), by=user.get("email", "")) + host_id = _opt_id(id) + if host_id is not None and not is_admin(user): # 개인정보를 못 보므로 빈칸 = 지우기가 아니라 그대로 + old = st.get_host(host_id) + if not old: + raise i18n.LiveError("호스트를 찾을 수 없습니다.") + values.update({k: values[k] or old[k] for k in store.PRIVATE_HOST_FIELDS}) + # 등록만 되는 칩 화면엔 사용 여부 칸이 없다 — 항상 사용(사용 안 함으로 만들면 본인이 되돌릴 수 없음) + st.save_host(host_id, values, is_active=bool(is_active) or not _can_edit_host(user), by=user.get("email", "")) except ValueError as exc: return _fail(request, exc) return _ok(request, "호스트를 저장했습니다.") diff --git a/app/modules/live/store.py b/app/modules/live/store.py index 7e8365f..c48c64e 100644 --- a/app/modules/live/store.py +++ b/app/modules/live/store.py @@ -25,9 +25,10 @@ _CENT = Decimal("0.01") _WEEKDAYS = ("MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY") _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} +HOST_LIMITS = {"display_name": 50, "full_name": 200, "phone": 40, "email": 254, "address": 500, "bank_name": 100, "bank_account": 40} HANDLE_LIMIT = 64 -_LABELS = {"full_name": "이름 (IC 기준)", "phone": "전화번호", "email": "이메일", "address": "주소", "bank_name": "은행명", +PRIVATE_HOST_FIELDS = ("phone", "email", "address", "bank_name", "bank_account") # 화면에 보이는 사람 = ERP 관리자만 +_LABELS = {"display_name": "간단한 이름", "full_name": "이름 (IC 기준)", "phone": "전화번호", "email": "이메일", "address": "주소", "bank_name": "은행명", "bank_account": "계좌번호"} _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]+$") @@ -45,8 +46,10 @@ def clean_handle(raw: Any) -> str: def clean_host(values: dict[str, Any]) -> dict[str, str]: - """호스트 입력 검사 — 이름만 필수, 나머지는 있으면 형식 확인. 틀리면 ValueError.""" + """호스트 입력 검사 — 간단한 이름·이름만 필수, 나머지는 있으면 형식 확인. 틀리면 ValueError.""" out = {k: str(values.get(k) or "").strip() for k in HOST_LIMITS} + if not out["display_name"]: + raise LiveError("간단한 이름을 입력하세요.") if not out["full_name"]: raise LiveError("이름 (IC 기준)을 입력하세요.") for key, limit in HOST_LIMITS.items(): @@ -156,7 +159,7 @@ def broadcast_view(b: dict[str, Any], lang: str = "ko") -> dict[str, Any]: "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"], - "label": b["tiktok_handle"] or b["host_name"], "color": HOST_COLORS[b["host_id"] % len(HOST_COLORS)], + "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"]), "edit": {"id": b["id"], "host_id": b["host_id"], "broadcast_date": b["broadcast_date"].isoformat(), diff --git a/app/modules/live/templates/live/_bar.html b/app/modules/live/templates/live/_bar.html index a2fb003..02198b0 100644 --- a/app/modules/live/templates/live/_bar.html +++ b/app/modules/live/templates/live/_bar.html @@ -11,7 +11,7 @@ {% include "live/_lang.html" %} - {% if can_add_host %}{{ t('호스트 설정') }}{% endif %} + {% if can_add_host or can_edit_host %}{{ t('호스트 설정') }}{% endif %} {% if not can_add %} diff --git a/app/modules/live/templates/live/_dialog.html b/app/modules/live/templates/live/_dialog.html index 3c0ed48..5fec8ff 100644 --- a/app/modules/live/templates/live/_dialog.html +++ b/app/modules/live/templates/live/_dialog.html @@ -6,7 +6,7 @@ diff --git a/app/modules/live/templates/live/_scripts.html b/app/modules/live/templates/live/_scripts.html index 95a5973..98ed789 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 b4596ec..b8fbb13 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시간 칸, 열 = 날짜, 맨 아래 = 날짜별 합계. 카드 머리 = Tiktok Handle(없으면 이름). +{#- 라이브 커머스 달력 보기(2026-11-04) — 줄 = 2시간 칸, 열 = 날짜, 맨 아래 = 날짜별 합계. 카드 머리 = 호스트 간단한 이름 + 그 방송의 틱톡 계정. 카드 머리를 끌어 빈 칸으로 옮기거나 다른 카드 위에 놓아 맞바꾼다(live.js). 문구 = t()(i18n.py), 영문은 CSS 로 대문자(받은 화면과 같게). -#} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
@@ -43,7 +43,7 @@
- {{ c.label }} + {{ c.label }}{% if c.tiktok_handle %}@{{ c.tiktok_handle }}{% endif %}
diff --git a/app/modules/live/templates/live/index.html b/app/modules/live/templates/live/index.html index ace6daf..ba26840 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 %}
diff --git a/app/modules/live/templates/live/settings.html b/app/modules/live/templates/live/settings.html index f8f3581..a1a6a15 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.js). 문구 = t()(i18n.py). -#} -{% block head_extra %}{% endblock %} +{#- 라이브 커머스 설정(2026-11-04) — 호스트 정보. 계좌 등 개인정보·지우기는 ERP 관리자만(router.settings), 칩 권한자는 이름·상태만 보임 — `live_host` = 새 등록, `live_host_edit` = 고치기(개인정보는 빈칸으로 열림, 비워 두면 그대로). 추가·고치기는 같은 창(live.js). 문구 = t()(i18n.py). -#} +{% block head_extra %}{% endblock %} {% block content %}
@@ -9,16 +9,17 @@

{{ t('호스트 설정') }}

{% include "live/_lang.html" %} - + {% if can_add_host %}{% endif %}
- {% if is_admin %}{% endif %}{% if is_admin %}{% endif %} + {% if is_admin %}{% endif %}{% if can_edit_host %}{% endif %} {% for h in hosts %} + {% if is_admin %} @@ -28,15 +29,20 @@ {% endif %} - {% if is_admin %} + {% if can_edit_host %} {% endif %} {% else %} - + {% endfor %}
{{ t('이름 (IC 기준)') }}{{ t('전화번호') }}{{ t('이메일') }}{{ t('주소') }}{{ t('은행명') }}{{ t('계좌번호') }}{{ t('상태') }}
{{ t('간단한 이름') }}{{ t('이름 (IC 기준)') }}{{ t('전화번호') }}{{ t('이메일') }}{{ t('주소') }}{{ t('은행명') }}{{ t('계좌번호') }}{{ t('상태') }}
{{ h.display_name }} {{ h.full_name }}{{ h.phone }}{{ h.bank_account }}{{ t('사용') if h.is_active else t('사용 안 함') }} - + {% if is_admin %} + + {% else %} + {#- 개인정보를 페이지에 싣지 않는다 -#} + + {% endif %}
{{ t('등록한 호스트가 없습니다.') }}
{{ t('등록한 호스트가 없습니다.') }}
@@ -48,7 +54,9 @@

+ + {% if not is_admin %}{% endif %} @@ -56,7 +64,7 @@
- {% if is_admin %}{% endif %} + {% if can_edit_host %}{% endif %}
diff --git a/app/static/live.css b/app/static/live.css index 79e5041..57bca78 100644 --- a/app/static/live.css +++ b/app/static/live.css @@ -66,6 +66,7 @@ .lv-card { margin-bottom: 4px; border: 1.5px solid #1f2937; border-radius: 6px; background: #fff; overflow: hidden; } .lv-card-head { display: flex; align-items: center; gap: 4px; padding: 3px 6px; border-bottom: 1px solid #1f2937; cursor: grab; } .lv-card-head:active { cursor: grabbing; } +.lv-card-name small { display: block; overflow: hidden; text-overflow: ellipsis; text-transform: none; font-size: 10px; font-weight: 600; letter-spacing: 0; } .lv-card-grip { font-size: 12px; color: #374151; } .lv-card-name { flex: 1 1 auto; min-width: 0; overflow: hidden; text-align: center; text-overflow: ellipsis; white-space: nowrap; text-transform: uppercase; font-size: 13px; font-weight: 800; letter-spacing: .03em; color: #111; } .lv-card-edit { padding: 0 2px; border: 0; background: none; color: #374151; font-size: 13px; cursor: pointer; } diff --git a/app/static/live.js b/app/static/live.js index 1dbe8c8..17ece6d 100644 --- a/app/static/live.js +++ b/app/static/live.js @@ -78,6 +78,7 @@ say(""); const editing = !!(row && row.id); title.textContent = editing ? title.dataset.edit : title.dataset.add; + form.querySelectorAll("[data-edit-only]").forEach(function (el) { el.hidden = !editing; }); form.elements.id.value = ""; Array.from(form.elements).forEach(function (el) { if (!row || !el.name || !(el.name in row)) return; diff --git a/app/store.py b/app/store.py index bd93eda..be76f06 100644 --- a/app/store.py +++ b/app/store.py @@ -41,6 +41,7 @@ MODULE_KEYS: tuple[str, ...] = ( "outreach", "live", "live_host", + "live_host_edit", "expense_approver", "vacation_approver", ) diff --git a/docs/DATABASES.md b/docs/DATABASES.md index 00e28f0..0e182f7 100644 --- a/docs/DATABASES.md +++ b/docs/DATABASES.md @@ -312,7 +312,7 @@ DDL: `scripts/sql/live_db_init.sql` (멱등). DB·역할(`live_app`)·테이블 | 테이블 | 용도 | | --- | --- | -| `live_hosts` | 호스트 — Full Name (as per IC)·Phone Number·Email·Address·Bank Name·Bank Account Number, `is_active`. `tiktok_handle` 열은 값만 남아 있고 쓰지 않음(003) | +| `live_hosts` | 호스트 — `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_broadcast_images` | 방송 결과 이미지(메타데이터 제거 후 BYTEA, 방송을 지우면 CASCADE) — 방송당 최대 10장(앱에서 확인) | | `live_daily_ad_spend` | 날짜별 광고비(RM) — 달력 보기 AD SPEND·ROAS. 마이그레이션 `live_db_002_ad_spend.sql`(init 에도 포함) | diff --git a/scripts/sql/live_db_004_host_display_name.sql b/scripts/sql/live_db_004_host_display_name.sql new file mode 100644 index 0000000..3334203 --- /dev/null +++ b/scripts/sql/live_db_004_host_display_name.sql @@ -0,0 +1,17 @@ +-- ===================================================================== +-- live_db 마이그레이션 004 — 호스트 간단한 이름(달력 카드·방송 창·스케줄표 표시용)(2026-11-05) +-- ===================================================================== +-- 왜: Full Name (as per IC)은 길고, 말레이 이름은 끝이 아버지 이름이라 자동으로 줄일 수 없다. 사람이 직접 입력한다. +-- 멱등(idempotent). 열 하나만 추가(기존 값 변경 없음). 비어 있는 호스트는 화면에 Full Name 이 그대로 보인다. +-- 운영: /opt/www/main 에서 기존 live_db 에 앱 배포 전에 적용(백업 먼저, 003 다음). +-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d live_db < scripts/sql/live_db_004_host_display_name.sql +-- 되돌리기: ALTER TABLE live_hosts DROP COLUMN display_name; (간단한 이름만 사라짐 — 실행 전 백업) +-- ===================================================================== +\set ON_ERROR_STOP on +BEGIN; + +ALTER TABLE live_hosts ADD COLUMN IF NOT EXISTS display_name TEXT NOT NULL DEFAULT ''; +COMMENT ON COLUMN live_hosts.display_name IS '간단한 이름 — 비어 있으면 화면은 full_name'; + +COMMIT; +SELECT 'live_db 004 host display name ready' AS status, count(*) AS hosts, count(*) FILTER (WHERE display_name <> '') AS named FROM live_hosts; diff --git a/scripts/sql/live_db_init.sql b/scripts/sql/live_db_init.sql index 73b167a..5239d5a 100644 --- a/scripts/sql/live_db_init.sql +++ b/scripts/sql/live_db_init.sql @@ -52,6 +52,7 @@ CREATE TABLE IF NOT EXISTS live_hosts ( address TEXT NOT NULL DEFAULT '', bank_name TEXT NOT NULL DEFAULT '', bank_account TEXT NOT NULL DEFAULT '', + display_name TEXT NOT NULL DEFAULT '', -- 간단한 이름(004), 비면 화면은 full_name tiktok_handle TEXT NOT NULL DEFAULT '', -- 쓰지 않음(003 부터 방송별 live_broadcasts.tiktok_handle) is_active BOOLEAN NOT NULL DEFAULT TRUE, -- FALSE = 새 방송에서 못 고름 created_by TEXT NOT NULL DEFAULT '', diff --git a/tests/test_live.py b/tests/test_live.py index e6a26c4..e5b5173 100644 --- a/tests/test_live.py +++ b/tests/test_live.py @@ -60,13 +60,14 @@ def _run(code: str, extra_env: dict[str, str] | None = None) -> subprocess.Compl 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", + got = store.clean_host({"display_name": " Siti ", "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"], "Siti Aisyah") + self.assertEqual((got["display_name"], got["full_name"]), ("Siti", "Siti Aisyah")) self.assertNotIn("tiktok_handle", got) # 계정은 방송마다 — 호스트에는 저장 안 함 - 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": "x" * 201}): + self.assertEqual(store.clean_host({"display_name": "A", "full_name": "A"})["phone"], "") # 두 이름만 필수 + ok = {"display_name": "A", "full_name": "A"} + for bad in ({}, {"full_name": "A"}, {"display_name": "A"}, {**ok, "full_name": " "}, {**ok, "email": "nope"}, {**ok, "phone": "abc"}, + {**ok, "bank_account": "12a"}, {**ok, "full_name": "x" * 201}, {**ok, "display_name": "x" * 51}): with self.assertRaises(ValueError, msg=bad): store.clean_host(bad) @@ -82,7 +83,7 @@ class StoreTests(unittest.TestCase): """고치기 창에 계정이 채워져야 저장하면서 지워지지 않는다.""" 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": []}) - self.assertEqual((view["tiktok_handle"], view["edit"]["tiktok_handle"], view["label"]), ("alt.acc", "alt.acc", "alt.acc")) + self.assertEqual((view["tiktok_handle"], view["edit"]["tiktok_handle"], view["label"]), ("alt.acc", "alt.acc", "Yaya")) # 카드 머리 = 호스트, 계정은 아래 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"): @@ -167,7 +168,7 @@ class StoreTests(unittest.TestCase): self.assertEqual(cal["days"][6]["is_weekend"], True) # 11-07 토 self.assertEqual(cal["days"][0]["roas"], "-") # 광고비 없음 noon = next(s for s in cal["slots"] if s["start"] == "12:00") - self.assertEqual(noon["cells"][3]["cards"][0]["label"], "yaya") # 카드 머리 = Tiktok Handle + self.assertEqual(noon["cells"][3]["cards"][0]["label"], "Yaya") # 카드 머리 = 호스트 간단한 이름 self.assertEqual((noon["cells"][3]["cards"][0]["card_sales"], noon["cells"][3]["cards"][0]["card_commission"], noon["cells"][3]["cards"][0]["card_fee"]), ("48", "4.80", "54.80")) late = next(s for s in cal["slots"] if s["start"] == "22:00") @@ -240,9 +241,9 @@ assert "live_host" in MODULE_KEYS and "live_host" in main.MODULE_LABELS class Fake: saved = [] def host_choices(self): - return [{"id": 1, "full_name": "Siti", "is_active": True}] + return [{"id": 1, "display_name": "Siti", "full_name": "Siti Binti Awa", "is_active": True}] def list_hosts(self): - return [{"id": 1, "full_name": "Siti", "phone": "012", "email": "s@e.my", "address": "KL", "bank_name": "Maybank", + return [{"id": 1, "display_name": "Siti", "full_name": "Siti Binti Awa", "phone": "012", "email": "s@e.my", "address": "KL", "bank_name": "Maybank", "bank_account": "998877", "is_active": True}] def list_broadcasts(self, start, end): return [] @@ -257,7 +258,7 @@ class Fake: fake = main.app.state.live_store = Fake() adder = U("adder@t.local"); adder["modules"]["live_host"] = True chip_only = U("chip@t.local", live=False); chip_only["modules"]["live_host"] = True -new = {"full_name": "New Host", "bank_account": "111"} +new = {"display_name": "Newbie", "full_name": "New Host", "bank_account": "111"} def body(c): who["u"] = adder @@ -287,6 +288,74 @@ def body(c): assert fake.saved[-1] == (1, "New Host", False, "a@t.local"), fake.saved print("OK") run(body) +''') + self.assertEqual(res.returncode, 0, res.stdout + res.stderr) + self.assertIn("OK", res.stdout) + + def test_live_host_edit_chip(self): + """`live_host_edit` 칩 = 고치기 — 개인정보는 페이지에 없고, 빈칸은 그대로·입력하면 바뀜, 등록·지우기는 안 됨.""" + res = _run(''' +from app.store import MODULE_KEYS +assert "live_host_edit" in MODULE_KEYS and main.MODULE_LABELS["live_host_edit"] == "라이브 호스트 수정" + +OLD = {"id": 1, "display_name": "Siti", "full_name": "Siti Binti Awa", "phone": "012", "email": "s@e.my", "address": "KL", "bank_name": "Maybank", + "bank_account": "998877", "is_active": True} + +class Fake: + saved = [] + def host_choices(self): + return [{k: OLD[k] for k in ("id", "display_name", "full_name", "is_active")}] + def list_hosts(self): + return [OLD] + def get_host(self, host_id): + return OLD if host_id == 1 else None + def list_broadcasts(self, start, end): + return [] + def account_choices(self): + return [] + def save_host(self, host_id, values, *, is_active, by): + self.saved.append((host_id, values, is_active)) + return 1 + def delete_host(self, host_id): + self.saved.append(("deleted", host_id)) + +fake = main.app.state.live_store = Fake() +editor = U("edit@t.local"); editor["modules"]["live_host_edit"] = True +chip_only = U("chip@t.local", live=False); chip_only["modules"]["live_host_edit"] = True +form = {"id": "1", "display_name": "Nabella", "full_name": "Siti Binti Awa", "is_active": "1"} + +def body(c): + who["u"] = editor + assert \'href="/live/settings"\' in c.get("/live/").text + page = c.get("/live/settings").text + for hidden in ("998877", "Maybank", "s@e.my", "/delete", \'id="lv-add"\'): + assert hidden not in page, hidden + assert "data-edit=\'" in page and "Siti Binti Awa" in page and \'name="is_active"\' in page and "data-edit-only" in page + + assert c.post("/live/settings/hosts", data=form).json()["ok"] + host_id, values, active = fake.saved[-1] + assert host_id == 1 and active is True and values["display_name"] == "Nabella" + assert (values["bank_account"], values["phone"], values["address"]) == ("998877", "012", "KL") # 빈칸 = 그대로 + assert c.post("/live/settings/hosts", data={**form, "bank_account": "111-222"}).json()["ok"] + assert fake.saved[-1][1]["bank_account"] == "111-222" and fake.saved[-1][1]["phone"] == "012" # 입력 = 바뀜 + assert c.post("/live/settings/hosts", data={**form, "is_active": ""}).json()["ok"] and fake.saved[-1][2] is False + assert c.post("/live/settings/hosts", data={**form, "id": "9"}).status_code == 400 # 없는 호스트 + assert c.post("/live/settings/hosts", data={**form, "display_name": ""}).status_code == 400 # 간단한 이름 필수 + + count = len(fake.saved) + assert c.post("/live/settings/hosts", data={**form, "id": ""}).status_code == 403 # 등록 권한 없음 + assert c.post("/live/settings/hosts/1/delete").status_code == 403 + for no_edit in (U("staff@t.local"), chip_only): + who["u"] = no_edit + assert c.get("/live/settings").status_code == 403 + assert c.post("/live/settings/hosts", data=form).status_code == 403 + assert len(fake.saved) == count + + # 관리자는 빈칸 = 지우기 그대로 + who["u"] = U("a@t.local", role="admin") + assert c.post("/live/settings/hosts", data=form).json()["ok"] and fake.saved[-1][1]["bank_account"] == "" + print("OK") +run(body) ''') self.assertEqual(res.returncode, 0, res.stdout + res.stderr) self.assertIn("OK", res.stdout) @@ -332,7 +401,7 @@ def jpeg(): return raw.getvalue() def body(c): - host = {"full_name": NAME, "phone": "+60 12-345", "email": "siti@example.my", "address": "Kuala Lumpur", + host = {"display_name": "S" + tag, "full_name": NAME, "phone": "+60 12-345", "email": "siti@example.my", "address": "Kuala Lumpur", "bank_name": "Maybank", "bank_account": ACCOUNT, "is_active": "1"} # ── 호스트 설정 = ERP 관리자만 ── who["u"] = staff @@ -397,7 +466,7 @@ def body(c): 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 "날짜로 이동" in cal and "토요일" in cal and "12:00 - 14:00" in cal and "2시간 (기본 RM50)" in cal - assert 'siti.%s' % tag in cal and "RM54.80" in cal and ">4.80" in cal + assert 'S%s@siti.%s' % (tag, tag) in cal and "RM54.80" in cal and ">4.80" in cal # ── 영문: 화면 세 개 모두 한글 없음(입력한 데이터 제외)·날짜·오류·권한 문구 ── def no_korean(url):