From cf0e3f2139e6cb734a6e63bbc3fe9fafd52ca36f Mon Sep 17 00:00:00 2001 From: king Date: Thu, 5 Nov 2026 18:50:29 +0900 Subject: [PATCH] =?UTF-8?q?feat(=EB=9D=BC=EC=9D=B4=EB=B8=8C):=20=EB=8B=AC?= =?UTF-8?q?=EB=A0=A5=20=EB=B3=B4=EA=B8=B0=20=EC=98=A4=EB=A5=B8=EC=AA=BD?= =?UTF-8?q?=EC=97=90=20=EA=B3=B5=EC=9A=A9=20=EB=8B=AC=EB=A0=A5=EA=B3=BC=20?= =?UTF-8?q?=EB=A7=90=EB=A0=88=EC=9D=B4=EC=8B=9C=EC=95=84=20=EA=B3=B5?= =?UTF-8?q?=ED=9C=B4=EC=9D=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 표 오른쪽에 erp-datepop 붙박이 달력을 두고, 날짜를 누르면 그 날이 표 맨 왼쪽에 오게 한다. 다른 달을 누르면 그 달 화면으로 이동해 같은 위치로 맞춘다. 마지막 날도 맨 왼쪽에 오도록 표 끝에 여백을 둔다. 말레이시아 공휴일·대체휴일 표(holidays.py, 쿠알라룸푸르 기준 2026·2027)를 표시한다. 공용 달력에 선택 옵션 locale 을 추가해 영문 화면도 영어로 그린다. 기존 화면 동작은 그대로. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- .../inout/templates/inout/_datepop.html | 2 +- app/modules/live/CLAUDE.md | 2 + app/modules/live/holidays.py | 59 +++++++++++++ app/modules/live/router.py | 5 +- app/modules/live/templates/live/_scripts.html | 2 +- app/modules/live/templates/live/calendar.html | 12 ++- app/modules/live/templates/live/index.html | 2 +- app/modules/live/templates/live/settings.html | 2 +- .../vacation/templates/vacation/form.html | 2 +- .../vacation/templates/vacation/options.html | 2 +- app/static/erp-datepop.js | 18 ++-- app/static/live.css | 7 ++ app/static/live.js | 50 +++++++++-- tests/js/live_calendar.browser.test.js | 82 +++++++++++++++++++ tests/js/render_live.py | 64 +++++++++++++++ tests/test_live.py | 46 +++++++++++ 17 files changed, 334 insertions(+), 25 deletions(-) create mode 100644 app/modules/live/holidays.py create mode 100644 tests/js/live_calendar.browser.test.js create mode 100644 tests/js/render_live.py diff --git a/CLAUDE.md b/CLAUDE.md index 02b0e47..3ab76ce 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -66,7 +66,7 @@ - `asset/media.py prepare_photo`(이미지 확인·메타데이터 제거): 자산 + 라이브 커머스. - `app/mail.py`: 프로젝트 알림 메일. - ERP 모든 화면 스크립트: `erp-notice.js`(공지) · `erp-overdue.js`(프로젝트 마감 알림). -- 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청·입출고 날짜 칸) — 바꾸면 둘 다. +- 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청·입출고 날짜 칸·라이브 오른쪽 달력) — 바꾸면 둘 다. - 국경일·대체공휴일 표 `project/store.py KR_HOLIDAYS`: 프로젝트 캘린더·날짜 팝업 + 휴가(달력·일수 계산 `vacation/db.holiday_map`) + 입출고(오른쪽 달력·날짜 칸). --- diff --git a/app/modules/inout/templates/inout/_datepop.html b/app/modules/inout/templates/inout/_datepop.html index de86fd2..76ad3d6 100644 --- a/app/modules/inout/templates/inout/_datepop.html +++ b/app/modules/inout/templates/inout/_datepop.html @@ -2,4 +2,4 @@ - + diff --git a/app/modules/live/CLAUDE.md b/app/modules/live/CLAUDE.md index a489d68..39ed7e1 100644 --- a/app/modules/live/CLAUDE.md +++ b/app/modules/live/CLAUDE.md @@ -17,6 +17,8 @@ - **달력 보기** `/live/calendar?month=`(`store.build_calendar`, 사용자가 준 화면 참고, 글자도 영어 그대로) — 줄 = 2시간 칸(06:00~24:00 늘 보임, 그보다 이른 칸은 방송이 있을 때만, 칸은 시작 시간으로 정함), 열 = 날짜, 주말 노랑, Jump to Date, 위 달 합계, 맨 아래 날짜별 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, 달력 보기만, 공용 `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(그때그때 만듦). 올린 뒤 내용이 안 바뀐다는 전제 — 이미지를 고치는 기능을 넣으면 캐시도 바꿀 것. - 저장은 `live.js` 가 fetch → JSON `{ok, message}`(틀려도 창의 입력값 유지). 창 하나로 추가·고치기(`data-edit` JSON). diff --git a/app/modules/live/holidays.py b/app/modules/live/holidays.py new file mode 100644 index 0000000..cc174d2 --- /dev/null +++ b/app/modules/live/holidays.py @@ -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 diff --git a/app/modules/live/router.py b/app/modules/live/router.py index 72d9f9e..101fb39 100644 --- a/app/modules/live/router.py +++ b/app/modules/live/router.py @@ -24,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"]) @@ -160,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(), - "accounts": st.account_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") diff --git a/app/modules/live/templates/live/_scripts.html b/app/modules/live/templates/live/_scripts.html index 98ed789..9a7c39d 100644 --- a/app/modules/live/templates/live/_scripts.html +++ b/app/modules/live/templates/live/_scripts.html @@ -1,2 +1,2 @@ - + diff --git a/app/modules/live/templates/live/calendar.html b/app/modules/live/templates/live/calendar.html index b8fbb13..8472f99 100644 --- a/app/modules/live/templates/live/calendar.html +++ b/app/modules/live/templates/live/calendar.html @@ -1,7 +1,9 @@ {% extends "erp_base.html" %} {#- 라이브 커머스 달력 보기(2026-11-04) — 줄 = 2시간 칸, 열 = 날짜, 맨 아래 = 날짜별 합계. 카드 머리 = 호스트 간단한 이름 + 그 방송의 틱톡 계정. 카드 머리를 끌어 빈 칸으로 옮기거나 다른 카드 위에 놓아 맞바꾼다(live.js). 문구 = t()(i18n.py), 영문은 CSS 로 대문자(받은 화면과 같게). -#} -{% block head_extra %}{% endblock %} +{% block head_extra %} + +{% endblock %} {% block content %}
@@ -20,6 +22,7 @@

{{ t('팁: 카드 머리를 끌어 옮기거나 맞바꿀 수 있습니다. 오른쪽으로 스크롤하면 이달 {n}일을 모두 볼 수 있습니다.').format(n=cal.days | length) }}

+
@@ -78,9 +81,14 @@
+ {#- 오른쪽 달력 — 날짜를 누르면 그 날이 표 맨 왼쪽(live.js), 말레이시아 공휴일(holidays.py) -#} + +
{% include "live/_dialog.html" %} {% endblock %} -{% block scripts %}{% include "live/_scripts.html" %}{% endblock %} +{% block scripts %} + +{% include "live/_scripts.html" %}{% endblock %} diff --git a/app/modules/live/templates/live/index.html b/app/modules/live/templates/live/index.html index ba26840..d1388c7 100644 --- a/app/modules/live/templates/live/index.html +++ b/app/modules/live/templates/live/index.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} {#- 라이브 커머스 스케줄표(2026-11-04) — 달마다 방송 목록. 추가·고치기 창은 달력과 공용(_dialog.html, live.js). 문구 = t()(i18n.py). -#} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
diff --git a/app/modules/live/templates/live/settings.html b/app/modules/live/templates/live/settings.html index a1a6a15..0932aa3 100644 --- a/app/modules/live/templates/live/settings.html +++ b/app/modules/live/templates/live/settings.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} {#- 라이브 커머스 설정(2026-11-04) — 호스트 정보. 계좌 등 개인정보·지우기는 ERP 관리자만(router.settings), 칩 권한자는 이름·상태만 보임 — `live_host` = 새 등록, `live_host_edit` = 고치기(개인정보는 빈칸으로 열림, 비워 두면 그대로). 추가·고치기는 같은 창(live.js). 문구 = t()(i18n.py). -#} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
diff --git a/app/modules/vacation/templates/vacation/form.html b/app/modules/vacation/templates/vacation/form.html index 5be5ea9..494c106 100644 --- a/app/modules/vacation/templates/vacation/form.html +++ b/app/modules/vacation/templates/vacation/form.html @@ -134,5 +134,5 @@ {% endblock %} {% block scripts %} - + {% endblock %} diff --git a/app/modules/vacation/templates/vacation/options.html b/app/modules/vacation/templates/vacation/options.html index 8a79273..0930b9f 100644 --- a/app/modules/vacation/templates/vacation/options.html +++ b/app/modules/vacation/templates/vacation/options.html @@ -149,5 +149,5 @@
{% endblock %} -{% block scripts %} +{% block scripts %} {% endblock %} diff --git a/app/static/erp-datepop.js b/app/static/erp-datepop.js index f0804cd..fec7884 100644 --- a/app/static/erp-datepop.js +++ b/app/static/erp-datepop.js @@ -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 += '"; } return '
' + - ["일", "월", "화", "수", "목", "금", "토"].map(function (w, i) { + ((locale && locale.weekdays) || ["일", "월", "화", "수", "목", "금", "토"]).map(function (w, i) { return '' + w + ""; }).join("") + days + "
"; } @@ -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 = '
' + - '' + - '' + viewY + "년 " + (viewM + 1) + "월" + - '' + - "
" + gridHtml(viewY, viewM, holidays, today, bandClasses); + '' + + '' + esc(loc.title ? loc.title(viewY, viewM) : viewY + "년 " + (viewM + 1) + "월") + "" + + '' + + "" + gridHtml(viewY, viewM, holidays, today, bandClasses, opts.locale); } box.addEventListener("click", function (e) { const nav = e.target.closest(".pj-dp-navbtn"); diff --git a/app/static/live.css b/app/static/live.css index 57bca78..f338f63 100644 --- a/app/static/live.css +++ b/app/static/live.css @@ -46,6 +46,13 @@ .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; } +/* 표 + 오른쪽 달력(공용 erp-datepop 서식) */ +.lv-cal-row { display: grid; grid-template-columns: minmax(0, 1fr) 300px; gap: 14px; align-items: start; } +.lv-side-cal { box-sizing: border-box; padding: 12px; border: 1px solid #cfd4dc; border-radius: 10px; background: #fff; font-size: 13px; } +@media (max-width: 1100px) { + .lv-cal-row { grid-template-columns: minmax(0, 1fr); } + .lv-side-cal { max-width: 340px; } +} .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; } diff --git a/app/static/live.js b/app/static/live.js index 17ece6d..9fd715b 100644 --- a/app/static/live.js +++ b/app/static/live.js @@ -4,6 +4,7 @@ "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() { @@ -131,17 +132,54 @@ const time = calWrap.querySelector("thead .lv-cal-time"); if (col && time) calWrap.scrollLeft += col.getBoundingClientRect().left - time.getBoundingClientRect().right; } + // 마지막 날들도 맨 왼쪽까지 오도록 표 끝에 여백(표 상자 너비 − 시간 열 − 날짜 열 하나) + 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"); + let sideCal = null; + if (sideBox && window.ErpDatePop) { + let holidays = {}; + try { holidays = JSON.parse(document.getElementById("lv-my-holidays").textContent); } catch (_) {} + const english = document.querySelector(".lv").lang === "en"; + sideCal = 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); + }, + }); + } document.addEventListener("click", function (e) { const b = e.target.closest("[data-jump]"); - if (b) jumpTo(b.dataset.jump); + if (!b) return; + jumpTo(b.dataset.jump); + if (sideCal) sideCal.set(b.dataset.jump, b.dataset.jump); }); 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) { diff --git a/tests/js/live_calendar.browser.test.js b/tests/js/live_calendar.browser.test.js new file mode 100644 index 0000000..c9ec707 --- /dev/null +++ b/tests/js/live_calendar.browser.test.js @@ -0,0 +1,82 @@ +// 라이브 커머스 오른쪽 달력(2026-11-05) — 실제 브라우저(Chromium). +// python tests/js/render_live.py +// NODE_PATH= PJ_TEST_BROWSER= node tests/js/live_calendar.browser.test.js +// 표 오른쪽에 달력, 말레이시아 공휴일·대체휴일 빨강·이름·말풍선, 날짜를 누르면 그 날이 표 맨 왼쪽(마지막 날까지), 다른 달은 그 달 화면으로 가서 맨 왼쪽, 영문 화면은 달력도 영어. +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(); + check("달력이 표 오른쪽", side.x >= wrap.x + wrap.width && Math.abs(side.y - wrap.y) < 2, { side: side, wrap: wrap }); + 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-jump-day[data-jump="2026-11-20"]').click(); + await p.waitForTimeout(150); + check("날짜로 이동 줄도 맨 왼쪽·달력 선택 따라감", (await gap("2026-11-20")) < 2 && (await day("2026-11-20").getAttribute("class")).includes("is-selected")); + + 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"); +})(); diff --git a/tests/js/render_live.py b/tests/js/render_live.py new file mode 100644 index 0000000..1673686 --- /dev/null +++ b/tests/js/render_live.py @@ -0,0 +1,64 @@ +"""라이브 커머스 달력 보기를 진짜 앱 라우터로 렌더 — 오른쪽 달력 브라우저 테스트용(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 [] + return [{"id": 1, "host_id": 1, "host_name": "Nabella", "tiktok_handle": "MainAccount", "broadcast_date": date(2026, 11, 5), "start_time": time(8), + "end_time": time(10), "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_() diff --git a/tests/test_live.py b/tests/test_live.py index e5b5173..00ee309 100644 --- a/tests/test_live.py +++ b/tests/test_live.py @@ -85,6 +85,21 @@ class StoreTests(unittest.TestCase): "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) @@ -356,6 +371,37 @@ def body(c): 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">(.*?)', 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)