Merge branch 'feat/live-host-platform'
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 코드가 기준.
|
||||
> 정적 파일: `app/static/live.js`, `live.css`. 템플릿: `templates/live/`. 테스트: `tests/test_live.py`(`LIVE_TEST_DB_URL` 이 localhost 일 때 실제 DB).
|
||||
> 다른 모듈과 연결: 이미지 검사 = 자산 모듈 `app/modules/asset/media.py prepare_photo` 재사용(바꾸면 양쪽 확인).
|
||||
> 다른 모듈과 연결: 이미지 검사 = 자산 모듈 `app/modules/asset/media.py prepare_photo` 재사용(바꾸면 양쪽 확인). 쇼핑몰 로고 = 말레이시아 배송 모듈 `app/static/dispatch/courier/tiktok.png`·`shopee.png`(지우거나 이름을 바꾸면 호스트 설정 로고도 깨짐).
|
||||
|
||||
- 말레이시아 라이브 커머스 방송의 호스트 정보·방송 스케줄. 권한키 `live`, DB `LIVE_DB_URL`(없으면 "설정 필요" 안내).
|
||||
- **호스트 설정** `/live/settings` — 간단한 이름(필수, `display_name`, 마이그레이션 004 — 말레이 이름은 끝이 아버지 이름이라 자동으로 줄이지 않고 사람이 입력, 빈 예전 호스트는 화면에 Full Name)·Full Name (as per IC)(필수)·Phone Number·Email·Address·Bank Name·Bank Account Number.
|
||||
@@ -10,6 +10,8 @@
|
||||
**틱톡 계정은 호스트가 아니라 방송마다**(2026-11-05, 마이그레이션 003 `live_broadcasts.tiktok_handle`) — 호스트가 여러 계정에서 방송하므로. 방송 창에서 입력(선택), `@`·주소를 붙여 넣어도 계정명만 저장, 쓴 적 있는 계정을 제안(`db.account_choices`). `live_hosts.tiktok_handle` 은 값만 남아 있고 안 씀. 달력에서 옮기거나 맞바꿔도 계정은 그 방송에 그대로. 달력 카드 머리·스케줄표·방송 창의 호스트 = 간단한 이름, 카드 머리 아래 작은 글자 = 계정.
|
||||
**`live_host_edit` 칩**(+ `live`, 관리자 페이지 토글) = 호스트 **고치기**(사용 여부 포함): 지우기 불가, 개인정보는 페이지에 싣지 않아 빈칸으로 열리고 비워 두면 그대로·입력하면 바뀜(이 칩으로는 지울 수 없음).
|
||||
**`live_host` 칩**(+ `live` 칩 필요) = 새 호스트 **등록만**: 설정 화면에 이름·상태만 보이고, 입력한 계좌 등은 저장 후 못 봄. 고치기·지우기 불가, 사용 여부 못 고름(항상 사용).
|
||||
**쇼핑몰**(2026-11-06, 마이그레이션 005 `live_hosts.platform`, `store.PLATFORMS` = tiktok·shopee) — 창 맨 위 라디오 + 로고(같은 상자 88×26, 안 고르면 흑백·고르면 컬러), 저장 때 필수. 목록 첫 열 = 로고. 예전 호스트는 빈 값(고치기에서 고르면 저장).
|
||||
**목록의 사용 토글**(`POST /live/settings/hosts/{id}/active`, `db.set_host_active`) = 고치기 권한(관리자·`live_host_edit` 칩)만, 바로 저장·실패하면 되돌림. 권한 없으면 글자(사용/사용 안 함).
|
||||
사용 안 함 = 새 방송에서 못 고름(그 호스트로 이미 등록된 방송을 고칠 때만 보임). 방송 기록이 있는 호스트는 못 지움(FK RESTRICT).
|
||||
- **스케줄표** `/live/?month=YYYY-MM`(`live` 권한자 모두) — 호스트·날짜·시작/끝 시간·방송 장소·판매금액·커미션·호스트 비용·결과 이미지. 호스트·날짜·시작·끝 시간 필수(판매금액은 방송 후 입력).
|
||||
시간은 입력한 말레이시아 시간 그대로(시간대 변환 없음, DATE·TIME). 판매금액 단위 RM(`NUMERIC(14,2)`, `store.parse_money`). 끝 시간이 시작보다 이르면 자정을 넘긴 방송.
|
||||
|
||||
+12
-5
@@ -18,7 +18,7 @@ from psycopg_pool import ConnectionPool
|
||||
from . import store
|
||||
from .i18n import LiveError
|
||||
|
||||
_HOST_COLUMNS = ("display_name", "full_name", "phone", "email", "address", "bank_name", "bank_account")
|
||||
_HOST_COLUMNS = ("platform", "display_name", "full_name", "phone", "email", "address", "bank_name", "bank_account")
|
||||
|
||||
|
||||
class LiveDBStore:
|
||||
@@ -39,7 +39,7 @@ class LiveDBStore:
|
||||
def host_choices(self) -> list[dict[str, Any]]:
|
||||
"""스케줄 화면 호스트 고르기 — 개인정보·계좌는 뺀다."""
|
||||
with self._pool.connection() as conn:
|
||||
return conn.execute("SELECT id, display_name, full_name, is_active FROM live_hosts ORDER BY full_name, id").fetchall()
|
||||
return conn.execute("SELECT id, platform, 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:
|
||||
@@ -56,18 +56,25 @@ class LiveDBStore:
|
||||
with self._pool.connection() as conn:
|
||||
if host_id is None:
|
||||
row = conn.execute(
|
||||
"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",
|
||||
"INSERT INTO live_hosts (platform, 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,%s) RETURNING id",
|
||||
(*cols, is_active, by, by)).fetchone()
|
||||
else:
|
||||
row = conn.execute(
|
||||
"UPDATE live_hosts SET display_name=%s, full_name=%s, phone=%s, email=%s, address=%s, bank_name=%s, bank_account=%s, "
|
||||
"UPDATE live_hosts SET platform=%s, 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:
|
||||
raise LiveError("호스트를 찾을 수 없습니다.")
|
||||
return int(row["id"])
|
||||
|
||||
def set_host_active(self, host_id: int, is_active: bool, *, by: str) -> None:
|
||||
"""목록의 사용 토글 — 사용 여부만 바꾼다."""
|
||||
with self._pool.connection() as conn:
|
||||
if not conn.execute("UPDATE live_hosts SET is_active=%s, updated_by=%s WHERE id=%s RETURNING id",
|
||||
(is_active, by, host_id)).fetchone():
|
||||
raise LiveError("호스트를 찾을 수 없습니다.")
|
||||
|
||||
def delete_host(self, host_id: int) -> None:
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
|
||||
@@ -41,6 +41,8 @@ EN: dict[str, str] = {
|
||||
"계좌번호": "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)",
|
||||
"쇼핑몰": "Platform", "쇼핑몰(틱톡·쇼피)을 고르세요.": "Choose the platform (TikTok or Shopee).",
|
||||
"사용으로 바꿨습니다.": "Set to active.", "사용 안 함으로 바꿨습니다.": "Set to inactive.",
|
||||
# 화면 스크립트(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",
|
||||
|
||||
@@ -276,7 +276,7 @@ def settings(request: Request) -> Any:
|
||||
|
||||
|
||||
@router.post("/settings/hosts")
|
||||
def host_save(request: Request, id: str = Form(""), display_name: str = Form(""), full_name: str = Form(""), phone: str = Form(""), email: str = Form(""),
|
||||
def host_save(request: Request, id: str = Form(""), platform: 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
|
||||
@@ -287,7 +287,7 @@ def host_save(request: Request, id: str = Form(""), display_name: str = Form("")
|
||||
_admin(request)
|
||||
st = _db(request)
|
||||
try:
|
||||
values = store.clean_host({"display_name": display_name, "full_name": full_name, "phone": phone, "email": email, "address": address, "bank_name": bank_name,
|
||||
values = store.clean_host({"platform": platform, "display_name": display_name, "full_name": full_name, "phone": phone, "email": email, "address": address, "bank_name": bank_name,
|
||||
"bank_account": bank_account})
|
||||
host_id = _opt_id(id)
|
||||
if host_id is not None and not is_admin(user): # 개인정보를 못 보므로 빈칸 = 지우기가 아니라 그대로
|
||||
@@ -302,6 +302,19 @@ def host_save(request: Request, id: str = Form(""), display_name: str = Form("")
|
||||
return _ok(request, "호스트를 저장했습니다.")
|
||||
|
||||
|
||||
@router.post("/settings/hosts/{host_id}/active")
|
||||
def host_active(request: Request, host_id: int, is_active: str = Form("")) -> JSONResponse:
|
||||
"""목록의 사용 토글 — 고치기 권한(ERP 관리자·`live_host_edit` 칩)."""
|
||||
user = _user(request)
|
||||
if not _can_edit_host(user):
|
||||
_admin(request)
|
||||
try:
|
||||
_db(request).set_host_active(host_id, is_active == "1", by=user.get("email", ""))
|
||||
except ValueError as exc:
|
||||
return _fail(request, exc)
|
||||
return _ok(request, "사용으로 바꿨습니다." if is_active == "1" else "사용 안 함으로 바꿨습니다.")
|
||||
|
||||
|
||||
@router.post("/settings/hosts/{host_id}/delete")
|
||||
def host_delete(request: Request, host_id: int) -> JSONResponse:
|
||||
_admin(request)
|
||||
|
||||
@@ -27,6 +27,7 @@ _MONTHS = ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT",
|
||||
|
||||
HOST_LIMITS = {"display_name": 50, "full_name": 200, "phone": 40, "email": 254, "address": 500, "bank_name": 100, "bank_account": 40}
|
||||
HANDLE_LIMIT = 64
|
||||
PLATFORMS = ("tiktok", "shopee") # 호스트 쇼핑몰(005) — 로고 = /static/dispatch/courier/<값>.png(말레이시아 배송 모듈 이미지)
|
||||
PRIVATE_HOST_FIELDS = ("phone", "email", "address", "bank_name", "bank_account") # 화면에 보이는 사람 = ERP 관리자만
|
||||
_LABELS = {"display_name": "간단한 이름", "full_name": "이름 (IC 기준)", "phone": "전화번호", "email": "이메일", "address": "주소", "bank_name": "은행명",
|
||||
"bank_account": "계좌번호"}
|
||||
@@ -46,8 +47,11 @@ 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}
|
||||
out["platform"] = str(values.get("platform") or "").strip().lower()
|
||||
if out["platform"] not in PLATFORMS:
|
||||
raise LiveError("쇼핑몰(틱톡·쇼피)을 고르세요.")
|
||||
if not out["display_name"]:
|
||||
raise LiveError("간단한 이름을 입력하세요.")
|
||||
if not out["full_name"]:
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
<script>window.LV_T = {{ js_text | tojson }};</script>
|
||||
<script src="/static/live.js?v=20261105c" defer></script>
|
||||
<script src="/static/live.js?v=20261106a" defer></script>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{#- 라이브 커머스 달력 보기(2026-11-04) — 줄 = 2시간 칸, 열 = 날짜, 맨 아래 = 날짜별 합계. 카드 머리 = 호스트 간단한 이름 + 그 방송의 틱톡 계정.
|
||||
카드 머리를 끌어 빈 칸으로 옮기거나 다른 카드 위에 놓아 맞바꾼다(live.js). 문구 = t()(i18n.py), 영문은 CSS 로 대문자(받은 화면과 같게). -#}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261105e" />
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261106a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<link rel="stylesheet" href="/static/erp-datepop.css?v=20261102a" />{% endblock %}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{#- 라이브 커머스 스케줄표(2026-11-04) — 달마다 방송 목록. 추가·고치기 창은 달력과 공용(_dialog.html, live.js). 문구 = t()(i18n.py). -#}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261105e" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261106a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="lv" lang="{{ lang }}">
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{#- 라이브 커머스 설정(2026-11-04) — 호스트 정보. 계좌 등 개인정보·지우기는 ERP 관리자만(router.settings), 칩 권한자는 이름·상태만 보임 — `live_host` = 새 등록, `live_host_edit` = 고치기(개인정보는 빈칸으로 열림, 비워 두면 그대로). 추가·고치기는 같은 창(live.js). 문구 = t()(i18n.py). -#}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261105e" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261106a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{#- 쇼핑몰(005, store.PLATFORMS) — 로고는 말레이시아 배송 모듈 이미지 -#}
|
||||
{% set platform_names = {"tiktok": "TikTok", "shopee": "Shopee"} %}
|
||||
<section class="lv" lang="{{ lang }}">
|
||||
<div class="lv-bar">
|
||||
<a class="erp-btn erp-btn-outline" href="/live/">{{ t('◀ 스케줄표') }}</a>
|
||||
@@ -15,10 +17,11 @@
|
||||
<div class="erp-card-block">
|
||||
<div class="erp-table-wrap">
|
||||
<table class="erp-table lv-table">
|
||||
<thead><tr><th>{{ t('간단한 이름') }}</th><th>{{ t('이름 (IC 기준)') }}</th>{% if is_admin %}<th>{{ t('전화번호') }}</th><th>{{ t('이메일') }}</th><th>{{ t('주소') }}</th><th>{{ t('은행명') }}</th><th>{{ t('계좌번호') }}</th>{% endif %}<th>{{ t('상태') }}</th>{% if can_edit_host %}<th></th>{% endif %}</tr></thead>
|
||||
<thead><tr><th>{{ t('쇼핑몰') }}</th><th>{{ t('간단한 이름') }}</th><th>{{ t('이름 (IC 기준)') }}</th>{% if is_admin %}<th>{{ t('전화번호') }}</th><th>{{ t('이메일') }}</th><th>{{ t('주소') }}</th><th>{{ t('은행명') }}</th><th>{{ t('계좌번호') }}</th>{% endif %}<th>{{ t('상태') }}</th>{% if can_edit_host %}<th></th>{% endif %}</tr></thead>
|
||||
<tbody>
|
||||
{% for h in hosts %}
|
||||
<tr{% if not h.is_active %} class="lv-off"{% endif %}>
|
||||
<td data-label="{{ t('쇼핑몰') }}">{% if h.platform %}<img class="lv-logo" src="/static/dispatch/courier/{{ h.platform }}.png" alt="{{ platform_names[h.platform] }}" title="{{ platform_names[h.platform] }}" />{% endif %}</td>
|
||||
<td data-label="{{ t('간단한 이름') }}">{{ h.display_name }}</td>
|
||||
<td data-label="{{ t('이름 (IC 기준)') }}">{{ h.full_name }}</td>
|
||||
{% if is_admin %}
|
||||
@@ -28,21 +31,25 @@
|
||||
<td data-label="{{ t('은행명') }}">{{ h.bank_name }}</td>
|
||||
<td class="lv-nowrap" data-label="{{ t('계좌번호') }}">{{ h.bank_account }}</td>
|
||||
{% endif %}
|
||||
{% if can_edit_host %}
|
||||
<td data-label="{{ t('상태') }}"><label class="erp-switch" title="{{ t('사용') }}"><input type="checkbox" data-active="/live/settings/hosts/{{ h.id }}/active" aria-label="{{ t('사용') }} — {{ h.display_name or h.full_name }}"{% if h.is_active %} checked{% endif %} /><span class="erp-switch-slider"></span></label></td>
|
||||
{% else %}
|
||||
<td class="lv-nowrap" data-label="{{ t('상태') }}">{{ t('사용') if h.is_active else t('사용 안 함') }}</td>
|
||||
{% endif %}
|
||||
{% if can_edit_host %}
|
||||
<td class="lv-actions">
|
||||
{% if is_admin %}
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-edit='{{ {"id": h.id, "display_name": h.display_name, "full_name": h.full_name, "phone": h.phone, "email": h.email, "address": h.address, "bank_name": h.bank_name, "bank_account": h.bank_account, "is_active": h.is_active} | tojson }}'>{{ t('고치기') }}</button>
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-edit='{{ {"id": h.id, "platform": h.platform, "display_name": h.display_name, "full_name": h.full_name, "phone": h.phone, "email": h.email, "address": h.address, "bank_name": h.bank_name, "bank_account": h.bank_account, "is_active": h.is_active} | tojson }}'>{{ t('고치기') }}</button>
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-post="/live/settings/hosts/{{ h.id }}/delete" data-confirm="{{ t('{name} 호스트를 지울까요?').format(name=h.full_name) }}">{{ t('지우기') }}</button>
|
||||
{% else %}
|
||||
{#- 개인정보를 페이지에 싣지 않는다 -#}
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-edit='{{ {"id": h.id, "display_name": h.display_name, "full_name": h.full_name, "is_active": h.is_active} | tojson }}'>{{ t('고치기') }}</button>
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-edit='{{ {"id": h.id, "platform": h.platform, "display_name": h.display_name, "full_name": h.full_name, "is_active": h.is_active} | tojson }}'>{{ t('고치기') }}</button>
|
||||
{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="{{ 9 if is_admin else 4 if can_edit_host else 3 }}" class="erp-empty">{{ t('등록한 호스트가 없습니다.') }}</td></tr>
|
||||
<tr><td colspan="{{ 10 if is_admin else 5 if can_edit_host else 4 }}" class="erp-empty">{{ t('등록한 호스트가 없습니다.') }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -54,6 +61,12 @@
|
||||
<form id="lv-form" action="/live/settings/hosts">
|
||||
<h3 id="lv-dlg-title" data-add="{{ t('호스트 등록') }}" data-edit="{{ t('호스트 고치기') }}"></h3>
|
||||
<input type="hidden" name="id" />
|
||||
<fieldset class="lv-platforms">
|
||||
<legend>{{ t('쇼핑몰') }}</legend>
|
||||
{% for p, name in platform_names.items() %}
|
||||
<label class="lv-platform"><input type="radio" name="platform" value="{{ p }}" required /><img class="lv-logo" src="/static/dispatch/courier/{{ p }}.png" alt="{{ name }}" /></label>
|
||||
{% endfor %}
|
||||
</fieldset>
|
||||
<label class="lv-field">{{ t('간단한 이름') }} <input class="erp-input" type="text" name="display_name" maxlength="50" required /></label>
|
||||
<label class="lv-field">{{ t('이름 (IC 기준)') }} <input class="erp-input" type="text" name="full_name" maxlength="200" required /></label>
|
||||
{% if not is_admin %}<p class="lv-sub" data-edit-only hidden>{{ t('개인정보는 보이지 않습니다. 비워 두면 그대로 유지됩니다.') }}</p>{% endif %}
|
||||
|
||||
@@ -127,6 +127,15 @@
|
||||
.lv-row { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
.lv-row .lv-field { flex-basis: 140px; }
|
||||
.lv-check { display: flex; align-items: center; gap: 6px; font-size: 13px; }
|
||||
/* 쇼핑몰 로고(말레이시아 배송 모듈 이미지) — 두 로고 같은 상자 크기. 창: 안 고르면 흑백, 고르면 컬러 */
|
||||
.lv-logo { display: block; width: 88px; height: 26px; object-fit: contain; }
|
||||
.lv-platforms { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 24px; margin: 0; padding: 0; border: 0; }
|
||||
.lv-platforms legend { width: 100%; margin-bottom: 6px; padding: 0; font-size: 13px; font-weight: 500; }
|
||||
.lv-platform { display: flex; align-items: center; gap: 8px; cursor: pointer; }
|
||||
.lv-platform input { margin: 0; accent-color: var(--color-deep-black, #000); }
|
||||
.lv-platform .lv-logo { filter: grayscale(1); opacity: .45; transition: filter .15s, opacity .15s; }
|
||||
.lv-platform input:checked + .lv-logo { filter: none; opacity: 1; }
|
||||
.lv-table .erp-switch input:focus-visible + .erp-switch-slider { outline: 2px solid var(--color-deep-black, #000); outline-offset: 2px; }
|
||||
.lv-saved { display: flex; flex-direction: column; gap: 6px; margin: 0; padding: 0; list-style: none; font-size: 13px; }
|
||||
.lv-saved li { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.lv-saved a { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
@@ -84,6 +84,7 @@
|
||||
Array.from(form.elements).forEach(function (el) {
|
||||
if (!row || !el.name || !(el.name in row)) return;
|
||||
if (el.type === "checkbox") el.checked = !!row[el.name];
|
||||
else if (el.type === "radio") el.checked = el.value === row[el.name];
|
||||
else if (el.type !== "file") el.value = row[el.name];
|
||||
});
|
||||
showHosts(editing && row.host_id);
|
||||
@@ -111,6 +112,22 @@
|
||||
if (dlg.open) say(r.message); else window.erpAlert(r.message, dialogText());
|
||||
});
|
||||
|
||||
// 호스트 목록의 사용 토글 — 바로 저장, 실패하면 되돌림. 줄 흐림(lv-off)만 바꾸고 다시 그리지 않음
|
||||
document.addEventListener("change", async function (e) {
|
||||
const sw = e.target.closest("input[data-active]");
|
||||
if (!sw) return;
|
||||
const body = new FormData();
|
||||
body.set("is_active", sw.checked ? "1" : "0");
|
||||
sw.disabled = true;
|
||||
const r = await post(sw.dataset.active, body);
|
||||
sw.disabled = false;
|
||||
if (!r.ok) { sw.checked = !sw.checked; window.erpAlert(r.message, dialogText()); return; }
|
||||
const line = sw.closest("tr");
|
||||
line.classList.toggle("lv-off", !sw.checked);
|
||||
const edit = line.querySelector("[data-edit]"); // 고치기 창이 옛 값으로 열려 저장 때 되돌리지 않게
|
||||
if (edit) { const row = JSON.parse(edit.dataset.edit); row.is_active = sw.checked; edit.dataset.edit = JSON.stringify(row); }
|
||||
});
|
||||
|
||||
form.addEventListener("submit", async function (e) {
|
||||
e.preventDefault();
|
||||
const save = form.querySelector('button[type="submit"]');
|
||||
|
||||
+1
-1
@@ -312,7 +312,7 @@ DDL: `scripts/sql/live_db_init.sql` (멱등). DB·역할(`live_app`)·테이블
|
||||
|
||||
| 테이블 | 용도 |
|
||||
| --- | --- |
|
||||
| `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_hosts` | 호스트 — `platform`(쇼핑몰 `tiktok`·`shopee`, `''` = 예전 호스트, 마이그레이션 `live_db_005_host_platform.sql`)·`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 에도 포함) |
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
-- =====================================================================
|
||||
-- live_db 마이그레이션 005 — 호스트 쇼핑몰(틱톡·쇼피)(2026-11-06)
|
||||
-- =====================================================================
|
||||
-- 왜: 호스트가 틱톡 호스트인지 쇼피 호스트인지 설정 화면에서 고르고 목록 첫 열에 로고로 보인다.
|
||||
-- 멱등(idempotent). 열 하나만 추가(기존 값 변경 없음). 예전 호스트는 '' (고치기에서 고르면 저장).
|
||||
-- 운영: /opt/www/main 에서 기존 live_db 에 앱 배포 전에 적용(백업 먼저, 004 다음).
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d live_db < scripts/sql/live_db_005_host_platform.sql
|
||||
-- 되돌리기: ALTER TABLE live_hosts DROP COLUMN platform; (쇼핑몰 값만 사라짐 — 실행 전 백업)
|
||||
-- =====================================================================
|
||||
\set ON_ERROR_STOP on
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE live_hosts ADD COLUMN IF NOT EXISTS platform TEXT NOT NULL DEFAULT ''
|
||||
CHECK (platform IN ('', 'tiktok', 'shopee'));
|
||||
COMMENT ON COLUMN live_hosts.platform IS '쇼핑몰 — tiktok·shopee, 빈 값 = 예전 호스트(아직 안 고름)';
|
||||
|
||||
COMMIT;
|
||||
SELECT 'live_db 005 host platform ready' AS status, count(*) AS hosts, count(*) FILTER (WHERE platform <> '') AS chosen FROM live_hosts;
|
||||
@@ -54,6 +54,7 @@ CREATE TABLE IF NOT EXISTS live_hosts (
|
||||
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)
|
||||
platform TEXT NOT NULL DEFAULT '' CHECK (platform IN ('', 'tiktok', 'shopee')), -- 쇼핑몰(005), '' = 아직 안 고름
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE, -- FALSE = 새 방송에서 못 고름
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
|
||||
+32
-15
@@ -60,13 +60,13 @@ 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({"display_name": " Siti ", "full_name": " Siti Aisyah ", "phone": "+60 12-345 6789", "email": "siti@example.my", "address": "KL",
|
||||
got = store.clean_host({"platform": "TikTok", "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["display_name"], got["full_name"]), ("Siti", "Siti Aisyah"))
|
||||
self.assertEqual((got["platform"], got["display_name"], got["full_name"]), ("tiktok", "Siti", "Siti Aisyah"))
|
||||
self.assertNotIn("tiktok_handle", got) # 계정은 방송마다 — 호스트에는 저장 안 함
|
||||
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 = {"platform": "shopee", "display_name": "A", "full_name": "A"}
|
||||
self.assertEqual(store.clean_host(ok)["phone"], "") # 쇼핑몰·두 이름만 필수
|
||||
for bad in ({}, {**ok, "full_name": ""}, {**ok, "display_name": ""}, {**ok, "platform": ""}, {**ok, "platform": "lazada"}, {**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)
|
||||
@@ -256,9 +256,9 @@ assert "live_host" in MODULE_KEYS and "live_host" in main.MODULE_LABELS
|
||||
class Fake:
|
||||
saved = []
|
||||
def host_choices(self):
|
||||
return [{"id": 1, "display_name": "Siti", "full_name": "Siti Binti Awa", "is_active": True}]
|
||||
return [{"id": 1, "platform": "tiktok", "display_name": "Siti", "full_name": "Siti Binti Awa", "is_active": True}]
|
||||
def list_hosts(self):
|
||||
return [{"id": 1, "display_name": "Siti", "full_name": "Siti Binti Awa", "phone": "012", "email": "s@e.my", "address": "KL", "bank_name": "Maybank",
|
||||
return [{"id": 1, "platform": "tiktok", "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 []
|
||||
@@ -273,7 +273,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 = {"display_name": "Newbie", "full_name": "New Host", "bank_account": "111"}
|
||||
new = {"platform": "tiktok", "display_name": "Newbie", "full_name": "New Host", "bank_account": "111"}
|
||||
|
||||
def body(c):
|
||||
who["u"] = adder
|
||||
@@ -281,12 +281,13 @@ def body(c):
|
||||
assert 'href="/live/settings"' in sched and 'name="tiktok_handle"' in sched and '<option value="alt.acc">' in sched
|
||||
page = c.get("/live/settings")
|
||||
assert page.status_code == 200 and "Siti" in page.text and 'name="full_name"' in page.text
|
||||
for hidden in ("998877", "Maybank", "s@e.my", 'name="tiktok_handle"', "data-edit='", "/delete", 'name="is_active"'):
|
||||
for hidden in ("998877", "Maybank", "s@e.my", 'name="tiktok_handle"', "data-edit='", "/delete", 'name="is_active"', "data-active="):
|
||||
assert hidden not in page.text, hidden
|
||||
assert c.post("/live/settings/hosts", data=new).json()["ok"]
|
||||
assert fake.saved == [(None, "New Host", True, "adder@t.local")], fake.saved
|
||||
assert c.post("/live/settings/hosts", data={**new, "id": "1"}).status_code == 403
|
||||
assert c.post("/live/settings/hosts/1/delete").status_code == 403
|
||||
assert c.post("/live/settings/hosts/1/active", data={"is_active": "0"}).status_code == 403 # 토글 = 고치기 권한
|
||||
assert len(fake.saved) == 1, fake.saved
|
||||
|
||||
for no_add in (U("staff@t.local"), chip_only):
|
||||
@@ -313,13 +314,13 @@ run(body)
|
||||
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",
|
||||
OLD = {"id": 1, "platform": "shopee", "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")}]
|
||||
return [{k: OLD[k] for k in ("id", "platform", "display_name", "full_name", "is_active")}]
|
||||
def list_hosts(self):
|
||||
return [OLD]
|
||||
def get_host(self, host_id):
|
||||
@@ -333,11 +334,15 @@ class Fake:
|
||||
return 1
|
||||
def delete_host(self, host_id):
|
||||
self.saved.append(("deleted", host_id))
|
||||
def set_host_active(self, host_id, is_active, *, by):
|
||||
if host_id != 1:
|
||||
raise ValueError("호스트를 찾을 수 없습니다.")
|
||||
self.saved.append(("active", host_id, is_active))
|
||||
|
||||
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"}
|
||||
form = {"id": "1", "platform": "shopee", "display_name": "Nabella", "full_name": "Siti Binti Awa", "is_active": "1"}
|
||||
|
||||
def body(c):
|
||||
who["u"] = editor
|
||||
@@ -346,6 +351,14 @@ def body(c):
|
||||
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 \'data-active="/live/settings/hosts/1/active"\' in page and \'src="/static/dispatch/courier/shopee.png"\' in page
|
||||
assert \'"platform": "shopee"\' in page and page.count(\'name="platform"\') == 2
|
||||
|
||||
# 목록 토글 — 사용 여부만
|
||||
assert c.post("/live/settings/hosts/1/active", data={"is_active": "0"}).json()["ok"] and fake.saved[-1] == ("active", 1, False)
|
||||
assert c.post("/live/settings/hosts/1/active", data={"is_active": "1"}).json()["ok"] and fake.saved[-1] == ("active", 1, True)
|
||||
assert c.post("/live/settings/hosts/9/active", data={"is_active": "1"}).status_code == 400
|
||||
assert c.post("/live/settings/hosts", data={**form, "platform": ""}).status_code == 400 # 쇼핑몰 필수
|
||||
|
||||
assert c.post("/live/settings/hosts", data=form).json()["ok"]
|
||||
host_id, values, active = fake.saved[-1]
|
||||
@@ -364,6 +377,7 @@ def body(c):
|
||||
who["u"] = no_edit
|
||||
assert c.get("/live/settings").status_code == 403
|
||||
assert c.post("/live/settings/hosts", data=form).status_code == 403
|
||||
assert c.post("/live/settings/hosts/1/active", data={"is_active": "0"}).status_code == 403
|
||||
assert len(fake.saved) == count
|
||||
|
||||
# 관리자는 빈칸 = 지우기 그대로
|
||||
@@ -447,7 +461,7 @@ def jpeg():
|
||||
return raw.getvalue()
|
||||
|
||||
def body(c):
|
||||
host = {"display_name": "S" + tag, "full_name": NAME, "phone": "+60 12-345", "email": "siti@example.my", "address": "Kuala Lumpur",
|
||||
host = {"platform": "tiktok", "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
|
||||
@@ -461,6 +475,9 @@ def body(c):
|
||||
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)
|
||||
assert st.get_host(hid)["platform"] == "tiktok"
|
||||
assert c.post("/live/settings/hosts/%d/active" % hid, data={"is_active": "0"}).json()["ok"] and st.get_host(hid)["is_active"] is False
|
||||
assert c.post("/live/settings/hosts/%d/active" % hid, data={"is_active": "1"}).json()["ok"] and st.get_host(hid)["is_active"] is True
|
||||
page = c.get("/live/settings").text
|
||||
for field in ("이름 (IC 기준)", "전화번호", "이메일", "주소", "은행명", "계좌번호"):
|
||||
assert field in page, field
|
||||
@@ -526,7 +543,7 @@ 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 "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 "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 & 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."
|
||||
@@ -537,7 +554,7 @@ def body(c):
|
||||
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"):
|
||||
for field in ("Full Name (as per IC)", "Phone Number", "Email", "Address", "Bank Name", "Bank Account Number", "Platform"):
|
||||
assert field in page, field
|
||||
who["u"] = staff
|
||||
c.cookies.set("live_lang", "<bad>") # 모르는 값 = 한글
|
||||
|
||||
Reference in New Issue
Block a user