29 Commits

Author SHA1 Message Date
king d9db230fe4 Merge branch 'feat/live-calendar-fit-screen' 2026-11-05 19:09:49 +09:00
king ece5b06f7a style(라이브): 달력 보기를 풀HD 한 화면에 맞춤
오른쪽 달력을 80%(240px)로 줄이고 표 글자·칸 높이·카드를 줄인다.
넓은 화면에서는 페이지 세로 스크롤을 없애고 표 상자가 남은 높이를 쓰게 한다.
풀HD 브라우저 세로 880px 에서 9개 시간 칸과 합계 줄이 표 안 스크롤 없이 들어간다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 19:09:44 +09:00
king fd37e367a1 Merge branch 'feat/live-split-full-width' 2026-11-05 18:55:59 +09:00
king 97b9729671 feat(라이브): 달력 보기 세로 2분할과 전체 너비
날짜로 이동 줄을 없애고 달력을 화면 오른쪽 위에 고정한다.
라이브 커머스 화면은 공용 최대 폭(1550px)을 풀고 안쪽 여백을 16px 로 줄여 화면 전체 너비를 쓴다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 18:55:54 +09:00
king db32d03e07 Merge branch 'feat/live-side-calendar' 2026-11-05 18:50:35 +09:00
king cf0e3f2139 feat(라이브): 달력 보기 오른쪽에 공용 달력과 말레이시아 공휴일
표 오른쪽에 erp-datepop 붙박이 달력을 두고, 날짜를 누르면 그 날이 표 맨 왼쪽에 오게 한다.
다른 달을 누르면 그 달 화면으로 이동해 같은 위치로 맞춘다. 마지막 날도 맨 왼쪽에 오도록 표 끝에 여백을 둔다.
말레이시아 공휴일·대체휴일 표(holidays.py, 쿠알라룸푸르 기준 2026·2027)를 표시한다.
공용 달력에 선택 옵션 locale 을 추가해 영문 화면도 영어로 그린다. 기존 화면 동작은 그대로.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 18:50:29 +09:00
king e77f3d6a82 Merge branch 'feat/live-host-short-name' 2026-11-05 18:15:35 +09:00
king e6ebf2188b feat(라이브): 호스트 간단한 이름과 수정 권한 칩
호스트에 간단한 이름(display_name, 필수)을 추가하고 달력 카드·스케줄표·방송 창에 표시한다.
달력 카드 머리 아래에 그 방송의 틱톡 계정을 작게 보여 준다.
관리자 페이지 칩 live_host_edit 로 호스트 수정을 허용한다. 지우기는 관리자만이고,
개인정보는 페이지에 싣지 않아 빈칸으로 열리며 비워 두면 값이 유지된다.
마이그레이션 004: live_hosts.display_name 추가.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 18:15:30 +09:00
king 43771edd77 Merge branch 'feat/live-account-per-broadcast' 2026-11-05 18:03:56 +09:00
king 42fdf98560 feat(라이브): 틱톡 계정을 호스트에서 방송으로 옮김
호스트가 메인 계정 외 다른 계정에서도 방송하므로 호스트 설정에서 틱톡 핸들을 빼고
방송 추가·고치기 창에서 방송마다 입력한다. 쓴 적 있는 계정을 입력 제안으로 보여 준다.
마이그레이션 003: live_broadcasts.tiktok_handle 추가, 기존 방송에 호스트의 지금 계정 복사.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 18:03:50 +09:00
king c325d91bab Merge branch 'revert/inout-list-cal-smaller-2' 2026-11-05 15:09:34 +09:00
king 74782da88c Revert "style(입출고): 달력과 발주 목록 글자를 다시 90%로"
사용자 요청으로 두 번째 축소를 취소한다. 달력 clamp(270px, 20.7vw, 396px),
발주 목록 글자는 원래의 90%로 되돌린다. 머지 e3b7e55 를 되돌림.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:09:20 +09:00
king e3b7e55695 Merge branch 'feat/inout-list-cal-smaller-2' 2026-11-05 15:08:05 +09:00
king f3cb198681 style(입출고): 달력과 발주 목록 글자를 다시 90%로
달력 clamp(243px, 18.63vw, 356px), 발주 목록 글자는 원래의 81%.
상태 열까지 표 안에 들어오도록 줄인다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:08:01 +09:00
king 44779c3979 Merge branch 'feat/inout-list-cal-smaller' 2026-11-05 15:05:28 +09:00
king 162f9f28d5 style(입출고): 오른쪽 달력과 발주 목록 글자를 90%로
달력 너비 clamp(270px, 20.7vw, 396px), 글자는 달력 너비 기준이라 함께 줄어든다.
발주 목록 표는 머리글과 칸의 글자 크기를 각각 90%로 줄여 비율을 유지한다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:05:23 +09:00
king 99069619d6 Merge branch 'feat/inout-filter-right' 2026-11-05 15:01:37 +09:00
king cff560ad71 style(입출고): 발주 목록 거르기 줄 날짜·검색을 오른쪽 정렬
상태·공장은 왼쪽에 두고 발주일부터 찾기까지 한 묶음으로 오른쪽 끝에 붙인다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 15:01:32 +09:00
king b637fdeeeb Merge branch 'feat/inout-list-head-style' 2026-11-05 14:58:49 +09:00
king 8449b02320 style(입출고): 발주 목록 표 머리글 강조
가운데 정렬, 굵게, 글자 11% 확대(12px → 13.32px), 회색 배경.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 14:58:44 +09:00
king 17b119d8c3 Merge branch 'feat/inout-list-receipt-dates' 2026-11-05 14:45:38 +09:00
king b7e05f58aa feat(입출고): 발주 목록에 입고일 열 추가
입고 예정일과 발주 사이에 입고일을 보여 준다. 여러 날에 나눠 입고하면 칸 안에서
줄바꿈하고, 같은 날 여러 번 입고는 한 번만, 입고 전에는 - 로 표시한다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 14:45:33 +09:00
king 50f25a7ec7 Merge branch 'feat/perf-tiktok-tab' 2026-11-05 14:19:39 +09:00
king 54e4e08802 feat(실적): 틱톡 탭과 틱톡 광고 API 연동
광고비 탭 오른쪽에 틱톡 탭 추가. 일자별 ROAS, 광고비, 매출을 광고비 탭과 같은 틀로 보여 준다.
실적 설정 광고 API 연동에 틱톡 추가(광고 계정 ID, 액세스 토큰, 선택 틱톡샵 ID).
채널 표(CHANNELS)에 넣지 않아 매출 실적·광고비 탭 합계에는 들어가지 않는다. DB 변경 없음.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 14:19:25 +09:00
king d27257f15b Merge branch 'feat/inout-datepop' 2026-11-05 14:12:13 +09:00
king 212a3dd6b0 feat(입출고): 날짜 칸을 ERP 공용 달력으로
발주 목록 기간, 발주일, 입고 예정일, 입고일을 erp-datepop 으로 교체.
국경일·대체공휴일을 빨강·이름으로 표시하고 마우스를 올리면 이름을 보여 준다.
필수 칸은 지우기를 빼고, 잠긴 입고일은 버튼도 비활성화.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 14:11:45 +09:00
king 01208ea4d4 Merge branch 'feat/live-host-add-permission' 2026-11-05 13:03:01 +09:00
king 49b3b6a0dc feat(라이브): 호스트 등록 전용 권한 칩 live_host
live + live_host 칩이 있으면 새 호스트 등록만 가능. 계좌 등 개인정보 보기,
고치기, 지우기, 사용 여부 변경은 ERP 관리자만.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 13:02:52 +09:00
king 4477a68819 Merge branch 'fix/cafe24-img-suffix-anywhere' 2026-11-04 22:09:49 +09:00
56 changed files with 1837 additions and 225 deletions
+3 -3
View File
@@ -47,7 +47,7 @@
| `[공지]` `[긴급공지]` | `notice/` | `project_db`(024) | 수퍼관리자 | `docs/NOTICE_MODULE.md` | `erp-notice*` |
| `[자산]` | `asset/` | `asset_db` | `asset` | `docs/ASSET_MODULE.md` | `asset.*` |
| `[안내문 발송]` | `outreach/` | `outreach_db` | `outreach` | (모듈 CLAUDE.md) | `outreach.*` |
| `[라이브커머스]` `[라이브]` | `live/` | `live_db` | `live` | (모듈 CLAUDE.md) | `live.*` |
| `[라이브커머스]` `[라이브]` | `live/` | `live_db` | `live`, `live_host` | (모듈 CLAUDE.md) | `live.*` |
| `[공통]` `[ERP]` | `app/main.py`, `app/templates/`(셸·로그인·관리자), 인증·권한 | — | — | `docs/PROJECT_OVERVIEW.md`, `docs/DESIGN.md` | `erp*.js/css`, `styles.css` |
| `[배포]` `[서버]` | `docker-compose*.yml`, `Dockerfile`, `scripts/` | — | — | `docs/DEPLOYMENT.md` | — |
| `[DB]` | `scripts/sql/` | — | — | `docs/DATABASES.md` | — |
@@ -66,8 +66,8 @@
- `asset/media.py prepare_photo`(이미지 확인·메타데이터 제거): 자산 + 라이브 커머스.
- `app/mail.py`: 프로젝트 알림 메일.
- ERP 모든 화면 스크립트: `erp-notice.js`(공지) · `erp-overdue.js`(프로젝트 마감 알림).
- 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청) — 바꾸면 둘 다.
- 국경일·대체공휴일 표 `project/store.py KR_HOLIDAYS`: 프로젝트 캘린더·날짜 팝업 + 휴가(달력·일수 계산 `vacation/db.holiday_map`).
- 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청·입출고 날짜 칸·라이브 오른쪽 달력) — 바꾸면 둘 다.
- 국경일·대체공휴일 표 `project/store.py KR_HOLIDAYS`: 프로젝트 캘린더·날짜 팝업 + 휴가(달력·일수 계산 `vacation/db.holiday_map`) + 입출고(오른쪽 달력·날짜 칸).
---
+2
View File
@@ -68,6 +68,8 @@ MODULE_LABELS: dict[str, str] = {
"inout": "입출고 관리",
"outreach": "안내문 발송",
"live": "라이브 커머스",
"live_host": "라이브 호스트 등록",
"live_host_edit": "라이브 호스트 수정",
"expense_approver": "개인경비",
"vacation_approver": "휴가",
}
+7 -2
View File
@@ -11,6 +11,9 @@
- 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고.
- 미입고 현황(제품별 합계·발주별·지연).
- 발주 목록 상태 보기(진행 중·완료·종결·취소·전체)는 **사람마다 기억**(2026-11-04) — `inout_settings` 키 `list_status:{이메일}`(마이그레이션 없음, 005 미적용이면 기억만 안 함). 주소에 `status` 가 있으면 저장, 없으면 저장값, 그것도 없으면 진행 중.
- 발주 목록 **입고일** 열(2026-11-05, 입고 예정일과 발주 사이, `db.list_orders` `receipt_dates`) — 여러 날에 나눠 입고하면 칸 안에서 줄바꿈(오래된 날부터), 같은 날 여러 번은 한 번만, 입고 전 `-`.
- 발주 목록 거르기 줄(2026-11-05) — 상태·공장은 왼쪽, 발주일~[찾기]는 오른쪽(`.io-filter-right`).
- 발주 목록 표 머리글(2026-11-05, `.io-list-table`) = 가운데·굵게·`--text-caption` × 111% × 90%·회색 배경, 표 글자 전체도 원래의 90%. 미입고 현황 등 다른 표는 그대로.
- [남은 수량 모두 채우기]를 한 번 더 누르면(= [채운 수량 되돌리기]) 채우기 전 값으로(2026-10-19, `inout.js`).
- 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`).
- **전체 입고 완료(모든 품목 입고 ≥ 발주, 상태 done·over)면 더 입고 못 함**(2026-10-19) — 화면은 입고 칸·[입고 저장]·사진·[남은 수량 채우기]를 흐리게 disabled, 서버 `_add_receipt` 도 잠근 뒤 거절. 입고 기록을 지우면 다시 열림.
@@ -106,8 +109,8 @@
## 오른쪽 달력 (2026-10-21)
- 입출고 **모든 화면** 2열(`.io-split` = 왼쪽 `section.io` | 오른쪽 `_calendar.html`, 1100px 미만은 한 열 300px). 스크롤해도 위에 붙음.
달력 크기 = 화면에 따라 300~440px(`clamp(300px, 23vw, 440px)`, 높이 ×320/300) — 입출고 화면만 ERP 공용 최대 폭 1550px 를 풀어 넓은 화면 여백을 씀(2026-10-21 "여백이 많다, 더 키워 달라").
- 입출고 **모든 화면** 2열(`.io-split` = 왼쪽 `section.io` | 오른쪽 `_calendar.html`, 1100px 미만은 한 열 270px). 스크롤해도 위에 붙음.
달력 크기 = 화면에 따라 270~396px(`clamp(270px, 20.7vw, 396px)`, 2026-11-05 90% 로 줄임, 높이 ×320/300) — 입출고 화면만 ERP 공용 최대 폭 1550px 를 풀어 넓은 화면 여백을 씀(2026-10-21 "여백이 많다, 더 키워 달라").
글자·칸은 달력 너비 기준 `cqw`(300px 일 때 1cqw = 3px)라 같은 비율로 커진다 — 새 크기 값도 px 대신 cqw 로.
- 프로젝트 달력 모양(일요일 시작·요일 줄 회색·오늘 검은 동그라미·토 파랑·일/공휴일 빨강 — 공휴일 표는 `project.store.holiday_name` 재사용).
공휴일 이름은 숫자 아래 한 줄(`.io-cal-hol`, 8.5px — 5글자까지 다 보임, 더 길면 … + 말풍선에 전체 이름).
@@ -119,3 +122,5 @@
- 시각은 DB 시간대와 무관하게 KST 로 읽음(`db._KstTimestamptzLoader`).
- 날짜 서식은 모두 `yyyy.mm.dd(요일)`(`ymd`·`ymdhm` 매크로, `store.fmt_date`).
- **날짜 칸 = ERP 공용 달력**(2026-11-05, `erp-datepop`, `_datepop.html` + `inout.js` 머리) — 발주 목록 기간·발주일·입고 예정일·입고일. `input[type=date]` 는 숨긴 값 저장소(폼 전송 그대로), 국경일·대체공휴일 빨강·이름 + 마우스를 올리면 이름(`title`, 표 = `project.store.KR_HOLIDAYS`, `router._date_holidays`).
필수 칸은 [지우기] 없음(숨긴 required 칸이 비면 브라우저가 안내 없이 저장을 막는다), 잠긴 입고일은 버튼도 disabled. 테스트 `tests/js/inout_datepop.browser.test.js`(`render_inout.py`).
+7 -1
View File
@@ -339,9 +339,15 @@ class InoutDBStore:
"SELECT l.order_id, l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received "
"FROM inout_order_lines l LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id "
"WHERE l.order_id = ANY(%s) GROUP BY l.id ORDER BY l.line_no", (ids,)).fetchall() if ids else []
# 입고일 열 — 같은 날 여러 번 입고해도 날짜는 하나
receipts = conn.execute("SELECT DISTINCT order_id, receipt_date FROM inout_receipts WHERE order_id = ANY(%s) "
"ORDER BY order_id, receipt_date", (ids,)).fetchall() if ids else []
by_order: dict[int, list[dict[str, Any]]] = {}
for ln in lines:
by_order.setdefault(int(ln["order_id"]), []).append(ln)
receipt_dates: dict[int, list[date]] = {}
for r in receipts:
receipt_dates.setdefault(int(r["order_id"]), []).append(r["receipt_date"])
allowed = store.STATUS_FILTERS.get(status, store.STATUS_FILTERS["active"])[1]
out = []
for h in heads:
@@ -351,7 +357,7 @@ class InoutDBStore:
continue
names = [x["item_name"] or x["item_code"] for x in ls]
out.append({**h, "status": st, "status_label": store.ORDER_LABELS[st], "summary": store.summarize(ls),
"line_count": len(ls), "items_label": (names[0] + (f" 외 {len(names) - 1}종" if len(names) > 1 else "")) if names else ""})
"receipt_dates": receipt_dates.get(int(h["id"]), []), "line_count": len(ls), "items_label": (names[0] + (f" 외 {len(names) - 1}종" if len(names) > 1 else "")) if names else ""})
if len(out) >= limit:
break
return out
+11 -1
View File
@@ -106,6 +106,16 @@ def _require(st: Any, user: dict[str, Any], what: str) -> dict[str, bool]:
return p
def _date_holidays() -> dict[str, str]:
"""날짜 칸 달력(erp-datepop)의 국경일·대체공휴일 — 프로젝트 달력과 같은 표."""
try:
from app.modules.project.store import KR_HOLIDAYS # noqa: WPS433
return dict(KR_HOLIDAYS)
except Exception: # noqa: BLE001 — 표를 못 읽어도 날짜 입력은 된다
return {}
def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, Any], status_code: int = 200) -> HTMLResponse:
from app.main import build_erp_nav, render_template # noqa: WPS433
@@ -114,7 +124,7 @@ def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, An
return render_template(request, name, {
"user": user, "is_admin": perms["admin"], "perms": perms,
"nav_items": build_erp_nav(user, active="inout"),
"msg": request.query_params.get("msg", ""), "today": today_kst(),
"msg": request.query_params.get("msg", ""), "today": today_kst(), "date_holidays": _date_holidays(),
"open_options": request.query_params.get("options") == "1" and perms["admin"], # 톱니 팝업 바로 열기
**ctx,
}, status_code=status_code)
@@ -0,0 +1,5 @@
{# 날짜 칸 = ERP 공용 달력(erp-datepop) — inout.js 가 input[type=date] 를 날짜 버튼으로 바꾼다. inout.js 보다 먼저 include. #}
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<link rel="stylesheet" href="/static/erp-datepop.css?v=20261102a" />
<script type="application/json" id="io-holidays">{{ (date_holidays or {}) | tojson }}</script>
<script src="/static/erp-datepop.js?v=20261105a" defer></script>
+9 -6
View File
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% from "inout/_macros.html" import order_badge, progress, due, n, ymd %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261104c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261105d" />{% endblock %}
{% block content %}
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
@@ -21,18 +21,20 @@
<option value="">전체 공장</option>
{% for f in factories %}<option value="{{ f.id }}" {% if filters.factory == f.id %}selected{% endif %}>{{ f.name }}{% if not f.is_active %} (사용 안 함){% endif %}</option>{% endfor %}
</select>
<label class="io-date">발주일 <input class="erp-input" type="date" name="from" value="{{ filters['from'] }}" /></label>
<div class="io-filter-right">
<label class="io-date">발주일 <input class="erp-input" type="date" name="from" value="{{ filters['from'] }}" aria-label="발주일 시작" /></label>
<span class="erp-muted">~</span>
<input class="erp-input" type="date" name="to" value="{{ filters['to'] }}" aria-label="발주일 끝" />
<input class="erp-input io-search" type="search" name="q" value="{{ filters.q }}" placeholder="발주번호·제품 코드·제품 이름" />
<button type="submit" class="erp-btn erp-btn-outline">찾기</button>
</div>
</form>
<div class="erp-card-block">
<div class="erp-table-wrap">
<table class="erp-table io-table">
<table class="erp-table io-table io-list-table">
<thead><tr>
<th>발주번호</th><th>공장</th><th>제품</th><th>발주일</th><th>입고 예정일</th>
<th>발주번호</th><th>공장</th><th>제품</th><th>발주일</th><th>입고 예정일</th><th>입고일</th>
<th class="io-num">발주</th><th class="io-num">입고</th><th class="io-num">미입고</th><th>진행</th><th>상태</th>
{% if perms.super %}<th class="io-col-trash"><span class="sr-only">삭제</span></th>{% endif %}
</tr></thead>
@@ -45,6 +47,7 @@
<td class="io-items">{{ o.items_label }}<div class="erp-row-sub">{{ o.line_count }}종</div></td>
<td>{{ ymd(o.order_date) }}</td>
<td>{{ due(o.due_date, today, active) }}</td>
<td>{% for d in o.receipt_dates %}<div>{{ ymd(d) }}</div>{% else %}-{% endfor %}</td>
<td class="io-num">{{ n(o.summary.ordered) }}</td>
<td class="io-num">{{ n(o.summary.received) }}</td>
<td class="io-num{% if o.summary.remaining and active %} io-remaining{% endif %}">{{ n(o.summary.remaining) }}{% if o.summary.over %}<div class="io-over-sub">초과 +{{ n(o.summary.over) }}</div>{% endif %}</td>
@@ -61,7 +64,7 @@
{% endif %}
</tr>
{% else %}
<tr><td colspan="{{ 11 if perms.super else 10 }}" class="erp-empty">{% if filters.status == 'active' %}진행 중인 발주가 없습니다.{% else %}조건에 맞는 발주가 없습니다.{% endif %}</td></tr>
<tr><td colspan="{{ 12 if perms.super else 11 }}" class="erp-empty">{% if filters.status == 'active' %}진행 중인 발주가 없습니다.{% else %}조건에 맞는 발주가 없습니다.{% endif %}</td></tr>
{% endfor %}
</tbody>
</table>
@@ -71,4 +74,4 @@
{% include "inout/_calendar.html" %}
</div>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261104c" defer></script>{% endblock %}
{% block scripts %}{% include "inout/_datepop.html" %}<script src="/static/inout.js?v=20261105a" defer></script>{% endblock %}
@@ -20,7 +20,7 @@
</footer>
</dialog>
{%- endmacro -%}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261104c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261105d" />{% endblock %}
{% block content %}
{% set active = order.status in ('open', 'partial') %}
@@ -155,7 +155,7 @@
</div>
{% if receiving %}
<div class="io-receipt-bar{% if recv_done %} is-locked{% endif %}"{% if recv_done %} aria-disabled="true" title="전체 입고 완료 — 더 입고할 수 없습니다"{% endif %}>
<label class="erp-field"><span>입고일 *</span><input type="date" name="receipt_date" value="{{ receipt_form.receipt_date }}" required{{ dis }} /></label>
<label class="erp-field"><span>입고일 *</span><input type="date" name="receipt_date" value="{{ receipt_form.receipt_date }}" aria-label="입고일" required{{ dis }} /></label>
<label class="erp-field io-grow"><span>메모</span><input type="text" name="memo" value="{{ receipt_form.memo }}" maxlength="500" placeholder="차량·박스 수·검수 메모 등"{{ dis }} /></label>
<div class="erp-field io-photo-field">
<span>입고증 사진 <small>(최대 {{ max_photos }}장)</small></span>
@@ -262,4 +262,4 @@
{% include "inout/_calendar.html" %}
</div>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261104c" defer></script>{% endblock %}
{% block scripts %}{% include "inout/_datepop.html" %}<script src="/static/inout.js?v=20261105a" defer></script>{% endblock %}
@@ -1,5 +1,5 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261104c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261105d" />{% endblock %}
{% block content %}
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
@@ -23,8 +23,8 @@
</select>
{% if not factories %}<span class="io-hint">공장이 없습니다 — 관리자가 옵션에서 먼저 공장을 추가해야 합니다.</span>{% endif %}
</label>
<label class="erp-field"><span>발주일 *</span><input type="date" name="order_date" value="{{ vals.order_date }}" required /></label>
<label class="erp-field"><span>입고 예정일</span><input type="date" name="due_date" value="{{ vals.due_date }}" /></label>
<label class="erp-field"><span>발주일 *</span><input type="date" name="order_date" value="{{ vals.order_date }}" aria-label="발주일" required /></label>
<label class="erp-field"><span>입고 예정일</span><input type="date" name="due_date" value="{{ vals.due_date }}" aria-label="입고 예정일" /></label>
<label class="erp-field"><span>메모</span><input type="text" name="memo" value="{{ vals.memo }}" maxlength="500" placeholder="공장 전달 사항 등" /></label>
</div>
@@ -102,4 +102,4 @@
{% include "inout/_calendar.html" %}
</div>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261104c" defer></script>{% endblock %}
{% block scripts %}{% include "inout/_datepop.html" %}<script src="/static/inout.js?v=20261105a" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% from "inout/_macros.html" import due, n, ymd %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261104c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261105d" />{% endblock %}
{% block content %}
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
@@ -91,4 +91,4 @@
{% include "inout/_calendar.html" %}
</div>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261104c" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261105a" defer></script>{% endblock %}
+10 -3
View File
@@ -5,17 +5,24 @@
> 다른 모듈과 연결: 이미지 검사 = 자산 모듈 `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·Tiktok Handle(`@`·주소를 붙여 넣어도 계정명만 저장).
**계좌 등 개인정보라 ERP 관리자만**(`is_admin`) — 화면·저장·지우기 모두. 스케줄 화면에는 `db.host_choices`(이름·틱톡·사용 여부)만 넘긴다.
- **호스트 설정** `/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` 은 값만 남아 있고 안 씀. 달력에서 옮기거나 맞바꿔도 계정은 그 방송에 그대로. 달력 카드 머리·스케줄표·방송 창의 호스트 = 간단한 이름, 카드 머리 아래 작은 글자 = 계정.
**`live_host_edit` 칩**(+ `live`, 관리자 페이지 토글) = 호스트 **고치기**(사용 여부 포함): 지우기 불가, 개인정보는 페이지에 싣지 않아 빈칸으로 열리고 비워 두면 그대로·입력하면 바뀜(이 칩으로는 지울 수 없음).
**`live_host` 칩**(+ `live` 칩 필요) = 새 호스트 **등록만**: 설정 화면에 이름·상태만 보이고, 입력한 계좌 등은 저장 후 못 봄. 고치기·지우기 불가, 사용 여부 못 고름(항상 사용).
사용 안 함 = 새 방송에서 못 고름(그 호스트로 이미 등록된 방송을 고칠 때만 보임). 방송 기록이 있는 호스트는 못 지움(FK RESTRICT).
- **스케줄표** `/live/?month=YYYY-MM`(`live` 권한자 모두) — 호스트·날짜·시작/끝 시간·방송 장소·판매금액·커미션·호스트 비용·결과 이미지. 호스트·날짜·시작·끝 시간 필수(판매금액은 방송 후 입력).
시간은 입력한 말레이시아 시간 그대로(시간대 변환 없음, DATE·TIME). 판매금액 단위 RM(`NUMERIC(14,2)`, `store.parse_money`). 끝 시간이 시작보다 이르면 자정을 넘긴 방송.
- **호스트 비용**(`store.session_pay`, 저장 안 함 — 화면마다 계산) = 시간 × RM 25(`HOURLY_RATE`) + 판매금액 × 10%(`COMMISSION_PERCENT`). 요율이 코드 상수라 바꾸면 지난 방송 금액도 바뀐다.
- **달력 보기** `/live/calendar?month=`(`store.build_calendar`, 사용자가 준 화면 참고, 글자도 영어 그대로) — 줄 = 2시간 칸(06:00~24:00 늘 보임, 그보다 이른 칸은 방송이 있을 때만, 칸은 시작 시간으로 정함), 열 = 날짜, 주말 노랑, Jump to Date, 위 달 합계, 맨 아래 날짜별 TOTAL SALES·AD SPEND·HOST FEE·ROAS.
- **달력 보기** `/live/calendar?month=`(`store.build_calendar`, 사용자가 준 화면 참고, 글자도 영어 그대로) — 줄 = 2시간 칸(06:00~24:00 늘 보임, 그보다 이른 칸은 방송이 있을 때만, 칸은 시작 시간으로 정함), 열 = 날짜, 주말 노랑, 위 달 합계, 맨 아래 날짜별 TOTAL SALES·AD SPEND·HOST FEE·ROAS.
카드 머리 = **Tiktok Handle**(없으면 이름, 색 = 호스트 id 순 `HOST_COLORS`), SALES·COM·Fee. 카드 머리를 끌어 빈 칸으로 = 옮기기(`move`, 방송 길이 유지) · 다른 카드 위 = 맞바꾸기(`swap_with`, 날짜·시간 교환). 다시 그린 뒤 가로 위치 유지(sessionStorage). 빈 칸 + = 그 날짜·시간이 채워진 추가 창.
**AD SPEND** = 날짜별 광고비 `live_daily_ad_spend`(마이그레이션 002, `POST /live/ad-spend`, 빈칸 = 지우기), ROAS = 판매금액 ÷ 광고비(광고비 없으면 `-`). 002 미적용이면 0 으로 보이고 저장만 안내.
- **한 화면 맞춤**(2026-11-05) — 달력 보기는 넓은 화면(1101px 이상)에서 페이지 세로 스크롤 없음: `.lv-cal-wrap` 이 남은 높이를 쓰고, 풀HD 브라우저(세로 880px 이상)면 9개 시간 칸·합계 줄이 표 안 스크롤 없이 들어간다(카드가 한 칸에 겹치거나 창이 더 낮으면 표 안에서 스크롤). 카드·표 글자·칸 크기를 늘리면 `live_calendar.browser.test.js` 로 다시 확인.
- **오른쪽 달력**(2026-11-05, 달력 보기만, 세로 2분할 `.lv-split`, 240px = 공용 달력의 80%, 예전 날짜로 이동 줄 대신, 공용 `erp-datepop` `mountRange` + `locale` 옵션으로 영문) — 날짜를 누르면 그 날이 표 맨 왼쪽(마지막 날까지 — `endGap` 이 표 끝에 여백), 다른 달이면 그 달 화면으로 가서 맨 왼쪽(sessionStorage `lv_cal_jump`). 표시만 하고 요금·일수에 안 씀. 테스트 `tests/js/live_calendar.browser.test.js`(`render_live.py`).
**말레이시아 공휴일 표 = `holidays.py`**(쿠알라룸푸르 기준, 2026·2027, 대체휴일 포함) — 이슬람 명절은 달 관측으로 바뀔 수 있고, 2028 은 공고되면 손으로 추가.
- **결과 이미지** — 방송 저장과 한 트랜잭션, JPG·PNG·WebP, 한 장 8MB, 방송당 10장(`store.MAX_IMAGES`). `prepare_photo` 가 실제 이미지 확인·긴 변 2400px·EXIF(GPS 등) 제거. BYTEA 저장.
`GET /live/images/{id}`(권한 필요, 하루 private 캐시), `?thumb=1` = 160px JPEG(그때그때 만듦). 올린 뒤 내용이 안 바뀐다는 전제 — 이미지를 고치는 기능을 넣으면 캐시도 바꿀 것.
- 라이브 커머스 화면은 공용 최대 폭(1550px)을 풀어 **화면 전체 너비**를 쓴다(`live.css` 맨 위, 스케줄표·달력·호스트 설정).
- 저장은 `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 공용 사이드바는 번역하지 않는다.
+20 -11
View File
@@ -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", "tiktok_handle")
_HOST_COLUMNS = ("display_name", "full_name", "phone", "email", "address", "bank_name", "bank_account")
class LiveDBStore:
@@ -39,21 +39,30 @@ class LiveDBStore:
def host_choices(self) -> list[dict[str, Any]]:
"""스케줄 화면 호스트 고르기 — 개인정보·계좌는 뺀다."""
with self._pool.connection() as conn:
return conn.execute("SELECT id, full_name, tiktok_handle, 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]:
"""방송 창 틱톡 계정 입력 제안 — 지금까지 방송에 쓴 계정."""
with self._pool.connection() as conn:
rows = conn.execute("SELECT DISTINCT tiktok_handle FROM live_broadcasts WHERE tiktok_handle <> '' ORDER BY tiktok_handle").fetchall()
return [r["tiktok_handle"] for r in rows]
def save_host(self, host_id: int | None, values: dict[str, str], *, is_active: bool, by: str) -> int:
cols = [values[k] for k in _HOST_COLUMNS]
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, tiktok_handle, "
"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, "
"tiktok_handle=%s, is_active=%s, updated_by=%s WHERE id=%s RETURNING id",
"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:
raise LiveError("호스트를 찾을 수 없습니다.")
@@ -73,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, h.tiktok_handle 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(
@@ -98,14 +107,14 @@ class LiveDBStore:
if not host["is_active"] and values["host_id"] != current:
raise LiveError("사용 안 함으로 바뀐 호스트입니다 — 다른 호스트를 고르세요.")
args = (values["host_id"], values["broadcast_date"], values["start_time"], values["end_time"], values["venue"],
values["sales_amount"], by)
values["tiktok_handle"], values["sales_amount"], by)
if broadcast_id is None:
broadcast_id = int(conn.execute(
"INSERT INTO live_broadcasts (host_id, broadcast_date, start_time, end_time, venue, sales_amount, updated_by, created_by) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id", (*args, by)).fetchone()["id"])
"INSERT INTO live_broadcasts (host_id, broadcast_date, start_time, end_time, venue, tiktok_handle, sales_amount, updated_by, created_by) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id", (*args, by)).fetchone()["id"])
else:
conn.execute("UPDATE live_broadcasts SET host_id=%s, broadcast_date=%s, start_time=%s, end_time=%s, venue=%s, "
"sales_amount=%s, updated_by=%s WHERE id=%s", (*args, broadcast_id))
"tiktok_handle=%s, 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 LiveError("방송 한 건에 이미지는 {max}장까지입니다(지금 {have}장).", max=store.MAX_IMAGES, have=have)
+59
View File
@@ -0,0 +1,59 @@
"""말레이시아 공휴일 표(쿠알라룸푸르 기준, 2026-11-05) — 달력 보기 오른쪽 달력에 표시만 한다(요금·일수 계산에 안 씀).
출처: publicholidays.com.my(KL 2026·2027), 2027 대체휴일은 총리실(JPM) 목록을 옮긴 maukerja.my 기준 — 공식 PDF 원문은 확인하지 못했다.
이슬람 명절(하리라야·이슬람 새해·예언자 탄신일 등)은 달 관측으로 며칠 바뀔 수 있고, 주마다 쉬는 날이 달라 다른 주 지사 생일 등은 넣지 않았다.
shortcut: 해마다 손으로 추가한다 — 2028 목록이 공고되면 여기에 더한다.
"""
from __future__ import annotations
_NAMES: dict[str, tuple[str, str]] = {
"new_year": ("새해", "New Year's Day"),
"thaipusam": ("타이푸삼", "Thaipusam"),
"ft_day": ("연방직할구의 날", "Federal Territory Day"),
"cny": ("음력 설", "Chinese New Year"),
"nuzul": ("코란 계시일", "Nuzul Al-Quran"),
"aidilfitri": ("하리라야 푸아사", "Hari Raya Aidilfitri"),
"labour": ("노동절", "Labour Day"),
"haji": ("하리라야 하지", "Hari Raya Haji"),
"wesak": ("웨삭", "Wesak Day"),
"agong": ("국왕 탄신일", "Agong's Birthday"),
"muharram": ("이슬람 새해", "Awal Muharram"),
"maulud": ("예언자 탄신일", "Maulidur Rasul"),
"merdeka": ("독립기념일", "Merdeka Day"),
"malaysia": ("말레이시아의 날", "Malaysia Day"),
"deepavali": ("디파발리", "Deepavali"),
"christmas": ("크리스마스", "Christmas Day"),
}
# 날짜 → 공휴일. "@" 로 시작 = 대체휴일(일요일·겹친 공휴일 다음 평일).
_DAYS: dict[str, str] = {
"2026-01-01": "new_year", "2026-02-01": "thaipusam", "2026-02-02": "@thaipusam", "2026-02-03": "@ft_day",
"2026-02-17": "cny", "2026-02-18": "cny", "2026-03-07": "nuzul",
"2026-03-20": "aidilfitri", "2026-03-21": "aidilfitri", "2026-03-22": "aidilfitri", "2026-03-23": "@aidilfitri",
"2026-05-01": "labour", "2026-05-27": "haji", "2026-05-31": "wesak", "2026-06-01": "agong", "2026-06-02": "@wesak",
"2026-06-17": "muharram", "2026-08-25": "maulud", "2026-08-31": "merdeka", "2026-09-16": "malaysia",
"2026-11-08": "deepavali", "2026-11-09": "@deepavali", "2026-12-25": "christmas",
"2027-01-01": "new_year", "2027-01-22": "thaipusam", "2027-02-01": "ft_day",
"2027-02-06": "cny", "2027-02-07": "cny", "2027-02-08": "@cny", "2027-02-24": "nuzul",
"2027-03-10": "aidilfitri", "2027-03-11": "aidilfitri", "2027-05-01": "labour", "2027-05-17": "haji", "2027-05-20": "wesak",
"2027-06-06": "muharram", "2027-06-07": "agong", "2027-06-08": "@muharram", "2027-08-15": "maulud", "2027-08-16": "@maulud",
"2027-08-31": "merdeka", "2027-09-16": "malaysia", "2027-10-28": "deepavali", "2027-12-25": "christmas",
}
# 같은 날 둘(2026-02-01 일요일 — 타이푸삼 + 연방직할구의 날)
_ALSO = {"2026-02-01": "ft_day"}
def holiday_names(lang: str = "ko") -> dict[str, str]:
"""{날짜: 이름} — 달력에 넘기는 값. 대체휴일은 한글 '… 대체'(공용 달력이 '대체휴일'로 줄임)·영문 '… (Replacement)'."""
i = 1 if lang == "en" else 0
out = {}
for day, key in _DAYS.items():
name = _NAMES[key.lstrip("@")][i]
if key.startswith("@"):
name += " (Replacement)" if lang == "en" else " 대체"
if day in _ALSO:
name += " · " + _NAMES[_ALSO[day]][i]
out[day] = name
return out
+4 -3
View File
@@ -30,14 +30,14 @@ EN: dict[str, str] = {
"이 달에 등록한 방송이 없습니다.": "No broadcasts this month.",
# 달력
"판매금액": "Sales", "커미션": "Com", "비용": "Fee", "광고비": "Ad Spend", "호스트 비용": "Host Fee", "총 판매금액": "Total Sales",
"ROAS": "ROAS", "합계 & ROAS": "Total & ROAS", "날짜로 이동": "Jump to Date",
"ROAS": "ROAS", "합계 & ROAS": "Total & ROAS",
"팁: 카드 머리를 끌어 옮기거나 맞바꿀 수 있습니다. 오른쪽으로 스크롤하면 이달 {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",
"간단한 이름": "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.",
+46 -18
View File
@@ -6,9 +6,10 @@
POST /live/broadcasts/{id}/move 달력에서 끌어 옮기기(broadcast_date·start_time) 또는 맞바꾸기(swap_with)
POST /live/ad-spend 날짜별 광고비(빈칸 = 지우기)
GET /live/images/{id} 결과 이미지(?thumb=1 = 작은 그림) · POST /live/images/{id}/delete
GET /live/settings 설정 — 호스트 정보(ERP 관리자만, 계좌 등 개인정보)
GET /live/settings 설정 — 호스트 정보(ERP 관리자만, 계좌 등 개인정보. `live_host` 칩은 이름·틱톡·상태만)
POST /live/settings/hosts 호스트 추가·고치기 · POST /live/settings/hosts/{id}/delete
권한: 모듈 권한키 `live`(스케줄), 설정은 ERP 관리자. DB: LIVE_DB_URL(live_db) — 없으면 "설정 필요" 안내.
권한: 모듈 권한키 `live`(스케줄), 설정은 ERP 관리자, `live` + `live_host` 칩 = 새 호스트 등록, `live` + `live_host_edit` 칩 = 고치기(둘 다 개인정보는 안 보임).
DB: LIVE_DB_URL(live_db) — 없으면 "설정 필요" 안내.
저장 요청은 live.js 가 fetch 로 보내고 JSON {ok, message} 를 받는다(틀려도 입력한 값이 창에 남게).
"""
@@ -23,7 +24,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 i18n, store
from . import holidays, i18n, store
router = APIRouter(prefix="/live", tags=["live"])
@@ -61,6 +62,18 @@ def _admin(request: Request) -> dict[str, Any]:
return user
def _can_add_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")
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:
@@ -93,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), "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})
@@ -133,7 +147,7 @@ def index(request: Request, month: str = "") -> Any:
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})
"accounts": st.account_choices(), "max_images": store.MAX_IMAGES})
@router.get("/calendar", response_class=HTMLResponse)
@@ -146,7 +160,8 @@ def calendar(request: Request, month: str = "") -> Any:
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})
"accounts": st.account_choices(), "max_images": store.MAX_IMAGES,
"my_holidays": holidays.holiday_names(lang)})
@router.post("/broadcasts/{broadcast_id}/move")
@@ -196,14 +211,14 @@ def _read_images(files: list[UploadFile]) -> list[dict[str, Any]]:
@router.post("/broadcasts")
def broadcast_save(request: Request, id: str = Form(""), host_id: str = Form(""), broadcast_date: str = Form(""),
start_time: str = Form(""), end_time: str = Form(""), venue: str = Form(""), sales_amount: str = Form(""),
images: list[UploadFile] = File(default=[])) -> JSONResponse:
start_time: str = Form(""), end_time: str = Form(""), venue: str = Form(""), tiktok_handle: str = Form(""),
sales_amount: str = Form(""), images: list[UploadFile] = File(default=[])) -> JSONResponse:
user = _user(request)
st = _db(request)
try:
broadcast_id = _opt_id(id)
values = store.clean_broadcast({"host_id": host_id, "broadcast_date": broadcast_date, "start_time": start_time,
"end_time": end_time, "venue": venue, "sales_amount": sales_amount})
"end_time": end_time, "venue": venue, "tiktok_handle": tiktok_handle, "sales_amount": sales_amount})
st.save_broadcast(broadcast_id, values, _read_images(images), by=user.get("email", ""))
except ValueError as exc:
return _fail(request, exc)
@@ -242,7 +257,7 @@ def image_delete(request: Request, image_id: int) -> JSONResponse:
# ────────────────────────────────────────────────────────────
# 설정 — 호스트 정보(ERP 관리자만: 계좌 등 개인정보)
# 설정 — 호스트 정보(ERP 관리자만: 계좌 등 개인정보). `live_host` 칩 = 새 호스트 등록만.
# ────────────────────────────────────────────────────────────
@router.get("/settings", response_class=HTMLResponse)
def settings(request: Request) -> Any:
@@ -253,22 +268,35 @@ def settings(request: Request) -> Any:
if not isinstance(got, tuple):
return got
st, user = got
if not is_admin(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)
return _render(request, "live/settings.html", user, {"hosts": st.list_hosts()})
# 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(""),
address: str = Form(""), bank_name: str = Form(""), bank_account: str = Form(""), tiktok_handle: 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:
user = _admin(request)
from app.store import is_admin # noqa: WPS433
# `live_host` 칩 = 새 등록, `live_host_edit` 칩 = 고치기(개인정보는 안 보이고, 비워 두면 그대로)
user = _user(request)
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,
"bank_account": bank_account, "tiktok_handle": tiktok_handle})
st.save_host(_opt_id(id), values, is_active=bool(is_active), by=user.get("email", ""))
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})
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, "호스트를 저장했습니다.")
+16 -10
View File
@@ -25,9 +25,11 @@ _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, "tiktok_handle": 64}
_LABELS = {"full_name": "이름 (IC 기준)", "phone": "전화번호", "email": "이메일", "address": "주소", "bank_name": "은행명",
"bank_account": "계좌번호", "tiktok_handle": "틱톡 핸들"}
HOST_LIMITS = {"display_name": 50, "full_name": 200, "phone": 40, "email": 254, "address": 500, "bank_name": 100, "bank_account": 40}
HANDLE_LIMIT = 64
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]+$")
_ACCOUNT_RE = re.compile(r"^[0-9\-\s]+$")
@@ -44,9 +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}
out["tiktok_handle"] = clean_handle(values.get("tiktok_handle"))
if not out["display_name"]:
raise LiveError("간단한 이름을 입력하세요.")
if not out["full_name"]:
raise LiveError("이름 (IC 기준)을 입력하세요.")
for key, limit in HOST_LIMITS.items():
@@ -58,8 +61,6 @@ def clean_host(values: dict[str, Any]) -> dict[str, str]:
raise LiveError("전화번호는 숫자·+·-·괄호만 입력하세요.")
if out["bank_account"] and not _ACCOUNT_RE.match(out["bank_account"]):
raise LiveError("계좌번호는 숫자·-만 입력하세요.")
if out["tiktok_handle"] and not _HANDLE_RE.match(out["tiktok_handle"]):
raise LiveError("틱톡 핸들은 영문·숫자·밑줄·점만 입력하세요.")
return out
@@ -107,8 +108,13 @@ def clean_broadcast(values: dict[str, Any]) -> dict[str, Any]:
end = _parse_time(values.get("end_time"), label="끝 시간", required=True)
if start == end:
raise LiveError("끝 시간이 시작 시간과 같습니다.")
handle = clean_handle(values.get("tiktok_handle"))
if len(handle) > HANDLE_LIMIT:
raise LiveError("{label} 이(가) 너무 깁니다({limit}자까지).", label="틱톡 핸들", limit=HANDLE_LIMIT)
if handle and not _HANDLE_RE.match(handle):
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"))}
"venue": venue, "tiktok_handle": handle, "sales_amount": parse_money(values.get("sales_amount"))}
def parse_move(day: Any, start: Any) -> tuple[date, time]:
@@ -153,12 +159,12 @@ 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(),
"start_time": f"{b['start_time']:%H:%M}", "end_time": f"{b['end_time']:%H:%M}" if b["end_time"] else "",
"venue": b["venue"], "sales_amount": f"{b['sales_amount']:.2f}" if b["sales_amount"] is not None else "",
"venue": b["venue"], "tiktok_handle": b["tiktok_handle"], "sales_amount": f"{b['sales_amount']:.2f}" if b["sales_amount"] is not None else "",
"images": [{"id": i["id"], "filename": i["filename"]} for i in b["images"]]},
}
+2 -2
View File
@@ -11,9 +11,9 @@
</nav>
<span class="lv-gap"></span>
{% include "live/_lang.html" %}
{% if is_admin %}<a class="erp-btn erp-btn-outline" href="/live/settings">{{ t('호스트 설정') }}</a>{% endif %}
{% if can_add_host or can_edit_host %}<a class="erp-btn erp-btn-outline" href="/live/settings">{{ t('호스트 설정') }}</a>{% endif %}
<button type="button" class="erp-btn erp-btn-primary" id="lv-add"{% if not can_add %} disabled{% endif %}>{{ t('+ 방송 추가') }}</button>
</div>
{% if not can_add %}
<p class="lv-note">{{ t('방송을 추가하려면 먼저 호스트를 등록해야 합니다.') }} {% if is_admin %}<a href="/live/settings">{{ t('호스트 설정') }}</a>{% else %}{{ t('ERP 관리자에게 등록을 요청하세요.') }}{% endif %}</p>
<p class="lv-note">{{ t('방송을 추가하려면 먼저 호스트를 등록해야 합니다.') }} {% if can_add_host %}<a href="/live/settings">{{ t('호스트 설정') }}</a>{% else %}{{ t('ERP 관리자에게 등록을 요청하세요.') }}{% endif %}</p>
{% endif %}
+4 -2
View File
@@ -1,4 +1,4 @@
{#- 방송 추가·고치기 창 — 스케줄표·달력 공통(live.js). 호스트 고르기엔 이름·틱톡만(계좌 등은 설정 화면). -#}
{#- 방송 추가·고치기 창 — 스케줄표·달력 공통(live.js). 호스트 고르기엔 이름만(계좌 등은 설정 화면). 틱톡 계정은 방송마다 — 쓴 적 있는 계정을 제안(새 계정도 입력 가능). -#}
<dialog class="lv-dlg" id="lv-dlg" aria-labelledby="lv-dlg-title">
<form id="lv-form" action="/live/broadcasts">
<h3 id="lv-dlg-title" data-add="{{ t('방송 추가') }}" data-edit="{{ t('방송 고치기') }}"></h3>
@@ -6,9 +6,11 @@
<label class="lv-field">{{ t('호스트') }}
<select class="erp-select" name="host_id" required>
<option value="">{{ t('호스트를 고르세요') }}</option>
{% for h in hosts %}<option value="{{ h.id }}"{% if not h.is_active %} data-inactive="1"{% endif %}>{{ h.full_name }}{% if h.tiktok_handle %} (@{{ h.tiktok_handle }}){% endif %}{% if not h.is_active %} — {{ t('사용 안 함') }}{% endif %}</option>{% endfor %}
{% for h in hosts %}<option value="{{ h.id }}"{% if not h.is_active %} data-inactive="1"{% endif %}>{{ h.display_name or h.full_name }}{% if not h.is_active %} — {{ t('사용 안 함') }}{% endif %}</option>{% endfor %}
</select>
</label>
<label class="lv-field">{{ t('틱톡 핸들') }} <input class="erp-input" type="text" name="tiktok_handle" maxlength="200" placeholder="@handle" list="lv-accounts" autocomplete="off" /></label>
<datalist id="lv-accounts">{% for a in accounts %}<option value="{{ a }}"></option>{% endfor %}</datalist>
<div class="lv-row">
<label class="lv-field">{{ t('방송 날짜') }} <input class="erp-input" type="date" name="broadcast_date" required /></label>
<label class="lv-field">{{ t('시작 시간') }} <input class="erp-input" type="time" name="start_time" required /></label>
@@ -1,2 +1,2 @@
<script>window.LV_T = {{ js_text | tojson }};</script>
<script src="/static/live.js?v=20261104c" defer></script>
<script src="/static/live.js?v=20261105c" defer></script>
+12 -8
View File
@@ -1,9 +1,12 @@
{% extends "erp_base.html" %}
{#- 라이브 커머스 달력 보기(2026-11-04) — 줄 = 2시간 칸, 열 = 날짜, 맨 아래 = 날짜별 합계. 카드 머리 = Tiktok Handle(없으면 이름).
{#- 라이브 커머스 달력 보기(2026-11-04) — 줄 = 2시간 칸, 열 = 날짜, 맨 아래 = 날짜별 합계. 카드 머리 = 호스트 간단한 이름 + 그 방송의 틱톡 계정.
카드 머리를 끌어 빈 칸으로 옮기거나 다른 카드 위에 놓아 맞바꾼다(live.js). 문구 = t()(i18n.py), 영문은 CSS 로 대문자(받은 화면과 같게). -#}
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261104c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261105d" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<link rel="stylesheet" href="/static/erp-datepop.css?v=20261102a" />{% endblock %}
{% block content %}
<div class="lv-split">
<section class="lv" lang="{{ lang }}">
{% include "live/_bar.html" %}
@@ -14,10 +17,6 @@
<div class="lv-kpi"><span>ROAS</span><b>{{ cal.totals.roas }}</b></div>
</div>
<nav class="lv-jump" aria-label="{{ t('날짜로 이동') }}">
<span class="lv-jump-label">{{ t('날짜로 이동') }}:</span>
{% for d in cal.days %}<button type="button" class="lv-jump-day{% if d.is_weekend %} is-weekend{% endif %}{% if d.is_today %} is-today{% endif %}" data-jump="{{ d.iso }}">{{ d.day }}</button>{% endfor %}
</nav>
<p class="lv-tip">{{ t('팁: 카드 머리를 끌어 옮기거나 맞바꿀 수 있습니다. 오른쪽으로 스크롤하면 이달 {n}일을 모두 볼 수 있습니다.').format(n=cal.days | length) }}</p>
<div class="lv-cal-wrap" id="lv-cal-wrap">
@@ -43,7 +42,7 @@
<article class="lv-card" data-card="{{ c.id }}">
<header class="lv-card-head" draggable="true" style="background:{{ c.color }}" title="{{ c.host_name }} · {{ c.times }}{% if c.venue %} · {{ c.venue }}{% endif %}">
<span class="lv-card-grip" aria-hidden="true">✥</span>
<span class="lv-card-name">{{ c.label }}</span>
<span class="lv-card-name">{{ c.label }}{% if c.tiktok_handle %}<small>@{{ c.tiktok_handle }}</small>{% endif %}</span>
<button type="button" class="lv-card-edit" data-edit='{{ c.edit | tojson }}' aria-label="{{ t('{name} {date} {times} 고치기').format(name=c.label, date=c.date, times=c.times) }}">✎</button>
</header>
<div class="lv-card-nums">
@@ -79,8 +78,13 @@
</table>
</div>
</section>
{#- 화면 오른쪽 위에 붙는 달력 — 날짜를 누르면 그 날이 표 맨 왼쪽(live.js), 말레이시아 공휴일(holidays.py) -#}
<aside class="lv-side-cal" id="lv-side-cal"></aside>
</div>
{% include "live/_dialog.html" %}
{% endblock %}
{% block scripts %}{% include "live/_scripts.html" %}{% endblock %}
{% block scripts %}<script type="application/json" id="lv-my-holidays">{{ my_holidays | tojson }}</script>
<script src="/static/erp-datepop.js?v=20261105a" defer></script>
{% include "live/_scripts.html" %}{% endblock %}
+1 -1
View File
@@ -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=20261104c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261105d" />{% endblock %}
{% block content %}
<section class="lv" lang="{{ lang }}">
+19 -9
View File
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{#- 라이브 커머스 설정(2026-11-04) — 호스트 정보. 계좌 등 개인정보라 ERP 관리자만(router.settings). 추가·고치기는 같은 창(live.js). 문구 = t()(i18n.py). -#}
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261104c" />{% endblock %}
{#- 라이브 커머스 설정(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=20261105d" />{% endblock %}
{% block content %}
<section class="lv" lang="{{ lang }}">
@@ -9,31 +9,40 @@
<h2 class="lv-month">{{ t('호스트 설정') }}</h2>
<span class="lv-gap"></span>
{% include "live/_lang.html" %}
<button type="button" class="erp-btn erp-btn-primary" id="lv-add">{{ t('+ 호스트 등록') }}</button>
{% if can_add_host %}<button type="button" class="erp-btn erp-btn-primary" id="lv-add">{{ t('+ 호스트 등록') }}</button>{% endif %}
</div>
<div class="erp-card-block">
<div class="erp-table-wrap">
<table class="erp-table lv-table">
<thead><tr><th>{{ t('이름 (IC 기준)') }}</th><th>{{ t('전화번호') }}</th><th>{{ t('이메일') }}</th><th>{{ t('주소') }}</th><th>{{ t('은행명') }}</th><th>{{ t('계좌번호') }}</th><th>{{ t('틱톡 핸들') }}</th><th>{{ t('상태') }}</th><th></th></tr></thead>
<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>
<tbody>
{% for h in hosts %}
<tr{% if not h.is_active %} class="lv-off"{% endif %}>
<td data-label="{{ t('간단한 이름') }}">{{ h.display_name }}</td>
<td data-label="{{ t('이름 (IC 기준)') }}">{{ h.full_name }}</td>
{% if is_admin %}
<td class="lv-nowrap" data-label="{{ t('전화번호') }}">{{ h.phone }}</td>
<td data-label="{{ t('이메일') }}">{{ h.email }}</td>
<td data-label="{{ t('주소') }}">{{ h.address }}</td>
<td data-label="{{ t('은행명') }}">{{ h.bank_name }}</td>
<td class="lv-nowrap" data-label="{{ t('계좌번호') }}">{{ h.bank_account }}</td>
<td data-label="{{ t('틱톡 핸들') }}">{% if h.tiktok_handle %}@{{ h.tiktok_handle }}{% endif %}</td>
{% endif %}
<td class="lv-nowrap" data-label="{{ t('상태') }}">{{ t('사용') if h.is_active else t('사용 안 함') }}</td>
{% if can_edit_host %}
<td class="lv-actions">
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-edit='{{ {"id": h.id, "full_name": h.full_name, "phone": h.phone, "email": h.email, "address": h.address, "bank_name": h.bank_name, "bank_account": h.bank_account, "tiktok_handle": h.tiktok_handle, "is_active": h.is_active} | tojson }}'>{{ t('고치기') }}</button>
{% 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-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>
{% endif %}
</td>
{% endif %}
</tr>
{% else %}
<tr><td colspan="9" class="erp-empty">{{ t('등록한 호스트가 없습니다.') }}</td></tr>
<tr><td colspan="{{ 9 if is_admin else 4 if can_edit_host else 3 }}" class="erp-empty">{{ t('등록한 호스트가 없습니다.') }}</td></tr>
{% endfor %}
</tbody>
</table>
@@ -45,7 +54,9 @@
<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" />
<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 %}
<label class="lv-field">{{ t('전화번호') }} <input class="erp-input" type="tel" name="phone" maxlength="40" /></label>
<label class="lv-field">{{ t('이메일') }} <input class="erp-input" type="email" name="email" maxlength="254" /></label>
<label class="lv-field">{{ t('주소') }} <textarea class="erp-input" name="address" rows="2" maxlength="500"></textarea></label>
@@ -53,8 +64,7 @@
<label class="lv-field">{{ t('은행명') }} <input class="erp-input" type="text" name="bank_name" maxlength="100" /></label>
<label class="lv-field">{{ t('계좌번호') }} <input class="erp-input" type="text" name="bank_account" maxlength="40" inputmode="numeric" /></label>
</div>
<label class="lv-field">{{ t('틱톡 핸들') }} <input class="erp-input" type="text" name="tiktok_handle" maxlength="200" placeholder="@handle" /></label>
<label class="lv-check"><input type="checkbox" name="is_active" value="1" checked /> {{ t('사용 (끄면 새 방송에서 고를 수 없습니다)') }}</label>
{% if can_edit_host %}<label class="lv-check"><input type="checkbox" name="is_active" value="1" checked /> {{ t('사용 (끄면 새 방송에서 고를 수 없습니다)') }}</label>{% endif %}
<p class="lv-msg" data-msg role="alert" hidden></p>
<div class="lv-foot">
<button type="button" class="erp-btn erp-btn-outline" data-close>{{ t('취소') }}</button>
+9 -1
View File
@@ -106,9 +106,17 @@
- **표 몸통 칸에는 풍선 도움말(title) 없음**(2026-10-22 사용자 요청) — 입력 칸·날짜 칸(공휴일은 칸 안 글자)·광고비 줄 모두. 열 머리글 말풍선은 그대로.
새 칸 기능에 title 을 다시 달지 말 것(설명은 표 아래 안내 문구에).
## 틱톡 (`/performance/tiktok`, 2026-11-05, 마이그레이션 없음)
- 광고비 탭 틀(기간 이동·KPI·표·그래프·연 누적), 표 열 = ROAS·광고비·매출. 값은 광고 API 만(읽기 전용, 칸 입력·메모 없음). 화면 데이터 `ad_spend.build_tiktok_dashboard`.
- **틱톡 탭에서만 보임** — 채널 코드 `tiktok` 은 `ad_sources` 에는 있지만 `ad_spend.CHANNELS` 에는 넣지 않는다(넣으면 광고비 탭 합계에 들어감). 쇼핑몰 표(`perf_marketplaces`)에도 없어 매출 실적 합계·열과 무관. 저장은 다른 광고 API 처럼 `perf_ad_spend`(`source='api'`), 매출 = `metrics["매출"]`.
- 설정 = 실적 설정 **광고 API 연동** 카드 → 틱톡 — 광고 계정 ID·장기 액세스 토큰·틱톡샵 ID(선택). [광고비 업데이트]·광고비 자동 업데이트에 함께 돈다.
- `ad_sources/tiktok_ads.py` — `report/integrated/get`(30일씩), 매출 = 웹 구매금액 + 틱톡샵 매출, 틱톡샵 ID 가 있으면 `gmv_max/report/get` 비용·매출도 더함(항목별 값은 metrics 에 따로 저장). 외화 계정은 그날 환율로 원화(`fx`). ROAS = 매출 ÷ 광고비.
**실제 토큰 대조 전**(2026-11-05) — 공식 문서를 읽지 못해 지표 이름은 이차 자료로 확인. 일반 보고서에 GMV Max 가 이미 들어 있으면 틱톡샵 ID 를 넣었을 때 중복되므로, 처음 쓸 때 광고 관리자 화면과 대조할 것.
## 광고비 (`/performance/ads`)
- 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니.
- 탭은 [매출 실적]·[광고비]·[틱톡] + 맨 오른쪽 설정 톱니.
- **표 모양(2026-10-22)** — 매출 실적 표와 같은 `perf-autofit`(열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정).
- **기타광고비** 열(`etc`, 애터미아자몰 오른쪽, 2026-10-22) — 쇼핑몰에 딸리지 않은 광고비 직접 입력. 매출 쇼핑몰이 없어(`ad_spend.NO_SALES`) ROAS 없음·매출 탭 광고비 줄에 안 나옴, 광고비 합계·매출 대비 광고비에는 들어감.
- `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`. 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로.
@@ -1,12 +1,14 @@
"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다)."""
"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다 —
틱톡만 예외: 광고비 탭에 안 나오게 CHANNELS 에 넣지 않고 틱톡 탭이 따로 읽는다)."""
from __future__ import annotations
from .base import AdSource
from .google_ads import GoogleAdsSource
from .meta_ads import MetaAdsSource
from .tiktok_ads import TiktokAdsSource
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource())
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource(), TiktokAdsSource())
_BY_CODE = {s.code: s for s in _SOURCES}
@@ -0,0 +1,202 @@
"""틱톡 광고(TikTok API for Business v1.3) — 날짜별 광고비·매출·ROAS. 화면은 틱톡 탭(광고비 탭·매출 실적에는 안 나옴).
인증(2026-11-05): 광고 계정(advertiser) ID 하나 + 장기 액세스 토큰(머리글 Access-Token). 토큰 앱에 보고서·광고 계정 읽기 권한이 있어야 한다.
조회
GET /report/integrated/get/ — report_type=BASIC · data_level=AUCTION_ADVERTISER · 차원 advertiser_id·stat_time_day.
매출 = 웹 구매금액(total_complete_payment_rate — 이름과 달리 금액) + 틱톡샵 매출(total_onsite_shopping_value).
GET /gmv_max/report/get/ — 틱톡샵 ID 를 넣었을 때만. 비용(cost)·매출(gross_revenue)을 더한다.
- 하루 단위 조회는 기간 제한이 있어 30일씩 나눠 묻는다.
- 금액은 광고 계정 통화 → 그날 환율로 원화(fx.krw_rates, 메타와 같음).
- ROAS(%) = 매출 ÷ 광고비 × 100(합친 값으로 계산 — 틱톡의 ROAS 칸은 더할 수 없다).
공식 문서가 스크립트 화면이라 지표 이름을 이차 자료로 확인했다 — 연결 테스트가 어제 하루를 실제로 물어 지표 이름 오류까지 잡는다.
"""
from __future__ import annotations
import json
import re
from datetime import date, timedelta
from decimal import ROUND_HALF_UP, Decimal
from typing import Any
import httpx
from app.timezone import today_kst
from .. import fx
from ..adapters.base import AdapterContext, ApiError, AuthFailed, CredentialField, TokenExpired
from .base import AdDay, AdSource
from .meta_ads import _num, _won
API_BASE = "https://business-api.tiktok.com/open_api/v1.3"
MAX_DAYS = 366
SPAN_DAYS = 30
PAGE_SIZE = 100 # 계정 하나·30일 = 많아야 30줄이라 한 쪽이면 된다
RATE_LIMIT = 40100
REPORT_METRICS = ("spend", "impressions", "clicks", "complete_payment", "total_complete_payment_rate",
"onsite_shopping", "total_onsite_shopping_value")
GMV_METRICS = ("cost", "gross_revenue", "orders")
# metrics 키 — 화면 이름 그대로 저장. 틱톡 탭은 M_REVENUE 를 매출로 읽는다(ad_spend.build_tiktok_dashboard).
M_SPEND, M_REVENUE, M_ROAS = "광고비", "매출", "ROAS(%)"
M_IMPR, M_CLICKS, M_ORDERS = "노출수", "클릭수", "구매수"
M_WEB, M_SHOP, M_GMV_COST, M_GMV_REVENUE = "웹 구매금액", "틱톡샵 매출", "GMV Max 비용", "GMV Max 매출"
def _http(ctx: AdapterContext) -> httpx.Client:
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
return httpx.Client(timeout=ctx.timeout_sec)
def _spans(start: date, end: date) -> list[tuple[date, date]]:
"""기간을 SPAN_DAYS 일씩 나눈다."""
out = []
while start <= end:
stop = min(start + timedelta(days=SPAN_DAYS - 1), end)
out.append((start, stop))
start = stop + timedelta(days=1)
return out
class TiktokAdsSource(AdSource):
code = "tiktok"
name = "틱톡"
docs_url = "https://business-api.tiktok.com/portal/docs"
note = ("TikTok API for Business 로 날짜별 광고비·매출·ROAS 를 가져와 틱톡 탭에 보여 줍니다(매출 실적·광고비 탭 합계에는 들어가지 않음). "
"준비: 개발자 앱에서 광고 계정을 승인해 장기 액세스 토큰 발급(보고서·광고 계정 읽기 권한). 외화 계정은 그날 환율로 원화로 바꿉니다.")
def credential_fields(self) -> list[CredentialField]:
return [
CredentialField("advertiser_id", "광고 계정 ID", placeholder="7123456789012345678",
help="틱톡 광고 관리자 주소의 aadvid= 뒤 숫자."),
CredentialField("access_token", "액세스 토큰", secret=True,
help="광고 계정을 승인할 때 받은 장기 액세스 토큰. 저장 후에는 화면에 다시 보이지 않습니다."),
CredentialField("shop_id", "틱톡샵 ID", required=False, placeholder="GMV Max 캠페인을 쓸 때만",
help="GMV Max 캠페인은 일반 보고서와 따로 조회합니다 — 넣으면 그 비용·매출도 더합니다. 안 쓰면 비워 둡니다."),
]
def validate_credentials(self, values: dict[str, str]) -> list[str]:
errors = super().validate_credentials(values)
advertiser = (values.get("advertiser_id") or "").strip()
if advertiser and advertiser != "__stored__" and not re.fullmatch(r"\d{5,30}", advertiser):
errors.append("광고 계정 ID 는 숫자여야 합니다.")
shop = (values.get("shop_id") or "").strip()
if shop and shop != "__stored__" and not re.fullmatch(r"\d{5,30}", shop):
errors.append("틱톡샵 ID 는 숫자여야 합니다.")
token = (values.get("access_token") or "").strip()
if token and token != "__stored__" and (len(token) < 20 or re.search(r"\s", token)):
errors.append("액세스 토큰 형식이 아닙니다(공백 없이 통째로 붙여 넣으세요).")
return errors
def _get(self, ctx: AdapterContext, client: httpx.Client, path: str, params: dict[str, Any]) -> dict[str, Any]:
"""틱톡은 오류도 HTTP 200 + code 로 준다. 토큰은 머리글로만 보내 주소·오류 문구에 들어가지 않는다."""
ctx.progress.check()
token = (ctx.credentials.get("access_token") or "").strip()
try:
resp = client.get(API_BASE + path, params=params, headers={"Access-Token": token})
except httpx.HTTPError as exc:
raise ApiError(f"틱톡 API 에 연결하지 못했습니다({type(exc).__name__}).") from None
try:
body = resp.json()
except ValueError:
raise ApiError(f"틱톡 API 응답을 읽을 수 없습니다(HTTP {resp.status_code}).") from None
code = body.get("code") if isinstance(body, dict) else None
if resp.status_code == 200 and code == 0:
return body.get("data") or {}
text = f"틱톡 API 오류({code if code is not None else resp.status_code}): {str((body or {}).get('message') or '')[:200]}"
if code == 40102:
raise TokenExpired(text + " — 액세스 토큰을 다시 발급해 넣으세요.")
if code == RATE_LIMIT:
raise ApiError(text + " — 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.")
if resp.status_code in (401, 403) or (isinstance(code, int) and 40100 < code < 40200):
raise AuthFailed(text + " — 토큰과 광고 계정 ID, 앱 권한을 확인하세요.")
raise ApiError(text)
def _info(self, ctx: AdapterContext, client: httpx.Client) -> dict[str, Any]:
advertiser = (ctx.credentials.get("advertiser_id") or "").strip()
rows = self._get(ctx, client, "/advertiser/info/", {
"advertiser_ids": json.dumps([advertiser]), "fields": json.dumps(["name", "currency", "timezone"])}).get("list") or []
if not rows:
raise AuthFailed("이 토큰으로 볼 수 없는 광고 계정입니다 — 광고 계정 ID 와 승인 여부를 확인하세요.")
return rows[0]
def _rows(self, ctx: AdapterContext, client: httpx.Client, path: str, metrics: tuple[str, ...], start: date, end: date,
**extra: Any) -> list[tuple[date, dict[str, Any]]]:
"""보고서 하나를 30일씩 물어 (날짜, 지표) 목록으로."""
advertiser = (ctx.credentials.get("advertiser_id") or "").strip()
out = []
for s, e in _spans(start, end):
data = self._get(ctx, client, path, {
"advertiser_id": advertiser, "dimensions": json.dumps(["advertiser_id", "stat_time_day"]), "metrics": json.dumps(metrics),
"start_date": s.isoformat(), "end_date": e.isoformat(), "page": 1, "page_size": PAGE_SIZE, **extra})
for r in data.get("list") or []:
try:
day = date.fromisoformat(str((r.get("dimensions") or {}).get("stat_time_day"))[:10])
except ValueError:
continue
out.append((day, r.get("metrics") or {}))
return out
def _collect(self, ctx: AdapterContext, client: httpx.Client, start: date, end: date) -> dict[date, dict[str, Decimal]]:
"""날짜 → 항목 합(계정 통화)."""
sums: dict[date, dict[str, Decimal]] = {}
def day_of(d: date) -> dict[str, Decimal]:
return sums.setdefault(d, {k: Decimal(0) for k in ("spend", "impr", "clicks", "orders", "web", "shop", "gmv_cost", "gmv")})
for d, m in self._rows(ctx, client, "/report/integrated/get/", REPORT_METRICS, start, end,
report_type="BASIC", data_level="AUCTION_ADVERTISER"):
one = day_of(d)
one["spend"] += _num(m.get("spend"))
one["impr"] += _num(m.get("impressions"))
one["clicks"] += _num(m.get("clicks"))
one["orders"] += _num(m.get("complete_payment")) + _num(m.get("onsite_shopping"))
one["web"] += _num(m.get("total_complete_payment_rate"))
one["shop"] += _num(m.get("total_onsite_shopping_value"))
shop_id = (ctx.credentials.get("shop_id") or "").strip()
if shop_id:
for d, m in self._rows(ctx, client, "/gmv_max/report/get/", GMV_METRICS, start, end, store_ids=json.dumps([shop_id])):
one = day_of(d)
one["orders"] += _num(m.get("orders"))
one["gmv_cost"] += _num(m.get("cost"))
one["gmv"] += _num(m.get("gross_revenue"))
return sums
def test_connection(self, ctx: AdapterContext) -> str:
self.require_configured(ctx)
yesterday = today_kst() - timedelta(days=1)
with _http(ctx) as client:
info = self._info(ctx, client)
self._collect(ctx, client, yesterday, yesterday) # 지표 이름·GMV Max 권한까지 실제로 확인
return f"연결됨 — {info.get('name') or '광고 계정'}({info.get('currency') or '?'}·{info.get('timezone') or '?'})"
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
if end < start:
start, end = end, start
if (end - start).days + 1 > MAX_DAYS:
raise ApiError(f"한 번에 {MAX_DAYS}일까지 가져올 수 있습니다.")
self.require_configured(ctx)
with _http(ctx) as client:
currency = str(self._info(ctx, client).get("currency") or "").upper()
if not re.fullmatch(r"[A-Z]{3}", currency):
raise ApiError(f"광고 계정 통화({currency[:10] or '없음'})를 알 수 없습니다.")
sums = self._collect(ctx, client, start, end)
try:
rates = fx.krw_rates(client, currency, start, end) if sums else {}
except fx.FxError as exc:
raise ApiError(f"{currency} 광고 계정을 원화로 바꿀 환율을 가져오지 못했습니다 — {exc}") from None
return [_day(d, sums[d], rates[d]) for d in sorted(sums)]
def _day(day: date, a: dict[str, Decimal], rate: Decimal) -> AdDay:
"""합친 값(계정 통화) → 하루치(원화). ROAS 는 비율이라 반올림 전 값으로."""
spend = (a["spend"] + a["gmv_cost"]) * rate
revenue = (a["web"] + a["shop"] + a["gmv"]) * rate
roas = (revenue / spend * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if spend > 0 else None
return AdDay(day=day, amount=_won(spend), roas=roas, metrics={
M_SPEND: _won(spend), M_REVENUE: _won(revenue), M_ROAS: float(roas) if roas is not None else None,
M_WEB: _won(a["web"] * rate), M_SHOP: _won(a["shop"] * rate), M_GMV_COST: _won(a["gmv_cost"] * rate), M_GMV_REVENUE: _won(a["gmv"] * rate),
M_IMPR: int(a["impr"]), M_CLICKS: int(a["clicks"]), M_ORDERS: int(a["orders"]),
})
+84 -25
View File
@@ -22,12 +22,13 @@ from __future__ import annotations
import csv
import io
from dataclasses import dataclass, field
from datetime import date
from datetime import date, timedelta
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
from typing import Any, Callable, Mapping, Sequence
from . import calc
from .ad_sources.base import ACCOUNTS_KEY
from .ad_sources.tiktok_ads import M_REVENUE as TIKTOK_REVENUE_KEY
from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date
# 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang).
@@ -57,6 +58,7 @@ NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널)
NO_SALES = frozenset({"etc"}) # 매출 쇼핑몰이 없는 채널 — ROAS 를 계산하지 않고 매출 탭 광고비 줄에도 안 나온다
ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in FILE_ROAS and c not in NO_SALES}
ROAS_SALES_CODE["coupang_wing"] = "coupang"
TIKTOK = "tiktok" # 광고 API 채널이지만 CHANNELS 에 없다 — 틱톡 탭(build_tiktok_dashboard)에서만 보인다
def roas(sales: int, spend: int) -> int | None:
@@ -476,6 +478,85 @@ def detail_tabs(rows: list[dict[str, Any]]) -> dict[str, Any]:
# ════════════════════════════════════════════════════════════
# 화면 데이터
# ════════════════════════════════════════════════════════════
def _period_word(period: Any, today: date) -> str:
"""KPI 이름 앞 말 — 이번달·해당 월 등."""
return {"day": "오늘" if period.start == today else "해당일",
"week": "이번주" if period.start <= today <= period.end else "해당 주",
"month": "이번달" if period.start <= today <= period.end else "해당 월",
"year": "올해" if period.start <= today <= period.end else "해당 연도",
"custom": "선택 기간"}[period.kind]
def _period_nav(period: Any, today: date) -> dict[str, Any]:
"""기간 이동 화살표·빠른 선택(이번달·올해만 — 2026-10-26 오늘·이번주 버튼 삭제, 매출 실적과 같게)."""
def url(k: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
if k == "custom":
return f"?period=custom&from={start.isoformat()}&to={end.isoformat()}"
return f"?period={k}&d={anchor_d.isoformat()}"
if period.kind == "custom":
length = timedelta(days=period.days)
prev_url = url("custom", start=period.start - length, end=period.start - timedelta(days=1))
next_url = url("custom", start=period.end + timedelta(days=1), end=period.end + length)
else:
prev_url, next_url = url(period.kind, period.prev_anchor), url(period.kind, period.next_anchor)
return {"prev": prev_url, "next": next_url, "quick": [
{"label": "이번달", "url": url("month", today), "active": period.kind == "month" and period.start <= today <= period.end},
{"label": "올해", "url": url("year", today), "active": period.kind == "year" and period.start <= today <= period.end},
]}
def build_tiktok_dashboard(store: Any, *, kind: str, anchor: date, today: date, custom_from: date | None = None,
custom_to: date | None = None, holidays: Mapping[str, str] | None = None) -> dict[str, Any]:
"""틱톡 탭(2026-11-05) — 광고비 탭과 같은 기간 이동·표·그래프, 열 = ROAS·광고비·매출. 광고 API 가 저장한 perf_ad_spend 만 읽는다.
CHANNELS 에 없어 광고비 탭·매출 실적 합계에는 들어가지 않는다."""
period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to)
cmp_start, cmp_end, cmp_label = period.compare_range(today)
ref = period.end if period.end < today else today if period.start <= today else period.start
year_period = calc.resolve_period("year", ref)
migration_needed = False
try:
rows = store.ad_details(TIKTOK, min(period.start, cmp_start, year_period.start), max(period.end, year_period.end))
except AdMigrationNeeded:
rows, migration_needed = [], True
cells: dict[tuple[date, str], calc.Money] = {}
for r in rows:
d = date.fromisoformat(r["date"])
cells[(d, "spend")] = calc.Money(gross=int(r["amount"] or 0))
cells[(d, "sales")] = calc.Money(gross=int((r["metrics"] or {}).get(TIKTOK_REVENUE_KEY) or 0))
table = calc.main_table(period, ("spend", "sales"), cells, today=today, holidays=holidays)
for row in table:
row["roas"] = roas(row["cells"]["sales"]["gross"], row["cells"]["spend"]["gross"])
cur = {c: calc.sum_range(cells, [c], period.start, period.end).gross for c in ("spend", "sales")}
prev = {c: calc.sum_range(cells, [c], cmp_start, cmp_end).gross for c in ("spend", "sales")}
word = _period_word(period, today)
spend_y = calc.year_months(year_period.start.year, ["spend"], cells, today=today)
sales_y = calc.year_months(year_period.start.year, ["sales"], cells, today=today)
year_rows = [{"label": a["label"], "future": a["future"], "spend": a["gross"], "sales": b["gross"],
"roas": None if a["future"] else roas(b["gross"], a["gross"])}
for a, b in zip(spend_y["rows"], sales_y["rows"])]
return {
"nav": _period_nav(period, today),
"period": period,
"period_kind": period.kind,
"today": today.isoformat(),
"kpis": [
{"key": "spend", "label": f"{word} 광고비", "value": cur["spend"], "primary": True,
"delta": calc.pct_change(cur["spend"], prev["spend"]), "cmp": cmp_label, "invert": True},
{"key": "sales", "label": f"{word} 매출", "value": cur["sales"],
"delta": calc.pct_change(cur["sales"], prev["sales"]), "cmp": cmp_label},
{"key": "roas", "label": f"{word} ROAS", "pct": roas(cur["sales"], cur["spend"])},
],
"table": table,
"chart_sales": calc.daily_series(period, ["sales"], cells),
"chart_spend": calc.daily_series(period, ["spend"], cells),
"year": {"year": year_period.start.year, "rows": year_rows, "spend": spend_y["total"]["gross"], "sales": sales_y["total"]["gross"],
"roas": roas(sales_y["total"]["gross"], spend_y["total"]["gross"])},
"migration_needed": migration_needed,
}
def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
custom_from: date | None = None, custom_to: date | None = None,
holidays: Mapping[str, str] | None = None,
@@ -522,11 +603,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
sales_total = sales_sum(total_codes, period.start, period.end) if total_codes else None
ratio = round(cur.gross / sales_total * 100, 1) if sales_total and sales_total > 0 else None
word = {"day": "오늘" if period.start == today else "해당일",
"week": "이번주" if period.start <= today <= period.end else "해당 주",
"month": "이번달" if period.start <= today <= period.end else "해당 월",
"year": "올해" if period.start <= today <= period.end else "해당 연도",
"custom": "선택 기간"}[period.kind]
word = _period_word(period, today)
kpis = [
{"key": "spend", "label": f"{word} 광고비", "value": cur.gross, "primary": True,
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label, "invert": True},
@@ -536,25 +613,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
"delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_cmp_label, "invert": True},
]
def url(k: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
if k == "custom":
return f"?period=custom&from={start.isoformat()}&to={end.isoformat()}"
return f"?period={k}&d={anchor_d.isoformat()}"
if period.kind == "custom":
from datetime import timedelta # noqa: WPS433
length = timedelta(days=period.days)
prev_url = url("custom", start=period.start - length, end=period.start - timedelta(days=1))
next_url = url("custom", start=period.end + timedelta(days=1), end=period.end + length)
else:
prev_url, next_url = url(period.kind, period.prev_anchor), url(period.kind, period.next_anchor)
# 빠른 선택은 이번달·올해만(2026-10-26 — 오늘·이번주 버튼 삭제, 매출 실적과 같게)
nav = {"prev": prev_url, "next": next_url, "quick": [
{"label": "이번달", "url": url("month", today), "active": period.kind == "month" and period.start <= today <= period.end},
{"label": "올해", "url": url("year", today), "active": period.kind == "year" and period.start <= today <= period.end},
]}
nav = _period_nav(period, today)
share = calc.by_code(cells, codes, period.start, period.end)
month = calc.month_summary(month_period.start.year, month_period.start.month, codes, cells)
table = calc.main_table(period, codes, cells, today=today, holidays=holidays)
+35 -4
View File
@@ -241,8 +241,15 @@ def ads_page(
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(),
sales_codes=total_sales_codes(_sales_marketplaces(store)),
)
# [광고비 업데이트](2026-10-20) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로.
# 마지막 업데이트 = 광고 API 마지막 성공 가져오기, 다음 업데이트 = 매출 자동 업데이트와 같은 회차.
_ad_update_ctx(store, user, ctx)
_colw_ctx(request, ctx)
return render_template(request, "performance/ads.html",
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
def _ad_update_ctx(store: Any, user: dict[str, Any], ctx: dict[str, Any]) -> None:
"""[광고비 업데이트](2026-10-20, 광고비·틱톡 탭 공통) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로.
마지막 업데이트 = 광고 API 마지막 성공 가져오기, 다음 업데이트 = 매출 자동 업데이트와 같은 회차."""
from . import jobs # noqa: WPS433
from .ad_sources.registry import get_source # noqa: WPS433
from .ad_sync import last_ad_update_at # noqa: WPS433
@@ -257,9 +264,33 @@ def ads_page(
ctx["ad_running"] = jobs.running_job("ads") is not None
ctx["auto_sync"] = _auto_sync_ctx(store, "ads")
ctx["update_watch"] = _update_watch("ads", user)
@router.get("/tiktok", response_class=HTMLResponse)
def tiktok_page(
request: Request,
period: str = "month",
d: str | None = None,
from_: str | None = Query(None, alias="from"),
to: str | None = None,
):
"""틱톡 탭(2026-11-05) — 일자별 ROAS·광고비·매출(광고 API 값, 읽기 전용). 설정 = 실적 설정 → 광고 API 연동."""
from app.main import render_template # noqa: WPS433
g = common.guard(request)
if not isinstance(g, tuple):
return g
store, user = g
from .ad_spend import build_tiktok_dashboard # noqa: WPS433
today = today_kst()
ctx = build_tiktok_dashboard(store, kind=period, anchor=_parse_date(d) or today, today=today,
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays())
_ad_update_ctx(store, user, ctx)
ctx["tiktok_configured"] = any(s["code"] == "tiktok" for s in ctx["ad_sync_sources"])
_colw_ctx(request, ctx)
return render_template(request, "performance/ads.html",
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
return render_template(request, "performance/tiktok.html",
{**common.base_ctx(user, active_tab="tiktok", page_title="틱톡"), **ctx})
@router.get("/settings", response_class=HTMLResponse)
@@ -0,0 +1,15 @@
{# 광고비 업데이트(2026-10-20, 광고비·틱톡 탭 공통) — 매출 탭과 같은 모양: 마지막 업데이트(광고 API 마지막 성공) · 다음 자동 업데이트(실적 설정의 광고비 일정)
· [광고비 업데이트](설정된 광고 API 전부, 진행 창). 업데이트 중에도 누르면 진행 창을 다시 연다. #}
{% if ad_sync_sources %}
<div class="perf-update">
<span class="perf-muted" id="perf-last-update" title="광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }}) 마지막 업데이트">마지막 업데이트
<b>{{ (ad_last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
{% if auto_sync %}
<span class="perf-muted perf-next-update" id="perf-next-update" title="광고비 자동 업데이트: {{ auto_sync.label }} (실적 설정에서 바꿈)">다음 업데이트까지 <b>—</b></span>
{% endif %}
<button type="button" class="erp-btn erp-btn-primary{% if ad_running %} is-running{% endif %}" id="perf-ad-sync-btn"
title="{% if ad_running %}업데이트 진행 상황 보기{% else %}지금 보고 있는 기간({{ period.label }}, 오늘까지)의 광고비·ROAS 를 광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }})에서 다시 가져옵니다{% endif %}">
{% if ad_running %}업데이트 중 · 진행 보기{% else %}광고비 업데이트{% endif %}
</button>
</div>
{% endif %}
@@ -1,4 +1,4 @@
{# 실적 모듈 탭 — [매출 실적] [광고비] 큰 탭 둘(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
{# 실적 모듈 탭 — [매출 실적] [광고비] [틱톡] 큰 탭(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<nav class="perf-tabs" aria-label="실적 메뉴">
@@ -9,6 +9,9 @@
<a class="perf-tab perf-tab-ads{% if active_tab == 'ads' %} is-active{% endif %}" href="/performance/ads"
role="tab" aria-selected="{{ 'true' if active_tab == 'ads' else 'false' }}">
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>광고비</a>
<a class="perf-tab perf-tab-tiktok{% if active_tab == 'tiktok' %} is-active{% endif %}" href="/performance/tiktok"
role="tab" aria-selected="{{ 'true' if active_tab == 'tiktok' else 'false' }}">
<span class="material-symbols-outlined" aria-hidden="true">music_note</span>틱톡</a>
</div>
<a class="perf-tab-gear{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings"
title="{{ '실적 설정' if is_admin else '수수료 설정' }}" aria-label="{{ '실적 설정' if is_admin else '수수료 설정' }}">
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261102b" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% endblock %}
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
@@ -34,21 +34,7 @@
<button class="erp-btn erp-btn-outline" type="submit">조회</button>
</form>
{# 광고비 업데이트(2026-10-20) — 매출 탭과 같은 모양: 마지막 업데이트(광고 API 마지막 성공) · 다음 자동 업데이트(실적 설정의 광고비 일정)
· [광고비 업데이트](설정된 광고 API 전부, 진행 창). 업데이트 중에도 누르면 진행 창을 다시 연다. #}
{% if ad_sync_sources %}
<div class="perf-update">
<span class="perf-muted" id="perf-last-update" title="광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }}) 마지막 업데이트">마지막 업데이트
<b>{{ (ad_last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
{% if auto_sync %}
<span class="perf-muted perf-next-update" id="perf-next-update" title="광고비 자동 업데이트: {{ auto_sync.label }} (실적 설정에서 바꿈)">다음 업데이트까지 <b>—</b></span>
{% endif %}
<button type="button" class="erp-btn erp-btn-primary{% if ad_running %} is-running{% endif %}" id="perf-ad-sync-btn"
title="{% if ad_running %}업데이트 진행 상황 보기{% else %}지금 보고 있는 기간({{ period.label }}, 오늘까지)의 광고비·ROAS 를 광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }})에서 다시 가져옵니다{% endif %}">
{% if ad_running %}업데이트 중 · 진행 보기{% else %}광고비 업데이트{% endif %}
</button>
</div>
{% endif %}
{% include "performance/_ad_update.html" %}
</div>
<div class="perf-notice" id="perf-sync-result" hidden></div>
@@ -237,4 +223,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261105a" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261102b" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
@@ -294,4 +294,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261105a" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261102b" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -255,7 +255,7 @@
<div class="erp-card perf-card" id="perf-ad-sources">
<div class="perf-card-head">
<h2 class="perf-h">광고 API 연동</h2>
<span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
<span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 틱톡은 틱톡 탭에서만 보입니다(매출 실적·광고비 탭 합계 제외). 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
설정이 끝나면 광고비 탭 [광고비 업데이트]와 광고비 자동 업데이트(위 "자동 업데이트" 일정) 때 가져옵니다.</span>
</div>
{% if not ad_api_ready %}
@@ -347,4 +347,4 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261105a" defer></script>{% endblock %}
@@ -0,0 +1,155 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
{%- elif v == 0 -%}<span class="perf-zero">–</span>
{%- else -%}{{ "{:,}".format(v) }}{%- endif -%}
{%- endmacro -%}
{%- macro pct(p) -%}{%- if p is none -%}<span class="perf-zero">–</span>{%- else -%}{{ "{:,}".format(p) }}%{%- endif -%}{%- endmacro -%}
{% block content %}
{#- 틱톡(2026-11-05) — 광고비 탭과 같은 기간 이동·표·그래프. 값은 광고 API 만(읽기 전용, 직접 입력 없음). 매출 실적·광고비 탭 합계에는 안 들어간다. -#}
<section class="perf perf-ads perf-tiktok" id="perf-dash" data-metric="gross" data-fixed-metric="gross">
{% include "performance/_tabs.html" %}
<div class="perf-toolbar">
<div class="perf-quick" role="group" aria-label="기간 선택">
{% for q in nav.quick %}
<a class="perf-seg{% if q.active %} is-active{% endif %}" href="{{ q.url }}">{{ q.label }}</a>
{% endfor %}
<button type="button" class="perf-seg{% if period_kind == 'custom' %} is-active{% endif %}" id="perf-custom-btn">직접선택</button>
</div>
{% include "performance/_period_nav.html" %}
<form class="perf-custom" id="perf-custom" method="get" action="/performance/tiktok"{% if period_kind != 'custom' %} hidden{% endif %}>
<input type="hidden" name="period" value="custom" />
<input class="erp-input perf-date" type="date" name="from" value="{{ period.start.isoformat() }}" required />
<span class="perf-muted">~</span>
<input class="erp-input perf-date" type="date" name="to" value="{{ period.end.isoformat() }}" required />
<button class="erp-btn erp-btn-outline" type="submit">조회</button>
</form>
{% include "performance/_ad_update.html" %}
</div>
<div class="perf-notice" id="perf-sync-result" hidden></div>
{% if migration_needed %}
<div class="perf-notice is-warn">광고비 저장 표가 아직 없습니다. 관리자가 performance_db 마이그레이션 005·006 을 적용해야 합니다.</div>
{% endif %}
{% if not tiktok_configured %}
<div class="perf-notice is-warn">틱톡 API 가 아직 설정되지 않았습니다. {% if is_admin %}<a href="/performance/settings#perf-ad-sources">실적 설정 → 광고 API 연동</a>에서{% else %}관리자가 실적 설정 → 광고 API 연동에서{% endif %} 틱톡 [설정]을 입력하면 데이터가 들어옵니다.</div>
{% endif %}
<div class="perf-kpi-line">
{% for k in kpis %}
<span class="perf-kpi-item">
<span class="perf-muted">{{ k.label }}</span>
{% if k.key == 'roas' %}
<b class="perf-kpi-line-value is-sub">{{ pct(k.pct) }}</b>
{% else %}
<b class="perf-kpi-line-value{% if not k.primary %} is-sub{% endif %}">₩{{ "{:,}".format(k.value) }}</b>
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
{% else %}
{% set up = k.delta > 0 %}
<span class="perf-delta {% if k.delta == 0 %}is-flat{% elif up != (k.invert or false) %}is-up{% else %}is-down{% endif %}">
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
<span class="perf-muted">{{ k.cmp }} 대비</span>
{% endif %}
{% endif %}
</span>
{% endfor %}
</div>
<div class="erp-card perf-card">
<div class="perf-card-head">
<h2 class="perf-h">{% if period_kind == 'year' %}월별 틱톡 실적{% else %}일자별 틱톡 실적{% endif %}</h2>
</div>
<div class="erp-table-wrap perf-table-wrap perf-main-wrap">
<table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="tiktok">
<thead>
<tr>
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
<th data-col="roas">ROAS</th>
<th data-col="spend">광고비</th>
<th data-col="sales">매출</th>
</tr>
</thead>
<tbody>
{% for r in table %}
<tr class="perf-row-{{ r.kind }}{% if r.weekday == 5 %} is-sat{% endif %}{% if r.weekday == 6 or r.holiday %} is-sun{% endif %}{% if r.today %} is-today{% endif %}{% if r.future %} is-future{% endif %}">
<th class="perf-td-label" scope="row">
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
</th>
<td class="perf-num">{{ pct(r.roas) }}</td>
<td class="perf-num"><span class="v v-gross">{{ won(r.cells.spend.gross) }}</span></td>
<td class="perf-num"><span class="v v-gross">{{ won(r.cells.sales.gross) }}</span></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="perf-grid2">
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 매출 추이</h2></div>
<div class="perf-chart" id="perf-chart-daily"></div>
</div>
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 광고비 추이</h2></div>
<div class="perf-chart" id="perf-chart-daily2"></div>
</div>
</div>
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적</h2></div>
<div class="erp-table-wrap">
<table class="perf-table perf-year">
<thead><tr><th class="perf-th-label">월</th><th>ROAS</th><th>광고비</th><th>매출</th></tr></thead>
<tbody>
{% for r in year.rows %}
<tr class="{% if r.future %}is-future{% endif %}">
<th class="perf-td-label" scope="row">{{ r.label }}</th>
<td class="perf-num">{% if not r.future %}{{ pct(r.roas) }}{% endif %}</td>
<td class="perf-num">{{ won(r.spend) }}</td>
<td class="perf-num">{{ won(r.sales) }}</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr class="perf-row-total">
<th class="perf-td-label" scope="row">합계</th>
<td class="perf-num">{{ pct(year.roas) }}</td>
<td class="perf-num">{{ won(year.spend) }}</td>
<td class="perf-num">{{ won(year.sales) }}</td>
</tr>
</tfoot>
</table>
</div>
</div>
<p class="perf-foot perf-muted">
틱톡 광고 API 값입니다. 매출 = 광고에 귀속된 구매금액(웹 구매 + 틱톡샵, 틱톡샵 ID 를 넣으면 GMV Max 포함)이며 틱톡샵 전체 판매액과는 다를 수 있습니다.
ROAS = 매출 ÷ 광고비 × 100, 외화 계정은 그날 환율로 원화로 바꿉니다. 이 값은 매출 실적·광고비 탭 합계에 들어가지 않습니다.
[광고비 업데이트]는 설정된 광고 API 전부를 함께 가져옵니다.
</p>
</section>
<script type="application/json" id="perf-data">{{ {
"period_kind": period_kind,
"today": today,
"period_start": period.start.isoformat(),
"period_end": period.end.isoformat(),
"period_label": period.label,
"daily": chart_sales,
"daily2": chart_spend,
"empty_text": "기간 내 틱톡 데이터가 없습니다.",
"auto_sync": auto_sync,
"update_watch": update_watch
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261105a" defer></script>{% endblock %}
@@ -0,0 +1,216 @@
"""틱톡 탭(2026-11-05) — 입력 검사·요청 매개변수·30일 나누기·매출 합산·환율·오류 안내·화면 데이터·다른 탭과 분리.
틱톡 서버는 가짜(httpx MockTransport)."""
from __future__ import annotations
import json
from datetime import date
from decimal import Decimal
from urllib.parse import parse_qs, urlparse
import httpx
import pytest
from app.modules.performance import ad_spend, fx
from app.modules.performance.ad_sources import tiktok_ads as tt
from app.modules.performance.ad_sources.registry import get_source
from app.modules.performance.adapters.base import AdapterContext, ApiError, AuthFailed, TokenExpired
TOKEN = "tiktoktoken0123456789abcdefSECRET"
class Creds:
def __init__(self, values):
self.values = values
def get(self, key):
return self.values.get(key, "")
def has(self, key):
return bool(self.values.get(key))
def ctx(**extra):
return AdapterContext(code="tiktok", credentials=Creds({"advertiser_id": "71234567", "access_token": TOKEN, **extra}), timeout_sec=5.0)
def server(monkeypatch, *, currency="KRW", report=None, gmv=None, seen=None):
"""가짜 틱톡 + 환율 서버. seen 에 (경로, 쿼리, 머리글)을 쌓는다."""
def handler(req: httpx.Request) -> httpx.Response:
url = urlparse(str(req.url))
q = {k: v[0] for k, v in parse_qs(url.query).items()}
if seen is not None:
seen.append((url.path, q, req.headers.get("access-token")))
if "business-api.tiktok.com" not in str(req.url):
return httpx.Response(200, json=[{"date": "2026-10-05", "base": "MYR", "quote": "KRW", "rate": 300}])
if url.path.endswith("/advertiser/info/"):
return httpx.Response(200, json={"code": 0, "data": {"list": [{"name": "DBX", "currency": currency, "timezone": "Asia/Seoul"}]}})
rows = gmv if url.path.endswith("/gmv_max/report/get/") else report
if isinstance(rows, httpx.Response):
return rows
return httpx.Response(200, json={"code": 0, "data": {"list": [
{"dimensions": {"stat_time_day": f"{d} 00:00:00"}, "metrics": m} for d, m in (rows or {}).items()]}})
monkeypatch.setattr(tt, "_http", lambda c: httpx.Client(transport=httpx.MockTransport(handler)))
def test_registered_but_not_a_channel():
"""틱톡은 광고 연동에는 있지만 광고비 탭 채널이 아니다(틱톡 탭에서만 보임)."""
assert get_source("tiktok").name == "틱톡"
assert "tiktok" not in ad_spend.CHANNEL_CODES
@pytest.mark.parametrize("values,word", [
({"advertiser_id": "abc", "access_token": TOKEN}, "광고 계정 ID"),
({"advertiser_id": "71234567", "access_token": "short"}, "액세스 토큰"),
({"advertiser_id": "71234567", "access_token": TOKEN, "shop_id": "x1"}, "틱톡샵 ID"),
])
def test_validation(values, word):
assert any(word in e for e in tt.TiktokAdsSource().validate_credentials(values))
def test_stored_values_pass_validation():
assert tt.TiktokAdsSource().validate_credentials({"advertiser_id": "71234567", "access_token": "__stored__"}) == []
def test_fetch_sums_revenue_and_splits_30_days(monkeypatch):
seen = []
server(monkeypatch, seen=seen, report={"2026-10-05": {
"spend": "1000", "impressions": "50", "clicks": "5", "complete_payment": "1", "onsite_shopping": "2",
"total_complete_payment_rate": "2000", "total_onsite_shopping_value": "1000.4"}})
days = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 9, 1), date(2026, 11, 3))
reports = [q for path, q, _ in seen if path.endswith("/report/integrated/get/")]
assert [(q["start_date"], q["end_date"]) for q in reports] == [
("2026-09-01", "2026-09-30"), ("2026-10-01", "2026-10-30"), ("2026-10-31", "2026-11-03")]
assert reports[0]["data_level"] == "AUCTION_ADVERTISER" and "stat_time_day" in json.loads(reports[0]["dimensions"])
assert not [p for p, _, _ in seen if p.endswith("/gmv_max/report/get/")] # 틱톡샵 ID 없으면 안 물음
assert all(h == TOKEN for _, _, h in seen) and not any(TOKEN in json.dumps(q) for _, q, _ in seen) # 토큰은 머리글로만
# 같은 날 응답이 쪽마다 오므로 3번 더해진다 — 가짜 서버가 기간과 무관하게 같은 줄을 주는 탓, 합산 동작 자체를 확인
d = days[0]
assert d.day == date(2026, 10, 5) and d.amount == 3000 and d.metrics[tt.M_REVENUE] == 9001
assert d.roas == Decimal("300.04") and d.metrics[tt.M_ORDERS] == 9
def test_gmv_max_added_only_with_shop_id(monkeypatch):
seen = []
server(monkeypatch, seen=seen, report={"2026-10-05": {"spend": "100", "total_onsite_shopping_value": "100"}},
gmv={"2026-10-05": {"cost": "100", "gross_revenue": "500", "orders": "3"}})
d = tt.TiktokAdsSource().fetch_days(ctx(shop_id="7555"), date(2026, 10, 5), date(2026, 10, 5))[0]
assert d.amount == 200 and d.metrics[tt.M_REVENUE] == 600 and d.roas == Decimal("300.00")
assert d.metrics[tt.M_GMV_REVENUE] == 500 and d.metrics[tt.M_GMV_COST] == 100 # 대조용으로 따로 남김
gmv_q = next(q for p, q, _ in seen if p.endswith("/gmv_max/report/get/"))
assert json.loads(gmv_q["store_ids"]) == ["7555"]
def test_foreign_currency_uses_that_day_rate(monkeypatch):
fx.clear_cache()
server(monkeypatch, currency="MYR", report={"2026-10-05": {"spend": "10", "total_onsite_shopping_value": "40"}})
d = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))[0]
assert d.amount == 3000 and d.metrics[tt.M_REVENUE] == 12000 and d.roas == Decimal("400.00")
fx.clear_cache()
def test_no_spend_means_no_roas(monkeypatch):
server(monkeypatch, report={"2026-10-05": {"spend": "0", "total_onsite_shopping_value": "40"}})
d = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))[0]
assert d.roas is None and d.metrics[tt.M_ROAS] is None
@pytest.mark.parametrize("code,exc", [(40102, TokenExpired), (40105, AuthFailed), (40100, ApiError), (40002, ApiError)])
def test_error_codes(monkeypatch, code, exc):
server(monkeypatch, report=httpx.Response(200, json={"code": code, "message": "bad"}))
with pytest.raises(exc) as got:
tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))
assert str(code) in str(got.value) and TOKEN not in str(got.value)
def test_connection_also_asks_report(monkeypatch):
"""연결 테스트가 보고서까지 물어야 지표 이름 오류를 저장 전에 잡는다."""
seen = []
server(monkeypatch, seen=seen)
msg = tt.TiktokAdsSource().test_connection(ctx())
assert "DBX" in msg and "KRW" in msg
assert any(p.endswith("/report/integrated/get/") for p, _, _ in seen)
class Store:
def __init__(self, rows=None, missing=False):
self.rows, self.missing = rows or [], missing
def ad_details(self, code, start, end):
assert code == "tiktok"
if self.missing:
raise ad_spend.AdMigrationNeeded("005")
return [r for r in self.rows if start.isoformat() <= r["date"] <= end.isoformat()]
def row(day, spend, sales):
return {"date": day, "amount": spend, "roas": None, "metrics": {tt.M_REVENUE: sales}, "source": "api"}
def test_dashboard_table_and_kpis():
store = Store([row("2026-10-05", 1000, 3000), row("2026-10-06", 1000, 1000), row("2026-09-05", 500, 500)])
ctx_ = ad_spend.build_tiktok_dashboard(store, kind="month", anchor=date(2026, 10, 15), today=date(2026, 10, 31),
holidays={"2026-10-09": "한글날"})
total = ctx_["table"][0]
assert total["kind"] == "total" and total["cells"]["spend"]["gross"] == 2000 and total["cells"]["sales"]["gross"] == 4000 and total["roas"] == 200
day = next(r for r in ctx_["table"] if r.get("date") == "2026-10-05")
assert day["roas"] == 300
assert next(r for r in ctx_["table"] if r.get("date") == "2026-10-09")["holiday"] == "한글날"
kpi = {k["key"]: k for k in ctx_["kpis"]}
assert kpi["spend"]["value"] == 2000 and kpi["sales"]["value"] == 4000 and kpi["roas"]["pct"] == 200
assert kpi["spend"]["delta"] == 300.0 and kpi["sales"]["delta"] == 700.0
assert ctx_["year"]["spend"] == 2500 and ctx_["year"]["sales"] == 4500 and ctx_["year"]["rows"][9]["roas"] == 200
assert ctx_["year"]["rows"][10]["future"] is True and ctx_["year"]["rows"][10]["roas"] is None
assert sum(p["gross"] for p in ctx_["chart_sales"]) == 4000 and sum(p["gross"] for p in ctx_["chart_spend"]) == 2000
def test_dashboard_without_table_or_data():
got = ad_spend.build_tiktok_dashboard(Store(missing=True), kind="month", anchor=date(2026, 10, 1), today=date(2026, 10, 31))
assert got["migration_needed"] is True and got["table"][0]["roas"] is None
assert {k["key"]: k for k in got["kpis"]}["roas"]["pct"] is None
def test_ads_tab_ignores_tiktok_rows():
"""perf_ad_spend 에 틱톡 줄이 있어도 광고비 탭 합계에 안 들어간다."""
class AdStore:
def ad_amounts(self, start, end):
return {(date(2026, 10, 5), "google"): 100, (date(2026, 10, 5), "tiktok"): 9000}, {}
def daily_amounts(self, start, end, codes):
return {}
got = ad_spend.build_ad_dashboard(AdStore(), kind="month", anchor=date(2026, 10, 1), today=date(2026, 10, 31))
assert got["table"][0]["total"]["gross"] == 100 and "tiktok" not in got["codes"]
assert {k["key"]: k for k in got["kpis"]}["spend"]["value"] == 100
def test_page_renders_after_ads_tab(monkeypatch):
"""진짜 라우터·템플릿 — 탭 순서, 열 순서, 값, 미설정 안내, 칸 입력 없음."""
import importlib
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import common
perf_router = importlib.import_module("app.modules.performance.router") # 패키지의 router 는 APIRouter 객체
store = Store([row("2026-10-05", 1000, 3000)])
user = {"email": "a@x", "name": "A", "role": "user"}
class Sync:
def configured(self):
return {"google": True, "tiktok": False}
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, user))
monkeypatch.setattr(perf_router, "_ad_services", lambda st: (None, Sync()))
monkeypatch.setattr(perf_router, "_auto_sync_ctx", lambda st, kind: None)
monkeypatch.setattr(perf_router, "today_kst", lambda: date(2026, 10, 31))
app = FastAPI()
app.include_router(perf_router.router)
html = TestClient(app).get("/performance/tiktok").text
tabs = html.split('class="perf-tabs-main"', 1)[1]
assert tabs.index("광고비</a>") < tabs.index("틱톡</a>") and "perf-tab-tiktok is-active" in tabs
head = html.split("<thead>", 1)[1].split("</thead>", 1)[0]
assert head.index("ROAS") < head.index("광고비") < head.index("매출")
assert "3,000" in html and "300%" in html
assert "틱톡 API 가 아직 설정되지 않았습니다" in html and "data-manual-code" not in html
@@ -134,5 +134,5 @@
{% endblock %}
{% block scripts %}<script type="application/json" id="vac-holidays">{{ holidays | tojson }}</script>
<script src="/static/erp-datepop.js?v=20261102a" defer></script>
<script src="/static/erp-datepop.js?v=20261105a" defer></script>
<script src="/static/vacation.js?v=20261102a" defer></script>{% endblock %}
@@ -149,5 +149,5 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/erp-datepop.js?v=20261102a" defer></script>
{% block scripts %}<script src="/static/erp-datepop.js?v=20261105a" defer></script>
<script src="/static/vacation.js?v=20261102a" defer></script>{% endblock %}
+10 -8
View File
@@ -63,7 +63,8 @@
const HOLIDAY_SHORT = { "부처님오신날": "석가탄신일", "추석·개천절": "추석" };
// 요일 줄 + 6주 날짜 칸(팝업·붙박이 달력 공용). extra(iso) = 그 칸에 더할 클래스 목록
function gridHtml(viewY, viewM, holidays, today, extra) {
// locale(선택, 라이브 커머스 영문 화면): { weekdays[7], shortName(이름), title(연, 월0), prev, next } — 없으면 한글
function gridHtml(viewY, viewM, holidays, today, extra, locale) {
const first = new Date(viewY, viewM, 1);
const gridStart = new Date(viewY, viewM, 1 - first.getDay());
let days = "";
@@ -78,14 +79,14 @@
if (iso === today) cls.push("is-today");
cls.push.apply(cls, extra(iso, d));
if (holName) cls.push("has-hol");
const holShort = /\s대체$/.test(holName) ? "대체휴일" : (HOLIDAY_SHORT[holName] || holName);
const holShort = locale && locale.shortName ? locale.shortName(holName) : /\s대체$/.test(holName) ? "대체휴일" : (HOLIDAY_SHORT[holName] || holName);
days += '<button type="button" class="' + cls.join(" ") + '" data-iso="' + iso + '"' +
(holName ? ' title="' + esc(holName) + '"' : "") + ">" +
'<span class="pj-dp-num">' + d.getDate() + "</span>" +
(holName ? '<span class="pj-dp-hol">' + esc(holShort) + "</span>" : "") + "</button>";
}
return '<div class="pj-dp-grid">' +
["일", "월", "화", "수", "목", "금", "토"].map(function (w, i) {
((locale && locale.weekdays) || ["일", "월", "화", "수", "목", "금", "토"]).map(function (w, i) {
return '<span class="pj-dp-wd' + (i === 0 ? " is-sun" : i === 6 ? " is-sat" : "") + '">' + w + "</span>";
}).join("") + days + "</div>";
}
@@ -355,7 +356,7 @@
// 화면에 붙박이는 기간 달력(2026-11-02, 휴가 신청) — 팝업과 같은 달력 서식(.pj-dp-*).
// 첫 클릭 = 시작일(동그라미), 다음 클릭 = 종료일(둥근 막대), 그다음 클릭 = 새로 시작. 시작일보다 앞을 누르면 그 날이 새 시작일.
// opts: { start, end, holidays, single() — true 면 클릭마다 하루, onChange(start, end) }. 반환 { set(start, end) }
// opts: { start, end, holidays, single() — true 면 클릭마다 하루, onChange(start, end), locale }. 반환 { set(start, end) }
function mountRange(box, opts) {
const holidays = opts.holidays || {};
const today = isoToday();
@@ -373,12 +374,13 @@
return c;
}
function render() {
const loc = opts.locale || {};
box.innerHTML =
'<div class="pj-dp-nav">' +
'<button type="button" class="pj-dp-navbtn" data-nav="-1" title="이전 달"><span class="material-symbols-outlined">chevron_left</span></button>' +
'<span class="pj-dp-title">' + viewY + "년 " + (viewM + 1) + "월</span>" +
'<button type="button" class="pj-dp-navbtn" data-nav="1" title="다음 달"><span class="material-symbols-outlined">chevron_right</span></button>' +
"</div>" + gridHtml(viewY, viewM, holidays, today, bandClasses);
'<button type="button" class="pj-dp-navbtn" data-nav="-1" title="' + esc(loc.prev || "이전 달") + '"><span class="material-symbols-outlined">chevron_left</span></button>' +
'<span class="pj-dp-title">' + esc(loc.title ? loc.title(viewY, viewM) : viewY + "년 " + (viewM + 1) + "월") + "</span>" +
'<button type="button" class="pj-dp-navbtn" data-nav="1" title="' + esc(loc.next || "다음 달") + '"><span class="material-symbols-outlined">chevron_right</span></button>' +
"</div>" + gridHtml(viewY, viewM, holidays, today, bandClasses, opts.locale);
}
box.addEventListener("click", function (e) {
const nav = e.target.closest(".pj-dp-navbtn");
+12 -3
View File
@@ -15,8 +15,10 @@
/* 거르기 줄 */
.io-filter { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.io-filter .erp-select { width: auto; }
.io-filter-right { display: flex; align-items: center; justify-content: flex-end; gap: 8px; flex-wrap: wrap; margin-left: auto; }
.io-search { width: 260px; }
.io-filter input[type="date"] { width: 150px; }
.io .pj-date-btn { margin-top: 0; height: 34px; box-sizing: border-box; }
.io .pj-date-btn:disabled { opacity: .5; cursor: not-allowed; }
.io-date { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--color-midtone-gray); }
.io-seg { display: inline-flex; padding: 2px; border: 1px solid var(--color-subtle-ash); border-radius: 10px; background: #fff; }
.io-seg-btn { padding: 5px 12px; border-radius: 8px; font-size: 12.5px; color: var(--color-rich-black); text-decoration: none; white-space: nowrap; }
@@ -27,6 +29,13 @@
.io-table td, .io-table th { white-space: nowrap; }
.io-table td.io-items { white-space: normal; min-width: 160px; }
.io-num { text-align: right !important; font-variant-numeric: tabular-nums; }
/* 발주 목록 머리글 — 숫자 열도 가운데(.io-num 의 !important 를 덮음) */
.io-table.io-list-table thead th { text-align: center !important; font-size: calc(var(--text-caption, 12px) * 1.11 * .9); font-weight: 700; background: var(--color-ghost-gray, #f2f2f2); }
/* 발주 목록 글자 = 원래 크기의 90% — 칸(13px)·작은 글자(12·11.5·11px) 비율 유지 */
.io-table.io-list-table tbody td { font-size: 11.7px; }
.io-list-table .erp-row-sub, .io-list-table .erp-muted, .io-list-table .io-progress-pct, .io-list-table .io-late { font-size: 10.8px; }
.io-list-table .io-badge { font-size: 10.35px; }
.io-list-table .io-over-sub, .io-list-table .io-badge-note { font-size: 9.9px; }
.io-code { font-family: ui-monospace, Consolas, monospace; font-size: 12px; }
.io-order-no { font-weight: 600; color: var(--color-rich-black); text-decoration: none; font-family: ui-monospace, Consolas, monospace; }
.io-order-no:hover { text-decoration: underline; }
@@ -346,12 +355,12 @@
달력은 화면 너비에 따라 300~440px(2026-10-21 "달력 오른쪽 여백이 많다 — 더 키워 달라") — 입출고 화면은 ERP 공용 최대 폭(1550px)을 풀어
넓은 화면의 빈 여백을 쓴다. 좁은 화면(1100px 미만)은 한 열 — 달력은 아래로. ── */
.erp-page:has(> .io-split) { max-width: none; }
.io-split { display: grid; grid-template-columns: minmax(0, 1fr) clamp(300px, 23vw, 440px); gap: 20px; align-items: start; }
.io-split { display: grid; grid-template-columns: minmax(0, 1fr) clamp(270px, 20.7vw, 396px); gap: 20px; align-items: start; }
.io-split > .io { min-width: 0; }
.io-side { min-width: 0; position: sticky; top: 12px; display: flex; flex-direction: column; gap: 6px; container-type: inline-size; }
@media (max-width: 1100px) {
.io-split { grid-template-columns: minmax(0, 1fr); }
.io-side { position: static; width: 300px; }
.io-side { position: static; width: 270px; }
}
/* 달력 = 오른쪽 열 너비 × (320/300) 높이 — 프로젝트 달력 모양(.pj-cal)을 작게: 머리(제목 ‹ › 오늘) + 둥근 테두리 안 요일 줄(회색) + 6주.
크기는 모두 달력 너비 기준(cqw — 300px 일 때 1cqw = 3px, 예전 300×320 그대로)이라 커지면 글자·칸이 같은 비율로 커진다. */
+12
View File
@@ -21,6 +21,18 @@
}
function fmt(n) { return n.toLocaleString("ko-KR"); }
// ── 날짜 칸 = ERP 공용 달력(프로젝트와 같은 모양, 국경일·대체공휴일 빨강·이름, 마우스를 올리면 이름) ──
// 필수 칸은 [지우기]를 뺀다 — 숨긴 required 칸이 비면 브라우저가 안내 없이 저장을 막는다.
if (window.ErpDatePop) {
let holidays = {};
try { holidays = JSON.parse((document.getElementById("io-holidays") || {}).textContent || "{}"); } catch (_) { holidays = {}; }
document.querySelectorAll('input[type="date"]').forEach(function (input) {
const pop = window.ErpDatePop.enhance(input, { label: input.getAttribute("aria-label") || "날짜",
format: window.ErpDatePop.fmtFull, clear: !input.required, holidays: holidays });
if (pop) pop.button.disabled = input.disabled;
});
}
// ── 목록 줄 누르기 → 발주서 ──
document.addEventListener("click", function (e) {
const row = e.target.closest(".io-row-link");
+56 -32
View File
@@ -1,5 +1,6 @@
/* 라이브 커머스(2026-11-04) — 스케줄표·호스트 설정 */
.erp-page:has(> .lv) { box-sizing: border-box; } /* 공용 .erp-page 는 폭 100% + 안쪽 여백이라 그대로면 화면보다 넓어진다 */
/* 공용 .erp-page 는 폭 100% + 안쪽 여백이라 그대로면 화면보다 넓어진다. 라이브 커머스는 화면 전체 너비를 쓴다(공용 최대 1550px 해제). */
.erp-page:has(> .lv), .erp-page:has(> .lv-split) { box-sizing: border-box; max-width: none; padding: var(--sp-16, 16px); }
.lv { display: flex; flex-direction: column; gap: 14px; min-width: 0; }
.lv *, .lv-dlg *, .lv-dlg *::before, .lv-dlg *::after { box-sizing: border-box; }
.lv-dlg [hidden] { display: none !important; }
@@ -35,56 +36,79 @@
/* ── 달력 보기 ── */
.lv-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; }
.lv-kpi { display: flex; flex-direction: column; gap: 2px; padding: 10px 14px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 10px; background: #fff; }
.lv-kpi span { font-size: 11px; font-weight: 600; letter-spacing: .04em; color: var(--color-midtone-gray, #666); }
.lv-kpi b { font-size: 18px; font-variant-numeric: tabular-nums; }
.lv-jump { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; padding: 8px 12px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 10px; background: #fff; }
.lv-jump-label { margin-right: 4px; font-size: 13px; font-weight: 600; color: #4b5563; }
.lv-jump-day { min-width: 28px; height: 28px; padding: 0 4px; border: 1px solid transparent; border-radius: 6px; background: #f1f3f6; color: #1f2937; font-size: 13px; font-weight: 600; cursor: pointer; }
.lv-jump-day:hover { background: #e2e6ec; }
.lv-jump-day.is-weekend { background: #fff6dc; border-color: #f3e2ae; color: #8a4b08; }
.lv-jump-day.is-today { outline: 2px solid #111; outline-offset: -2px; }
.lv-tip { margin: 0; padding: 8px 12px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 10px; background: #f6f8fb; font-size: 13px; color: #374151; }
.lv-kpi { display: flex; flex-direction: column; gap: 0; padding: 4px 12px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 10px; background: #fff; }
.lv-kpi span { font-size: 10px; font-weight: 600; letter-spacing: .04em; color: var(--color-midtone-gray, #666); }
.lv-kpi b { font-size: 15px; font-variant-numeric: tabular-nums; }
.lv-tip { margin: 0; padding: 2px 12px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 10px; background: #f6f8fb; font-size: 11.5px; color: #374151; }
/* 달력 보기 = 세로 2분할: 왼쪽 표 + 오른쪽 위에 붙는 달력(공용 erp-datepop 서식) */
.lv-split { display: grid; grid-template-columns: minmax(0, 1fr) 240px; gap: 12px; }
.lv-split > .lv { gap: 6px; }
/* 풀HD 브라우저(세로 약 880~940px)에서 페이지 세로 스크롤 없이 한 화면 — 표 상자가 남은 높이를 쓰고, 더 좁은 창이나 카드가 겹친 칸은 표 안에서 스크롤 */
@media (min-width: 1101px) {
.erp-page:has(> .lv-split) { overflow: hidden; padding: 10px 12px; }
.lv-split { flex: 1 1 auto; min-height: 0; grid-template-rows: minmax(0, 1fr); }
.lv-split > .lv { min-height: 0; }
.lv-split .lv-cal-wrap { flex: 1 1 auto; min-height: 0; max-height: none; }
.lv-split .lv-cal { height: 100%; }
}
@media (max-width: 1100px) {
.lv-split { grid-template-columns: minmax(0, 1fr); }
.lv-side-cal { order: -1; max-width: 340px; }
}
/* 오른쪽 달력 = 공용 달력의 80% */
.lv-side-cal { align-self: start; box-sizing: border-box; padding: 10px; border: 1px solid #cfd4dc; border-radius: 10px; background: #fff; font-size: 10.4px; }
.lv-side-cal .pj-dp-nav { margin: 0 0 4px; }
.lv-side-cal .pj-dp-title { font-size: 11.2px; }
.lv-side-cal .pj-dp-navbtn { width: 22px; height: 22px; }
.lv-side-cal .pj-dp-navbtn .material-symbols-outlined { font-size: 18px; }
.lv-side-cal .pj-dp-wd { padding: 3px 0 4px; font-size: 9.6px; }
.lv-side-cal .pj-dp-day { height: 27px; font-size: 10.8px; }
.lv-side-cal .pj-dp-day::before { width: 24px; height: 24px; top: 13.5px; }
.lv-side-cal .pj-dp-num { height: 27px; }
.lv-side-cal .pj-dp-day.has-hol { height: 37px; }
.lv-side-cal .pj-dp-hol { margin-top: -2px; font-size: 8px; }
.lv-cal-wrap { overflow: auto; max-height: calc(100vh - 150px); border: 1px solid #cfd4dc; border-radius: 10px; background: #fff; }
.lv-cal { border-collapse: separate; border-spacing: 0; min-width: max-content; }
.lv-cal th, .lv-cal td { border-right: 1px solid #e3e6eb; border-bottom: 1px solid #e3e6eb; }
.lv-cal thead th { position: sticky; top: 0; z-index: 2; width: 182px; min-width: 182px; padding: 8px 6px; background: #e4e8ee; text-align: center; font-weight: 700; }
.lv-cal thead th { position: sticky; top: 0; z-index: 2; width: 182px; min-width: 182px; height: 1px; padding: 3px 6px; background: #e4e8ee; text-align: center; font-weight: 700; }
.lv-cal thead th.is-weekend { background: #f5efd3; color: #7a5c00; }
.lv-cal thead th.is-today { box-shadow: inset 0 -3px 0 #111; }
.lv-cal-weekday { font-size: 13px; letter-spacing: .03em; }
.lv-cal-count { display: inline-block; min-width: 18px; padding: 0 4px; margin-left: 2px; border: 1px solid #cfd4dc; border-radius: 4px; background: #fff; color: #374151; font-size: 11px; font-weight: 600; }
.lv-cal-date { margin-top: 2px; font-size: 11px; font-weight: 600; color: #6b7280; }
.lv-cal .lv-cal-time { position: sticky; left: 0; z-index: 1; width: 132px; min-width: 132px; padding: 8px; background: #f6f7f9; text-align: center; font-size: 13px; font-weight: 700; white-space: nowrap; }
.lv-cal-weekday { font-size: 11.5px; letter-spacing: .03em; }
.lv-cal-count { display: inline-block; min-width: 15px; padding: 0 3px; margin-left: 2px; border: 1px solid #cfd4dc; border-radius: 4px; background: #fff; color: #374151; font-size: 9.5px; font-weight: 600; }
.lv-cal-date { margin-top: 0; font-size: 9.5px; font-weight: 600; color: #6b7280; }
.lv-cal .lv-cal-time { position: sticky; left: 0; z-index: 1; width: 112px; min-width: 112px; padding: 2px 6px; background: #f6f7f9; text-align: center; font-size: 11.5px; font-weight: 700; white-space: nowrap; }
.lv-cal thead .lv-cal-time { z-index: 3; background: #d9dee6; }
.lv-cal .lv-cal-time small { display: block; margin-top: 2px; font-size: 10.5px; font-weight: 600; color: #6b7280; }
.lv-cell { min-height: 100px; padding: 4px; vertical-align: top; background: #fff; }
.lv-cal .lv-cal-time small { display: block; margin-top: 0; font-size: 9px; font-weight: 600; color: #6b7280; }
.lv-cell { padding: 2px; vertical-align: top; background: #fff; }
.lv-cell.is-weekend { background: #fffdf3; }
.lv-cell.is-drop { background: #e8f1ff; box-shadow: inset 0 0 0 2px #3b82f6; }
.lv-cell-add { display: block; width: 100%; min-height: 88px; border: 1px dashed #d8dce3; border-radius: 6px; background: transparent; color: #b0b6c0; font-size: 16px; cursor: pointer; }
.lv-cell-add { display: block; width: 100%; height: 100%; min-height: 52px; border: 1px dashed #d8dce3; border-radius: 6px; background: transparent; color: #b0b6c0; font-size: 14px; cursor: pointer; }
.lv-cell-add:hover, .lv-cell-add:focus-visible { border-color: #6b7280; color: #374151; }
.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 + .lv-card { margin-top: 2px; }
.lv-card { border: 1px solid #1f2937; border-radius: 6px; background: #fff; overflow: hidden; }
.lv-card-head { display: flex; align-items: center; gap: 3px; padding: 1px 4px; border-bottom: 1px solid #1f2937; cursor: grab; }
.lv-card-head:active { cursor: grabbing; }
.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; }
.lv-card-name small { display: block; overflow: hidden; text-overflow: ellipsis; text-transform: none; font-size: 9px; line-height: 1.1; font-weight: 600; letter-spacing: 0; }
.lv-card-grip { font-size: 10px; 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: 11px; line-height: 1.2; font-weight: 800; letter-spacing: .03em; color: #111; }
.lv-card-edit { padding: 0 2px; border: 0; background: none; color: #374151; font-size: 11px; cursor: pointer; }
.lv-card-nums { display: grid; grid-template-columns: 1fr 1fr; }
.lv-card-nums div { display: flex; flex-direction: column; text-align: center; }
.lv-card-nums div { display: flex; align-items: baseline; justify-content: center; gap: 4px; padding: 1px 2px; white-space: nowrap; }
.lv-card-nums div + div { border-left: 1px solid #e3e6eb; }
.lv-card-nums span { padding: 2px 0; background: #f6f7f9; font-size: 10px; font-weight: 600; color: #4b5563; }
.lv-card-nums b { padding: 3px 0; font-size: 14px; font-variant-numeric: tabular-nums; }
.lv-card-foot { display: flex; justify-content: space-between; gap: 4px; padding: 2px 6px; border-top: 1px solid #e3e6eb; background: #f6f7f9; font-size: 10.5px; font-weight: 600; color: #4b5563; }
.lv-card-nums span { font-size: 9px; font-weight: 600; color: #4b5563; }
.lv-card-nums b { font-size: 11px; font-variant-numeric: tabular-nums; }
.lv-card-foot { display: flex; justify-content: space-between; gap: 4px; padding: 0 4px; border-top: 1px solid #e3e6eb; background: #f6f7f9; font-size: 9px; font-weight: 600; color: #4b5563; }
.lv-card-foot b { color: #8a2c0d; }
.lv-card-foot a { color: #1d4f91; }
.lv-cal tfoot th, .lv-cal tfoot td { position: sticky; bottom: 0; z-index: 2; padding: 8px; background: #101a33; color: #fff; border-color: #2a3550; }
.lv-cal tfoot .lv-cal-time { z-index: 3; background: #101a33; font-size: 12px; }
.lv-total { display: flex; flex-direction: column; gap: 2px; margin: 0; font-size: 11px; font-weight: 600; }
.lv-cal tfoot th, .lv-cal tfoot td { position: sticky; bottom: 0; z-index: 2; height: 1px; padding: 3px 6px; background: #101a33; color: #fff; border-color: #2a3550; }
.lv-cal tfoot .lv-cal-time { z-index: 3; background: #101a33; font-size: 11px; }
.lv-total { display: flex; flex-direction: column; gap: 0; margin: 0; font-size: 9.5px; line-height: 1.25; font-weight: 600; }
.lv-total div { display: flex; justify-content: space-between; gap: 6px; }
.lv-total dt { color: #aab3c5; }
.lv-total dd { margin: 0; font-variant-numeric: tabular-nums; color: #fbbf72; white-space: nowrap; }
.lv-total dd.is-sales { color: #6ee7a8; }
.lv-total-edit { padding: 0 2px; border: 0; background: none; color: #cbd5e1; font-size: 11px; cursor: pointer; }
.lv-total-edit { padding: 0 2px; border: 0; background: none; color: #cbd5e1; font-size: 9.5px; line-height: 1; cursor: pointer; }
.lv-dlg { width: min(560px, calc(100vw - 32px)); max-height: calc(100vh - 40px); padding: 0; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 12px; }
.lv-dlg::backdrop { background: rgba(0, 0, 0, .35); }
+42 -10
View File
@@ -1,9 +1,10 @@
/* 라이브 커머스(2026-11-04) — 스케줄표·달력·호스트 설정 공용: 추가·고치기 창, 저장·지우기(fetch → JSON {ok, message}, 틀려도 입력한 값이 창에 남음).
달력: Jump to Date, 카드 끌어 옮기기·맞바꾸기, 날짜별 광고비. 다시 그린 뒤에도 보던 가로 위치 유지. */
달력: 오른쪽 달력으로 날짜 이동, 카드 끌어 옮기기·맞바꾸기, 날짜별 광고비. 다시 그린 뒤에도 보던 가로 위치 유지. */
(function () {
"use strict";
const calWrap = document.getElementById("lv-cal-wrap");
const CAL_POS = "lv_cal_left";
const CAL_JUMP = "lv_cal_jump";
function tr(text) { return (window.LV_T && window.LV_T[text]) || text; }
const dialogText = function () { return { okText: tr("확인"), cancelText: tr("취소") }; };
function reload() {
@@ -78,6 +79,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;
@@ -130,17 +132,47 @@
const time = calWrap.querySelector("thead .lv-cal-time");
if (col && time) calWrap.scrollLeft += col.getBoundingClientRect().left - time.getBoundingClientRect().right;
}
document.addEventListener("click", function (e) {
const b = e.target.closest("[data-jump]");
if (b) jumpTo(b.dataset.jump);
});
// 마지막 날들도 맨 왼쪽까지 오도록 표 끝에 여백(표 상자 너비 − 시간 열 − 날짜 열 하나)
function endGap() {
const time = calWrap.querySelector("thead .lv-cal-time");
const col = calWrap.querySelector("thead th[data-day]");
const table = calWrap.querySelector("table");
if (time && col && table) table.style.marginRight = Math.max(0, calWrap.clientWidth - time.offsetWidth - col.offsetWidth) + "px";
}
endGap();
window.addEventListener("resize", endGap);
// ── 오른쪽 달력(공용 erp-datepop, 말레이시아 공휴일): 날짜를 누르면 그 날이 표 맨 왼쪽, 다른 달이면 그 달 화면으로 가서 맨 왼쪽 ──
let pending = null;
try { pending = sessionStorage.getItem(CAL_JUMP); sessionStorage.removeItem(CAL_JUMP); } catch (_) {}
const hasDay = function (iso) { return !!iso && !!calWrap.querySelector('thead th[data-day="' + iso + '"]'); };
const todayHead = calWrap.querySelector("thead th[data-today]");
const firstHead = calWrap.querySelector("thead th[data-day]");
const shownDay = hasDay(pending) ? pending : todayHead ? todayHead.dataset.day : firstHead && firstHead.dataset.day;
const sideBox = document.getElementById("lv-side-cal");
if (sideBox && window.ErpDatePop) {
let holidays = {};
try { holidays = JSON.parse(document.getElementById("lv-my-holidays").textContent); } catch (_) {}
const english = document.querySelector(".lv").lang === "en";
window.ErpDatePop.mountRange(sideBox, {
start: shownDay, end: shownDay, holidays: holidays, single: function () { return true; },
locale: english ? {
weekdays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], prev: "Previous month", next: "Next month",
title: function (y, m) { return new Date(y, m, 1).toLocaleString("en", { month: "long" }) + " " + y; },
shortName: function (name) { return / \(Replacement\)$/.test(name) ? "Replacement" : name; },
} : undefined,
onChange: function (iso) {
if (hasDay(iso)) { jumpTo(iso); return; }
try { sessionStorage.setItem(CAL_JUMP, iso); } catch (_) {}
location.href = "/live/calendar?month=" + iso.slice(0, 7);
},
});
}
let left = null;
try { left = sessionStorage.getItem(CAL_POS); sessionStorage.removeItem(CAL_POS); } catch (_) {}
if (left !== null) calWrap.scrollLeft = Number(left);
else {
const today = calWrap.querySelector("thead th[data-today]");
if (today) jumpTo(today.dataset.day);
}
if (hasDay(pending)) jumpTo(pending);
else if (left !== null) calWrap.scrollLeft = Number(left);
else if (todayHead) jumpTo(todayHead.dataset.day);
// ── 달력: 날짜별 광고비 ──
document.addEventListener("click", async function (e) {
+5
View File
@@ -43,6 +43,7 @@
.perf-tab.is-active { color: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, .18); }
.perf-tab-sales.is-active, .perf-tab-sales.is-active:hover { background: var(--color-deep-black, #1e1f21); }
.perf-tab-ads.is-active, .perf-tab-ads.is-active:hover { background: var(--perf-ad, #d9480f); }
.perf-tab-tiktok.is-active, .perf-tab-tiktok.is-active:hover { background: var(--perf-tiktok, #e11d48); }
a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
.perf-tab-gear {
margin-left: auto; display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px;
@@ -59,6 +60,10 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
.perf-ads td.is-upload .v-gross { color: var(--perf-ad); }
/* 광고 API(구글 광고 등)로 가져온 칸 — 초록 숫자 */
.perf-ads td.is-api .v-gross { color: #1e8e3e; }
/* 틱톡 화면 — 광고비 화면 틀에 색만 바꿈 */
.perf, .perf-modal { --perf-tiktok: #e11d48; }
.perf-tiktok .perf-quick .perf-seg.is-active { background: var(--perf-tiktok); }
.perf-tiktok .perf-chart .bar { fill: var(--perf-tiktok); }
.perf-ad-actions { margin-left: auto; display: inline-flex; align-items: center; gap: 6px; flex-wrap: wrap; }
/* 광고 API 설정 창 — 서비스 계정 JSON 같은 여러 줄 항목 */
.perf-cred-multi { width: 100%; font-family: ui-monospace, Consolas, monospace; font-size: 12px; resize: vertical; }
+6 -5
View File
@@ -358,7 +358,8 @@
root.querySelectorAll(".perf-metric .perf-seg").forEach(function (b) {
b.classList.toggle("is-active", b.dataset.metric === m);
});
drawDaily(m);
drawDaily(m, "perf-chart-daily", data.daily);
drawDaily(m, "perf-chart-daily2", data.daily2); // 틱톡 탭 — 매출·광고비 두 그래프
drawShare(m);
root.querySelectorAll(".perf-metric-name").forEach(function (n) { n.textContent = METRIC_NAMES[m]; });
}
@@ -1045,10 +1046,10 @@
const n = v / p;
return (n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10) * p;
}
function drawDaily(metric) {
const box = document.getElementById("perf-chart-daily");
function drawDaily(metric, boxId, series) {
const box = document.getElementById(boxId);
if (!box) return;
const pts = data.daily || [];
const pts = series || [];
const vals = pts.map(function (p) { return p[metric] || 0; });
if (!pts.length || vals.every(function (v) { return !v; })) {
box.innerHTML = '<div class="perf-chart-empty">' + esc(EMPTY_TEXT) + "</div>";
@@ -1332,7 +1333,7 @@
});
if (colwReset) colwReset.addEventListener("click", async function () {
if (!(await confirmMsg("매출 실적·광고비 표에서 조절한 열 너비를 모두 지우고 자동 너비로 되돌릴까요?"))) return;
try { localStorage.removeItem("perf_colw_sales"); localStorage.removeItem("perf_colw_ads"); } catch (_) { /* 저장소 없음 */ }
try { localStorage.removeItem("perf_colw_sales"); localStorage.removeItem("perf_colw_ads"); localStorage.removeItem("perf_colw_tiktok"); } catch (_) { /* 저장소 없음 */ }
colwReset.textContent = "초기화했습니다";
setTimeout(function () { colwReset.textContent = "조절한 너비 초기화"; }, 1800);
});
+2
View File
@@ -40,6 +40,8 @@ MODULE_KEYS: tuple[str, ...] = (
"inout",
"outreach",
"live",
"live_host",
"live_host_edit",
"expense_approver",
"vacation_approver",
)
+2 -2
View File
@@ -312,8 +312,8 @@ 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·Tiktok Handle(@ 없이), `is_active` |
| `live_broadcasts` | 방송 스케줄 — `host_id`(FK RESTRICT)·`broadcast_date`·`start_time`·`end_time`(말레이시아 시간 그대로)·`venue`·`sales_amount`(RM, NULL = 미입력) |
| `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 에도 포함) |
@@ -0,0 +1,26 @@
-- =====================================================================
-- live_db 마이그레이션 003 — 틱톡 계정을 호스트가 아니라 방송마다(2026-11-05)
-- =====================================================================
-- 왜: 호스트는 메인 계정에서만 방송하지 않고 다른 계정에서도 방송한다(말레이시아 직원 요청).
-- 멱등(idempotent). 열 하나 추가 + 처음 추가할 때만 기존 방송에 그 호스트의 지금 계정을 복사한다.
-- live_hosts.tiktok_handle 은 지우지 않는다(값 보존 — 앱이 더는 읽거나 쓰지 않음).
-- 운영: /opt/www/main 에서 기존 live_db 에 앱 배포 전에 적용(백업 먼저).
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d live_db < scripts/sql/live_db_003_broadcast_account.sql
-- 되돌리기: ALTER TABLE live_broadcasts DROP COLUMN tiktok_handle; (방송별 계정만 사라짐 — 실행 전 백업)
-- =====================================================================
\set ON_ERROR_STOP on
BEGIN;
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'live_broadcasts' AND column_name = 'tiktok_handle') THEN
ALTER TABLE live_broadcasts ADD COLUMN tiktok_handle TEXT NOT NULL DEFAULT '';
UPDATE live_broadcasts b SET tiktok_handle = h.tiktok_handle FROM live_hosts h WHERE h.id = b.host_id;
END IF;
END $$;
COMMENT ON COLUMN live_broadcasts.tiktok_handle IS '그 방송을 한 틱톡 계정(@ 없이)';
COMMIT;
SELECT 'live_db 003 broadcast account ready' AS status,
count(*) AS broadcasts, count(*) FILTER (WHERE tiktok_handle <> '') AS with_account FROM live_broadcasts;
@@ -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;
+3 -1
View File
@@ -52,7 +52,8 @@ CREATE TABLE IF NOT EXISTS live_hosts (
address TEXT NOT NULL DEFAULT '',
bank_name TEXT NOT NULL DEFAULT '',
bank_account TEXT NOT NULL DEFAULT '',
tiktok_handle 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 '',
updated_by TEXT NOT NULL DEFAULT '',
@@ -74,6 +75,7 @@ CREATE TABLE IF NOT EXISTS live_broadcasts (
start_time TIME NOT NULL,
end_time TIME,
venue TEXT NOT NULL DEFAULT '',
tiktok_handle TEXT NOT NULL DEFAULT '', -- 그 방송을 한 계정(@ 없이), 마이그레이션 003
sales_amount NUMERIC(14,2) CHECK (sales_amount IS NULL OR sales_amount >= 0), -- NULL = 아직 입력 안 함
created_by TEXT NOT NULL DEFAULT '',
updated_by TEXT NOT NULL DEFAULT '',
+115
View File
@@ -0,0 +1,115 @@
// 입출고 날짜 칸 = ERP 공용 달력(2026-11-05) — 실제 브라우저(Chromium).
// python tests/js/render_inout.py
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/inout_datepop.browser.test.js
// 기본 달력 대신 날짜 버튼, 국경일·대체공휴일 빨강·이름·말풍선(title), 고르면 값 전송, 필수 칸은 지우기 없음, 잠긴 칸은 못 누름.
const fs = require("fs"), path = require("path");
const { chromium } = require("playwright");
const ROOT = path.join(__dirname, "..", "..");
const fails = [];
function check(name, cond, extra) {
if (cond) console.log("PASS " + name);
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
}
(async function () {
const exe = process.env.PJ_TEST_BROWSER;
const browser = await chromium.launch(exe ? { executablePath: exe } : {});
try {
const p = await (await browser.newContext({ viewport: { width: 1400, height: 900 } })).newPage();
const errors = [];
p.on("pageerror", function (e) { errors.push(String(e)); });
await p.route("**/*", function (r) {
const url = new URL(r.request().url()).pathname;
if (url.startsWith("/static/")) {
const f = path.join(ROOT, "app", url);
if (!fs.existsSync(f)) return r.fulfill({ status: 404, body: "" });
const type = f.endsWith(".css") ? "text/css" : f.endsWith(".js") ? "application/javascript" : "font/woff2";
return r.fulfill({ status: 200, contentType: type, body: fs.readFileSync(f) });
}
if (!url.endsWith(".html")) return r.fulfill({ status: 200, contentType: "application/json", body: "{}" });
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fs.readFileSync(path.join(__dirname, ".out", url.slice(1)), "utf8") });
});
await p.goto("http://erp.test/inout_form.html");
await p.waitForTimeout(200);
const order = p.locator('input[name="order_date"]'), due = p.locator('input[name="due_date"]');
check("기본 달력 칸은 숨김", !(await order.isVisible()) && !(await due.isVisible()));
const orderBtn = p.locator('input[name="order_date"] + button'), dueBtn = p.locator('input[name="due_date"] + button');
check("발주일 버튼 = yyyy.mm.dd(요일)", (await orderBtn.textContent()).includes("2026.10.05(월)"), await orderBtn.textContent());
await orderBtn.click();
const pop = p.locator(".pj-datepop");
check("달력이 열림", await pop.isVisible());
const hol = pop.locator('[data-iso="2026-10-09"]');
check("한글날 = 빨강 칸·이름·말풍선", (await hol.getAttribute("class")).includes("is-sun") && (await hol.getAttribute("title")) === "한글날" && (await hol.textContent()).includes("한글날"), await hol.getAttribute("title"));
check("필수 칸은 지우기 없음", (await pop.getByText("지우기").count()) === 0);
await p.waitForTimeout(200); // 등장 애니메이션 뒤에 찍는다
await p.screenshot({ path: path.join(__dirname, ".out", "inout_datepop.png") });
await pop.locator('[data-iso="2026-10-08"]').click();
await p.keyboard.press("Escape");
check("고른 날짜가 값으로", (await order.inputValue()) === "2026-10-08", await order.inputValue());
check("버튼 글자도 바뀜", (await orderBtn.textContent()).includes("2026.10.08(목)"));
await dueBtn.click();
check("선택 칸은 지우기 있음", (await pop.getByText("지우기").count()) === 1);
// 대체공휴일 — 2026-03-02 삼일절 대체(달을 넘겨 찾지 않고 표 값으로 확인)
const holidays = await p.evaluate(function () { return JSON.parse(document.getElementById("io-holidays").textContent); });
check("대체공휴일도 표에 있음", holidays["2026-03-02"] === "삼일절 대체", holidays["2026-03-02"]);
await p.keyboard.press("Escape");
await p.goto("http://erp.test/inout_list.html");
await p.waitForTimeout(200);
check("목록 필터 시작일 버튼", (await p.locator('input[name="from"] + button').textContent()).includes("2026.10.01(목)"));
const box = await p.locator('input[name="from"] + button').boundingBox();
const search = await p.locator('input[name="q"]').boundingBox();
check("필터 줄 높이가 맞음", Math.abs((box.y + box.height / 2) - (search.y + search.height / 2)) < 4, { box: box, search: search });
await p.screenshot({ path: path.join(__dirname, ".out", "inout_list.png") });
// 목록 거르기(2026-11-05) — 발주일~찾기 묶음의 오른쪽 끝 = 표 상자 오른쪽 끝(표는 넓으면 상자 안에서 가로 스크롤), 줄이 바뀌어도
const rightEdge = async function () {
const btn = await p.getByRole("button", { name: "찾기" }).boundingBox();
const wrap = await p.locator(".erp-table-wrap").boundingBox();
return Math.abs(btn.x + btn.width - (wrap.x + wrap.width));
};
check("좁은 화면: 찾기가 오른쪽 끝", (await rightEdge()) < 2, await rightEdge());
await p.setViewportSize({ width: 2000, height: 900 });
await p.waitForTimeout(100);
await p.screenshot({ path: path.join(__dirname, ".out", "inout_list_wide.png") });
check("넓은 화면: 찾기가 오른쪽 끝", (await rightEdge()) < 2, await rightEdge());
await p.setViewportSize({ width: 1400, height: 900 });
await p.waitForTimeout(100);
// 목록 머리글(2026-11-05) — 숫자 열까지 가운데, 굵게, 12px × 1.11, 회색 배경
const headStyles = await p.locator(".io-table thead th").evaluateAll(function (els) {
return els.map(function (el) { const c = getComputedStyle(el); return [c.textAlign, c.fontWeight, c.fontSize, c.backgroundColor].join("|"); });
});
check("머리글 모양", headStyles.length > 0 && headStyles.every(function (s) { return /^center\|700\|11\.98\d*px\|rgb\(242, 242, 242\)$/.test(s); }), headStyles);
const sizeOf = function (sel) { return p.locator(sel).first().evaluate(function (el) { return getComputedStyle(el).fontSize; }); };
check("표 글자 90%", (await sizeOf(".io-table tbody td")) === "11.7px" && (await sizeOf(".io-table .erp-row-sub")) === "10.8px" && (await sizeOf(".io-table .io-progress-pct")) === "10.8px" && (await sizeOf(".io-table .io-badge")) === "10.35px");
await p.setViewportSize({ width: 2000, height: 900 });
await p.waitForTimeout(100);
check("달력 최대 396px(440px × 90%)", Math.round((await p.locator(".io-side").boundingBox()).width) === 396, await p.locator(".io-side").boundingBox());
await p.setViewportSize({ width: 1400, height: 900 });
await p.waitForTimeout(100);
// 목록 입고일 열(2026-11-05) — 입고 예정일과 발주 사이, 여러 날은 한 칸에서 줄바꿈, 입고 전 "-"
const heads = await p.locator(".io-table thead th").allInnerTexts();
check("입고일 열 위치", heads.indexOf("입고일") === heads.indexOf("입고 예정일") + 1 && heads.indexOf("발주") === heads.indexOf("입고일") + 1, heads);
const col = heads.indexOf("입고일") + 1;
const cell = function (row) { return p.locator(".io-table tbody tr:nth-child(" + row + ") td:nth-child(" + col + ")"); };
const lines = await cell(1).locator("div").evaluateAll(function (els) {
return els.map(function (el) { return { text: el.textContent, top: el.getBoundingClientRect().top }; });
});
check("여러 날 = 줄바꿈", lines.length === 2 && lines[0].text === "2026.10.21(수)" && lines[1].text === "2026.10.23(금)" && lines[1].top > lines[0].top, lines);
check("하루 입고 = 한 줄", (await cell(2).innerText()).trim() === "2026.10.22(목)");
check("입고 전 = -", (await cell(3).innerText()).trim() === "-");
await p.goto("http://erp.test/inout_locked.html");
await p.waitForTimeout(200);
check("잠긴 입고일은 못 누름", await p.locator('input[name="receipt_date"] + button').isDisabled());
check("스크립트 오류 없음", errors.length === 0, errors);
} finally {
await browser.close();
}
if (fails.length) { console.log("\n" + fails.length + " FAILED"); process.exit(1); }
console.log("\nALL OK");
})();
+118
View File
@@ -0,0 +1,118 @@
// 라이브 커머스 오른쪽 달력(2026-11-05) — 실제 브라우저(Chromium).
// python tests/js/render_live.py
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/live_calendar.browser.test.js
// 세로 2분할·오른쪽 위 고정·전체 너비, 말레이시아 공휴일·대체휴일 빨강·이름·말풍선, 날짜를 누르면 그 날이 표 맨 왼쪽(마지막 날까지), 다른 달은 그 달 화면으로 가서 맨 왼쪽, 영문 화면은 달력도 영어.
const fs = require("fs"), path = require("path");
const { chromium } = require("playwright");
const ROOT = path.join(__dirname, "..", "..");
const fails = [];
function check(name, cond, extra) {
if (cond) console.log("PASS " + name);
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
}
(async function () {
const exe = process.env.PJ_TEST_BROWSER;
const browser = await chromium.launch(exe ? { executablePath: exe } : {});
try {
const p = await (await browser.newContext({ viewport: { width: 1600, height: 900 } })).newPage();
const errors = [];
p.on("pageerror", function (e) { errors.push(String(e)); });
await p.route("**/*", function (r) {
const u = new URL(r.request().url());
if (u.pathname.startsWith("/static/")) {
const f = path.join(ROOT, "app", u.pathname);
if (!fs.existsSync(f)) return r.fulfill({ status: 404, body: "" });
const type = f.endsWith(".css") ? "text/css" : f.endsWith(".js") ? "application/javascript" : "font/woff2";
return r.fulfill({ status: 200, contentType: type, body: fs.readFileSync(f) });
}
const page = u.pathname === "/live/calendar" ? (u.searchParams.get("month") === "2026-12" ? "live_cal_dec.html" : "live_cal_ko.html") : u.pathname.slice(1);
if (!page.endsWith(".html")) return r.fulfill({ status: 200, contentType: "application/json", body: "{}" });
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fs.readFileSync(path.join(__dirname, ".out", page), "utf8") });
});
// 맨 왼쪽 = 그 날 열의 왼쪽 끝이 고정된 시간 열 바로 옆
const gap = function (iso) {
return p.evaluate(function (d) {
const col = document.querySelector('thead th[data-day="' + d + '"]').getBoundingClientRect();
return Math.abs(col.left - document.querySelector("thead .lv-cal-time").getBoundingClientRect().right);
}, iso);
};
const day = function (iso) { return p.locator('#lv-side-cal [data-iso="' + iso + '"]'); };
await p.goto("http://erp.test/live/calendar?month=2026-11");
await p.waitForTimeout(300);
const side = await p.locator("#lv-side-cal").boundingBox(), wrap = await p.locator("#lv-cal-wrap").boundingBox();
const bar = await p.locator(".lv-bar").boundingBox();
check("달력이 오른쪽 위(왼쪽 내용과 같은 높이에서 시작)", side.x >= wrap.x + wrap.width && Math.abs(side.y - bar.y) < 6, { side: side, bar: bar });
check("날짜로 이동 줄 없음", (await p.locator(".lv-jump, [data-jump]").count()) === 0);
const edges = await p.evaluate(function () {
const page = document.querySelector(".erp-page").getBoundingClientRect();
const s = document.getElementById("lv-side-cal").getBoundingClientRect(), l = document.querySelector(".lv").getBoundingClientRect();
return { left: l.left - page.left, right: page.right - s.right };
});
check("좌우 여백 12px", edges.left <= 13 && edges.right <= 13, edges);
await p.setViewportSize({ width: 2400, height: 900 });
await p.waitForTimeout(100);
const wide = await p.evaluate(function () {
const page = document.querySelector(".erp-page").getBoundingClientRect();
return { pageRight: page.right, shell: document.documentElement.clientWidth };
});
check("넓은 화면도 전체 너비(최대 폭 해제)", Math.abs(wide.pageRight - wide.shell) < 2, wide);
// 풀HD 브라우저 — 페이지 세로 스크롤 없음, 모든 시간 칸에 카드가 있어도 표 안 스크롤도 없음
const fit = function () {
return p.evaluate(function () {
const pg = document.querySelector(".erp-page"), w = document.getElementById("lv-cal-wrap");
return { page: pg.scrollHeight - pg.clientHeight, table: w.scrollHeight - w.clientHeight, wrapH: w.clientHeight, row: document.querySelector(".lv-cal tbody tr").getBoundingClientRect().height };
});
};
for (const h of [937, 880]) {
await p.setViewportSize({ width: 1920, height: h });
await p.waitForTimeout(100);
const f = await fit();
check("1920×" + h + ": 페이지·표 세로 스크롤 없음", f.page <= 0 && f.table <= 0, f);
if (h === 880) await p.screenshot({ path: path.join(__dirname, ".out", "live_fit_880.png") });
}
await p.setViewportSize({ width: 1600, height: 600 });
await p.waitForTimeout(100);
const small = await fit();
check("더 낮은 창: 페이지는 안 움직이고 표 안에서 스크롤", small.page <= 0 && small.table > 0, small);
const miniW = (await p.locator("#lv-side-cal").boundingBox()).width;
check("오른쪽 달력 = 240px(300px × 80%)", Math.round(miniW) === 240, miniW);
const miniDay = await day("2026-11-17").evaluate(function (el) { const c = getComputedStyle(el); return c.height + "|" + c.fontSize; });
check("달력 칸·글자도 80%", miniDay === "27px|10.8px", miniDay);
await p.setViewportSize({ width: 1600, height: 900 });
await p.waitForTimeout(100);
check("디파발리 = 빨강·이름·말풍선", (await day("2026-11-08").getAttribute("class")).includes("has-hol") && (await day("2026-11-08").getAttribute("title")) === "디파발리");
check("대체휴일 표시", (await day("2026-11-09").innerText()).includes("대체휴일") && (await day("2026-11-09").getAttribute("title")) === "디파발리 대체", await day("2026-11-09").innerText());
await p.screenshot({ path: path.join(__dirname, ".out", "live_side_cal.png") });
await day("2026-11-17").click();
await p.waitForTimeout(150);
check("17일이 맨 왼쪽", (await gap("2026-11-17")) < 2, await gap("2026-11-17"));
check("누른 날 선택 표시", (await day("2026-11-17").getAttribute("class")).includes("is-selected"));
await day("2026-11-30").click();
await p.waitForTimeout(150);
check("마지막 날도 맨 왼쪽", (await gap("2026-11-30")) < 2, await gap("2026-11-30"));
await p.screenshot({ path: path.join(__dirname, ".out", "live_side_cal_end.png") });
await day("2026-11-02").click();
await p.waitForTimeout(150);
check("앞날로 돌아감", (await gap("2026-11-02")) < 2, await gap("2026-11-02"));
await p.locator('#lv-side-cal [data-nav="1"]').click();
await Promise.all([p.waitForURL(/month=2026-12/), day("2026-12-10").click()]);
await p.waitForTimeout(300);
check("다른 달 = 그 달 화면에서 맨 왼쪽", (await gap("2026-12-10")) < 2, await gap("2026-12-10"));
check("크리스마스 표시", (await day("2026-12-25").getAttribute("title")) === "크리스마스");
await p.goto("http://erp.test/live_cal_en.html");
await p.waitForTimeout(300);
const text = await p.locator("#lv-side-cal").innerText();
check("영문 화면 = 달력도 영어", !/[가-힣]/.test(text) && text.includes("November 2026") && text.includes("Sun") && text.includes("Replacement"), text);
check("영문 말풍선", (await day("2026-11-09").getAttribute("title")) === "Deepavali (Replacement)");
check("스크립트 오류 없음", errors.length === 0, errors);
} finally {
await browser.close();
}
if (fails.length) { console.log("\n" + fails.length + " FAILED"); process.exit(1); }
console.log("\nALL OK");
})();
+63
View File
@@ -0,0 +1,63 @@
// 실적 틱톡 탭(2026-11-05) — 실제 브라우저(Chromium).
// python tests/js/render_performance.py
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/perf_tiktok.browser.test.js
// 광고비 오른쪽 탭, ROAS·광고비·매출 열, 매출·광고비 그래프 둘, 합계 줄 스크롤 고정, 칸 입력 없음, 스크립트 오류 없음.
const fs = require("fs"), path = require("path");
const { chromium } = require("playwright");
const ROOT = path.join(__dirname, "..", "..");
const fails = [];
function check(name, cond, extra) {
if (cond) console.log("PASS " + name);
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
}
(async function () {
const exe = process.env.PJ_TEST_BROWSER;
const browser = await chromium.launch(exe ? { executablePath: exe } : {});
try {
const p = await (await browser.newContext({ viewport: { width: 1400, height: 800 } })).newPage();
const errors = [];
p.on("pageerror", function (e) { errors.push(String(e)); });
await p.route("**/*", function (r) {
const url = new URL(r.request().url()).pathname;
if (url.startsWith("/static/")) {
const f = path.join(ROOT, "app", url);
if (!fs.existsSync(f)) return r.fulfill({ status: 404, body: "" });
const type = f.endsWith(".css") ? "text/css" : f.endsWith(".js") ? "application/javascript" : "font/woff2";
return r.fulfill({ status: 200, contentType: type, body: fs.readFileSync(f) });
}
if (!url.endsWith(".html")) return r.fulfill({ status: 200, contentType: "application/json", body: "{}" });
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fs.readFileSync(path.join(__dirname, ".out", url.slice(1)), "utf8") });
});
await p.goto("http://erp.test/perf_tiktok_shell.html");
await p.waitForTimeout(300);
const tabs = await p.locator(".perf-tabs-main .perf-tab").allInnerTexts();
check("탭 순서 = 매출 실적·광고비·틱톡", tabs.map(function (t) { return t.replace(/^[a-z_]+\s*/, "").trim(); }).join() === "매출 실적,광고비,틱톡", tabs);
check("틱톡 탭이 켜짐", await p.locator(".perf-tab-tiktok.is-active").count() === 1);
const head = await p.locator("table.perf-main thead th").allInnerTexts();
check("열 = 날짜·ROAS·광고비·매출", head.join() === "날짜,ROAS,광고비,매출", head);
const total = await p.locator("table.perf-main tbody tr").first().innerText();
check("맨 위 기간 합계", total.includes("합계") && total.includes("210,000") && total.includes("630,000") && total.includes("300%"), total);
const day = await p.locator("table.perf-main tbody tr", { hasText: "400%" }).first().innerText();
check("일자 줄 값", day.includes("120,000") && day.includes("480,000"), day);
check("매출 그래프", await p.locator("#perf-chart-daily svg rect.bar").count() > 0);
check("광고비 그래프", await p.locator("#perf-chart-daily2 svg rect.bar").count() > 0);
check("칸 입력 없음", await p.locator("[data-manual-code]").count() === 0);
check("업데이트 버튼", (await p.locator("#perf-ad-sync-btn").innerText()).includes("광고비 업데이트"));
await p.screenshot({ path: path.join(__dirname, ".out", "perf_tiktok.png") });
await p.locator("table.perf-main").hover();
await p.mouse.wheel(0, 500);
await p.waitForTimeout(250);
const stuck = await p.evaluate(function () {
const first = document.querySelector("table.perf-main tbody tr.perf-row-total:first-child th");
const top = first.getBoundingClientRect().top;
return document.querySelector("table.perf-main thead th").getBoundingClientRect().bottom <= top + 2 && top >= 0 && top < 300;
});
check("스크롤해도 제목·합계 줄 고정", stuck);
check("스크립트 오류 없음", errors.length === 0, errors);
} finally {
await browser.close();
}
if (fails.length) { console.log("\n" + fails.length + " FAILED"); process.exit(1); }
console.log("\nALL OK");
})();
+52
View File
@@ -0,0 +1,52 @@
"""입출고 날짜 칸 화면을 진짜 ERP 셸(erp_base.html)로 렌더 — 공용 달력 브라우저 테스트용(2026-11-05).
python tests/js/render_inout.py # → tests/js/.out/inout_form.html · inout_list.html · inout_locked.html
DB 없이 날짜 칸에 필요한 값만 넣는다(나머지 값은 비어 있음 — ChainableUndefined). 공휴일 = 실제 표.
"""
from __future__ import annotations
import os
import sys
from datetime import date
import jinja2
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, ROOT)
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
from app.modules.inout.router import _date_holidays # noqa: E402
def _order(no: int, receipt_dates: list[date]) -> dict:
return {"id": no, "order_no": f"PO-26102{no}-01", "factory_name": "대성화학", "items_label": "미라클 봉투", "line_count": 1,
"order_date": date(2026, 10, 20), "due_date": None, "receipt_dates": receipt_dates, "status": "partial", "status_label": "일부 입고",
"summary": {"ordered": 100, "received": 10, "remaining": 90, "over": 0}}
def main() -> None:
os.makedirs(OUT_DIR, exist_ok=True)
env = jinja2.Environment(
loader=jinja2.FileSystemLoader([os.path.join(ROOT, "app", "templates"), os.path.join(ROOT, "app", "modules", "inout", "templates")]),
autoescape=True, undefined=jinja2.ChainableUndefined)
base = {"date_holidays": _date_holidays(), "today": date(2026, 10, 5), "user": {"name": "테스트", "email": "t@test.local"}, "nav_items": [], "perms": {"can_order": True, "can_receive": True}}
pages = {
"inout_form.html": ("inout/order_form.html", {"vals": {"order_date": "2026-10-05", "due_date": ""}, "factories": []}),
"inout_list.html": ("inout/index.html", {"filters": {"from": "2026-10-01", "to": "", "status": "open", "q": "", "factory": ""}, "factories": [], "status_filters": {}, "orders": [
_order(1, [date(2026, 10, 21), date(2026, 10, 23)]), _order(2, [date(2026, 10, 22)]), _order(3, [])]}),
}
for out, (name, ctx) in pages.items():
with open(os.path.join(OUT_DIR, out), "w", encoding="utf-8") as f:
f.write(env.get_template(name).render(**base, **ctx))
# 입고 칸만 — order_detail.html 은 값이 많아, 전체 입고 완료로 잠긴 입고일 칸(disabled)을 같은 스크립트로 확인
locked = env.from_string('{% extends "erp_base.html" %}{% block head_extra %}<link rel="stylesheet" href="/static/inout.css" />{% endblock %}'
'{% block content %}<section class="io"><input type="date" name="receipt_date" value="2026-10-05" aria-label="입고일" required disabled /></section>{% endblock %}'
'{% block scripts %}{% include "inout/_datepop.html" %}<script src="/static/inout.js" defer></script>{% endblock %}')
with open(os.path.join(OUT_DIR, "inout_locked.html"), "w", encoding="utf-8") as f:
f.write(locked.render(**base))
if __name__ == "__main__":
main()
+67
View File
@@ -0,0 +1,67 @@
"""라이브 커머스 달력 보기를 진짜 앱 라우터로 렌더 — 오른쪽 달력 브라우저 테스트용(2026-11-05).
python tests/js/render_live.py # → tests/js/.out/live_cal_ko.html · live_cal_en.html · live_cal_dec.html
DB 없이 가짜 저장소로 11월·12월 화면을 그린다(공휴일 = 실제 표).
"""
from __future__ import annotations
import os
import sys
import tempfile
from datetime import date, time
from decimal import Decimal
from unittest.mock import patch
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, ROOT)
os.chdir(ROOT)
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE", "MALAYSIA_STOCK", "ITEMCODE", "EXPENSE", "INOUT", "OUTREACH", "LIVE"):
os.environ[key + "_DB_URL"] = ""
os.environ.update(SESSION_SECRET_KEY="local-live-test-only", SESSION_COOKIE_SECURE="false", PERFORMANCE_AUTO_SYNC="false", DATA_DIR=tempfile.mkdtemp())
from fastapi.testclient import TestClient # noqa: E402
import app.main as main # noqa: E402
class Fake:
def host_choices(self):
return [{"id": 1, "display_name": "Nabella", "full_name": "Nazzureen Nabella binti Samad", "is_active": True}]
def list_broadcasts(self, start, end):
if start.month != 11:
return []
# 운영 화면처럼 — 6·8·16시 칸에 카드(세 줄 모두 카드가 있으면 그 줄이 가장 높다), 모든 시간 칸을 채워 높이 최악으로
return [{"id": h, "host_id": 1, "host_name": "Nabella", "tiktok_handle": "MainAccount", "broadcast_date": date(2026, 11, 5), "start_time": time(h),
"end_time": time(h + 2), "venue": "", "sales_amount": Decimal("500"), "images": []} for h in range(6, 24, 2) if h < 22] + \
[{"id": 22, "host_id": 1, "host_name": "Nabella", "tiktok_handle": "MainAccount", "broadcast_date": date(2026, 11, 5), "start_time": time(22),
"end_time": time(23, 30), "venue": "", "sales_amount": Decimal("500"), "images": []}]
def ad_spends(self, start, end):
return {}
def account_choices(self):
return ["MainAccount"]
def main_() -> None:
os.makedirs(OUT_DIR, exist_ok=True)
main.app.state.live_store = Fake()
user = {"email": "t@test.local", "name": "T", "role": "user", "is_super_admin": False, "modules": {"live": True}}
with patch.object(main, "get_current_user_record", side_effect=lambda r: user), patch.object(main, "get_session_user", side_effect=lambda r: user), \
patch.object(main.user_store, "get", side_effect=lambda e: user), patch.object(main.user_store, "list_all", side_effect=lambda: [user]):
for name, lang, month in (("live_cal_ko.html", "ko", "2026-11"), ("live_cal_en.html", "en", "2026-11"), ("live_cal_dec.html", "ko", "2026-12")):
client = TestClient(main.app)
client.cookies.set("live_lang", lang)
res = client.get("/live/calendar?month=" + month)
assert res.status_code == 200, (name, res.status_code)
with open(os.path.join(OUT_DIR, name), "w", encoding="utf-8") as f:
f.write(res.text)
print("ok")
if __name__ == "__main__":
main_()
+13 -1
View File
@@ -19,7 +19,7 @@ ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)
sys.path.insert(0, ROOT)
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
from app.modules.performance.ad_spend import build_ad_dashboard # noqa: E402
from app.modules.performance.ad_spend import build_ad_dashboard, build_tiktok_dashboard # noqa: E402
from app.modules.performance.dashboard import amount_text, build_dashboard, build_settings # noqa: E402
from app.modules.performance.router import _auto_sync_settings_ctx # noqa: E402
@@ -84,6 +84,12 @@ def env() -> jinja2.Environment:
return e
class TiktokStore:
def ad_details(self, code, start, end):
rows = [("2026-10-02", 120000, 480000), ("2026-10-05", 90000, 150000), ("2026-09-20", 50000, 100000)]
return [{"date": d, "amount": a, "roas": None, "metrics": {"매출": b}, "source": "api"} for d, a, b in rows]
def main() -> None:
os.makedirs(OUT_DIR, exist_ok=True)
e = env()
@@ -117,6 +123,12 @@ def main() -> None:
html = shell.get_template("performance/ads.html").render(**sbase, active_tab="ads", **sactx)
with open(os.path.join(OUT_DIR, "perf_ads_shell.html"), "w", encoding="utf-8") as f:
f.write(html)
# 틱톡 탭(2026-11-05) — 가상의 광고 API 값
tk = build_tiktok_dashboard(TiktokStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7), holidays={"2026-10-03": "개천절"})
tk.update(auto_sync=ctx["auto_sync"], update_watch={"kind": "ads", "seen": "job-old"}, tiktok_configured=True, ad_running=False,
ad_last_update_at=None, ad_sync_sources=[{"code": "tiktok", "name": "틱톡"}])
with open(os.path.join(OUT_DIR, "perf_tiktok_shell.html"), "w", encoding="utf-8") as f:
f.write(shell.get_template("performance/tiktok.html").render(**sbase, active_tab="tiktok", **tk))
actx =build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
sales_codes=["cafe24", "coupang"])
actx["ad_sync_sources"] = [{"code": "google", "name": "구글 광고"}] # [구글 광고 불러오기]
+30
View File
@@ -15,6 +15,26 @@ DSN = os.getenv("INOUT_TEST_DB_URL", "")
ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
class ListReceiptDatesNoDbTests(unittest.TestCase):
"""DB 없이 — 발주별로 입고일을 묶어 돌려주는지(입고 없는 발주 = 빈 목록)."""
def test_groups_dates_by_order(self):
from contextlib import nullcontext
from unittest.mock import MagicMock
from app.modules.inout.db import InoutDBStore
heads = [{"id": i, "order_no": f"PO-{i}", "closed_at": None, "cancelled_at": None} for i in (1, 2)]
lines = [{"order_id": i, "item_code": "A", "item_name": "A", "qty": 10, "received": 1} for i in (1, 2)]
receipts = [{"order_id": 1, "receipt_date": date(2026, 10, 21)}, {"order_id": 1, "receipt_date": date(2026, 10, 23)}]
conn = MagicMock()
conn.execute.side_effect = lambda sql, *a: MagicMock(fetchall=lambda: receipts if "receipt_date" in sql else lines if "inout_order_lines l" in sql else heads)
st = InoutDBStore.__new__(InoutDBStore)
st._pool = MagicMock(connection=lambda: nullcontext(conn))
got = {o["id"]: o["receipt_dates"] for o in st.list_orders()}
self.assertEqual(got, {1: [date(2026, 10, 21), date(2026, 10, 23)], 2: []})
@unittest.skipUnless(ENABLED, "INOUT_TEST_DB_URL(localhost) not set")
class InoutDbTests(unittest.TestCase):
@classmethod
@@ -66,6 +86,16 @@ class InoutDbTests(unittest.TestCase):
self.assertNotIn(o["id"], [x["id"] for x in self.st.list_orders(status="active", factory_id=self.fid)])
self.assertIn(o["id"], [x["id"] for x in self.st.list_orders(status="done", factory_id=self.fid)])
def test_list_receipt_dates(self):
"""목록 입고일 — 입고 전 빈 목록, 여러 날은 오래된 날부터, 같은 날 두 번은 한 번만."""
o = self.order([("MT-D", 100)])
line = self.line_ids(o["id"])["MT-D"]
dates = lambda: next(x for x in self.st.list_orders(status="all", factory_id=self.fid) if x["id"] == o["id"])["receipt_dates"]
self.assertEqual(dates(), [])
for day in ("2026-10-23", "2026-10-21", "2026-10-23"):
self.st.add_receipt(o["id"], {line: "10"}, receipt_date=day, memo="", confirm_over=False, by="w@x")
self.assertEqual(dates(), [date(2026, 10, 21), date(2026, 10, 23)])
def test_over_receipt_needs_confirm(self):
from app.modules.inout.db import OverReceipt
+205 -16
View File
@@ -60,16 +60,46 @@ 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"], got["tiktok_handle"]), ("Siti Aisyah", "siti.live"))
self.assertEqual(store.clean_host({"full_name": "A"})["phone"], "") # Full Name 만 필수
for bad in ({}, {"full_name": " "}, {"full_name": "A", "email": "nope"}, {"full_name": "A", "phone": "abc"},
{"full_name": "A", "bank_account": "12a"}, {"full_name": "A", "tiktok_handle": "한글"},
{"full_name": "x" * 201}):
self.assertEqual((got["display_name"], got["full_name"]), ("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, "bank_account": "12a"}, {**ok, "full_name": "x" * 201}, {**ok, "display_name": "x" * 51}):
with self.assertRaises(ValueError, msg=bad):
store.clean_host(bad)
def test_broadcast_account(self):
good = {"host_id": "3", "broadcast_date": "2026-11-04", "start_time": "20:00", "end_time": "22:00"}
self.assertEqual(store.clean_broadcast(good)["tiktok_handle"], "") # 선택 칸
self.assertEqual(store.clean_broadcast({**good, "tiktok_handle": "https://www.tiktok.com/@alt.acc?lang=en"})["tiktok_handle"], "alt.acc")
for bad in ("한글", "x" * 65):
with self.assertRaises(ValueError, msg=bad):
store.clean_broadcast({**good, "tiktok_handle": bad})
def test_edit_keeps_broadcast_account(self):
"""고치기 창에 계정이 채워져야 저장하면서 지워지지 않는다."""
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", "Yaya")) # 카드 머리 = 호스트, 계정은 아래
def test_my_holidays(self):
from app.modules.live import holidays
ko, en = holidays.holiday_names("ko"), holidays.holiday_names("en")
self.assertEqual(set(ko), set(en))
for day in ko:
date.fromisoformat(day)
self.assertEqual((ko["2026-11-08"], ko["2026-11-09"]), ("디파발리", "디파발리 대체"))
self.assertEqual((en["2026-11-08"], en["2026-11-09"]), ("Deepavali", "Deepavali (Replacement)"))
self.assertIn("Federal Territory Day", en["2026-02-01"])
self.assertFalse([n for n in en.values() if re.search("[가-힣]", n)])
# 대체휴일은 평일에 — 토·일이면 표가 틀린 것
for day, name in en.items():
if "Replacement" in name:
self.assertLess(date.fromisoformat(day).weekday(), 5, day)
def test_clean_handle(self):
for raw in ("@siti.live", "siti.live", "https://www.tiktok.com/@siti.live?lang=en", "tiktok.com/@siti.live/video/1"):
self.assertEqual(store.clean_handle(raw), "siti.live", raw)
@@ -86,7 +116,7 @@ class StoreTests(unittest.TestCase):
got = store.clean_broadcast({"host_id": "3", "broadcast_date": "2026-11-04", "start_time": "20:00", "end_time": "22:00",
"venue": " Studio ", "sales_amount": "100"})
self.assertEqual(got, {"host_id": 3, "broadcast_date": date(2026, 11, 4), "start_time": time(20, 0), "end_time": time(22, 0),
"venue": "Studio", "sales_amount": Decimal("100.00")})
"venue": "Studio", "tiktok_handle": "", "sales_amount": Decimal("100.00")})
good = {"host_id": "3", "broadcast_date": "2026-11-04", "start_time": "20:00", "end_time": "22:00"}
for over in ({"host_id": ""}, {"host_id": "x"}, {"broadcast_date": ""}, {"broadcast_date": "2026-13-01"}, {"start_time": ""},
{"start_time": "25:00"}, {"end_time": ""}, {"end_time": "nope"}, {"end_time": "20:00"}, {"venue": "x" * 201}, {"sales_amount": "-5"}):
@@ -153,7 +183,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")
@@ -213,6 +243,165 @@ def body(c):
assert nav and nav[0]["label"] == "라이브 커머스" # 사이드바는 짧게
print("OK")
run(body)
''')
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
def test_live_host_chip_adds_only(self):
"""`live_host` 칩 = 새 호스트 등록만 — 계좌 안 보임, 고치기·지우기·사용 안 함 불가. DB 없이 가짜 저장소로."""
res = _run('''
from app.store import MODULE_KEYS
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}]
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",
"bank_account": "998877", "is_active": True}]
def list_broadcasts(self, start, end):
return []
def account_choices(self):
return ["MainAccount", "alt.acc"]
def save_host(self, host_id, values, *, is_active, by):
self.saved.append((host_id, values["full_name"], is_active, by))
return 2
def delete_host(self, host_id):
self.saved.append(("deleted", host_id))
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"}
def body(c):
who["u"] = adder
sched = c.get("/live/").text
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"'):
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 len(fake.saved) == 1, fake.saved
for no_add in (U("staff@t.local"), chip_only):
who["u"] = no_add
assert c.get("/live/settings").status_code == 403
assert c.post("/live/settings/hosts", data=new).status_code == 403
assert len(fake.saved) == 1, fake.saved
# 관리자는 그대로 — 계좌 보임, 고치기, 사용 안 함
who["u"] = U("a@t.local", role="admin")
page = c.get("/live/settings").text
assert "998877" in page and "data-edit='" in page and 'name="is_active"' in page
assert c.post("/live/settings/hosts", data={**new, "id": "1"}).json()["ok"]
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)
def test_calendar_page_side_calendar(self):
res = _run('''
import json, re
class Fake:
def host_choices(self):
return []
def list_broadcasts(self, start, end):
return []
def ad_spends(self, start, end):
return {}
def account_choices(self):
return []
main.app.state.live_store = Fake()
def names(page):
return json.loads(re.search(r'id="lv-my-holidays">(.*?)</script>', page).group(1))
def body(c):
who["u"] = U("s@t.local")
page = c.get("/live/calendar?month=2026-11").text
assert 'id="lv-side-cal"' in page and "/static/erp-datepop.js" in page
assert names(page)["2026-11-09"] == "디파발리 대체"
c.cookies.set("live_lang", "en")
assert names(c.get("/live/calendar?month=2026-11").text)["2026-11-09"] == "Deepavali (Replacement)"
print("OK")
run(body)
''')
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
@@ -258,8 +447,8 @@ def jpeg():
return raw.getvalue()
def body(c):
host = {"full_name": NAME, "phone": "+60 12-345", "email": "siti@example.my", "address": "Kuala Lumpur",
"bank_name": "Maybank", "bank_account": ACCOUNT, "tiktok_handle": "@siti.%s" % tag, "is_active": "1"}
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
assert c.get("/live/settings").status_code == 403
@@ -273,17 +462,17 @@ def body(c):
assert r.json()["ok"], r.text
hid = next(h["id"] for h in st.list_hosts() if h["full_name"] == NAME)
page = c.get("/live/settings").text
for field in ("이름 (IC 기준)", "전화번호", "이메일", "주소", "은행명", "계좌번호", "틱톡 핸들"):
for field in ("이름 (IC 기준)", "전화번호", "이메일", "주소", "은행명", "계좌번호"):
assert field in page, field
assert ACCOUNT in page and "Siti &lt;b&gt;" in page and "<b>" + tag not in page
assert st.list_hosts() and next(h for h in st.list_hosts() if h["id"] == hid)["tiktok_handle"] == "siti." + tag
assert "틱톡 핸들" not in page and 'name="tiktok_handle"' not in page # 계정은 방송마다
# ── 스케줄: 일반 권한자도 추가·고치기, 화면에 계좌·주소 없음 ──
who["u"] = staff
page = c.get("/live/?month=2031-03").text
assert 'value="%d"' % hid in page and "@siti." + tag in page
assert 'value="%d"' % hid in page
assert ACCOUNT not in page and "Kuala Lumpur" not in page and "Maybank" not in page
show = {"host_id": hid, "broadcast_date": "2031-03-05", "start_time": "20:00", "end_time": "22:30", "venue": "KL Studio", "sales_amount": "1,234.5"}
show = {"host_id": hid, "broadcast_date": "2031-03-05", "start_time": "20:00", "end_time": "22:30", "venue": "KL Studio", "tiktok_handle": "@siti.%s" % tag, "sales_amount": "1,234.5"}
assert c.post("/live/broadcasts", data={**show, "host_id": ""}).status_code == 400
assert c.post("/live/broadcasts", data={**show, "host_id": 99999999}).status_code == 400
junk = c.post("/live/broadcasts", data=show, files=[("images", ("x.jpg", b"not an image", "image/jpeg"))])
@@ -322,8 +511,8 @@ def body(c):
# ── 달력: 카드 머리 = Tiktok Handle, Fee, 옮기기(길이 유지)·맞바꾸기, 광고비·ROAS, 권한 ──
c.post("/live/broadcasts", data={**show, "id": bid, "sales_amount": "48", "start_time": "12:00", "end_time": "14:00", "broadcast_date": "2031-03-05"})
cal = c.get("/live/calendar?month=2031-03").text
assert "날짜로 이동" in cal and "토요일" in cal and "12:00 - 14:00" in cal and "2시간 (기본 RM50)" in cal
assert '<span class="lv-card-name">siti.%s</span>' % tag in cal and "RM54.80" in cal and ">4.80</b>" in cal
assert "날짜로 이동" not in cal and "토요일" in cal and "12:00 - 14:00" in cal and "2시간 (기본 RM50)" in cal
assert '<span class="lv-card-name">S%s<small>@siti.%s</small></span>' % (tag, tag) in cal and "RM54.80" in cal and ">4.80</b>" in cal
# ── 영문: 화면 세 개 모두 한글 없음(입력한 데이터 제외)·날짜·오류·권한 문구 ──
def no_korean(url):