Files
dbx-main/app/static/live.js
T
king be4c663f70 feat(라이브): 달력 카드 이미지 링크에 마우스를 올리면 오른쪽 달력 아래에 미리보기
- 오른쪽 줄을 달력 + 미리보기(.lv-side)로, 첫 장·호스트·날짜·시간 표시, 벗어나면 숨김
- 키보드 탭으로 가도 표시, 좁은 화면은 미리보기 없음(링크는 그대로 새 탭)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 11:22:19 +09:00

282 lines
14 KiB
JavaScript

/* 라이브 커머스(2026-11-04) — 스케줄표·달력·호스트 설정 공용: 추가·고치기 창, 저장·지우기(fetch → JSON {ok, message}, 틀려도 입력한 값이 창에 남음).
달력: 오른쪽 달력으로 날짜 이동, 카드 끌어 옮기기·맞바꾸기, 날짜별 광고비. 다시 그린 뒤에도 보던 가로 위치 유지. */
(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() {
if (calWrap) { try { sessionStorage.setItem(CAL_POS, String(calWrap.scrollLeft)); } catch (_) {} }
location.reload();
}
// 한글·영문 전환 — 브라우저마다 기억(쿠키, /live 안에서만), 서버가 그 언어로 그린다
document.addEventListener("click", function (e) {
const b = e.target.closest("button[data-lang]");
if (!b) return;
document.cookie = "live_lang=" + b.dataset.lang + "; path=/live; max-age=31536000; SameSite=Lax" + (location.protocol === "https:" ? "; Secure" : "");
reload();
});
const dlg = document.getElementById("lv-dlg");
const form = document.getElementById("lv-form");
if (!dlg || !form) return;
const title = dlg.querySelector("#lv-dlg-title");
const msg = form.querySelector("[data-msg]");
const saved = form.querySelector("[data-saved]");
const hostSelect = form.querySelector('select[name="host_id"]');
const fileInput = form.querySelector('input[type="file"]');
function say(text, info) {
msg.textContent = text || "";
msg.hidden = !text;
msg.classList.toggle("is-info", !!info);
}
async function post(url, body) {
try {
const res = await fetch(url, { method: "POST", body: body, headers: { Accept: "application/json" } });
const data = await res.json().catch(function () { return {}; });
return { ok: res.ok && data.ok !== false, message: data.message || data.detail || "HTTP " + res.status, data: data };
} catch (_) {
return { ok: false, message: tr("서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.") };
}
}
// 사용 안 함 호스트는 그 호스트로 이미 등록된 방송을 고칠 때만 보인다
function showHosts(current) {
if (!hostSelect) return;
Array.from(hostSelect.options).forEach(function (opt) {
const off = opt.dataset.inactive === "1" && opt.value !== String(current || "");
opt.hidden = off;
opt.disabled = off;
});
}
function showSaved(images) {
if (!saved) return;
saved.textContent = "";
(images || []).forEach(function (im) {
const li = document.createElement("li");
const link = document.createElement("a");
link.href = "/live/images/" + im.id;
link.target = "_blank";
link.rel = "noopener";
link.textContent = im.filename || "#" + im.id;
const del = document.createElement("button");
del.type = "button";
del.className = "erp-btn erp-btn-outline erp-btn-sm";
del.dataset.post = "/live/images/" + im.id + "/delete";
del.dataset.confirm = tr("{name} 를 지울까요?").replace("{name}", im.filename || tr("이 이미지"));
del.textContent = tr("지우기");
li.append(link, del);
saved.appendChild(li);
});
saved.hidden = !saved.children.length;
}
function open(row) {
form.reset();
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;
if (el.type === "checkbox") el.checked = !!row[el.name];
else if (el.type === "radio") el.checked = el.value === row[el.name];
else if (el.type !== "file") el.value = row[el.name];
});
showHosts(editing && row.host_id);
if (editing && hostSelect) hostSelect.value = String(row.host_id); // 위에서 보이게 한 뒤 다시 고름
showSaved(editing && row.images);
dlg.showModal();
}
const addBtn = document.getElementById("lv-add");
if (addBtn) addBtn.addEventListener("click", function () { open(null); });
dlg.addEventListener("click", function (e) {
if (e.target.closest("[data-close]")) dlg.close();
});
document.addEventListener("click", async function (e) {
const edit = e.target.closest("[data-edit]");
if (edit && edit.tagName === "BUTTON") { open(JSON.parse(edit.dataset.edit)); return; }
const fresh = e.target.closest("button[data-new]");
if (fresh) { open(JSON.parse(fresh.dataset.new)); return; }
const btn = e.target.closest("button[data-post]");
if (!btn) return;
if (!(await window.erpConfirm(btn.dataset.confirm, dialogText()))) return;
const r = await post(btn.dataset.post);
if (r.ok) { reload(); return; }
if (dlg.open) say(r.message); else window.erpAlert(r.message, dialogText());
});
// 호스트 목록의 사용 토글 — 바로 저장, 실패하면 되돌림. 줄 흐림(lv-off)만 바꾸고 다시 그리지 않음
document.addEventListener("change", async function (e) {
const sw = e.target.closest("input[data-active]");
if (!sw) return;
const body = new FormData();
body.set("is_active", sw.checked ? "1" : "0");
sw.disabled = true;
const r = await post(sw.dataset.active, body);
sw.disabled = false;
if (!r.ok) { sw.checked = !sw.checked; window.erpAlert(r.message, dialogText()); return; }
const line = sw.closest("tr");
line.classList.toggle("lv-off", !sw.checked);
const edit = line.querySelector("[data-edit]"); // 고치기 창이 옛 값으로 열려 저장 때 되돌리지 않게
if (edit) { const row = JSON.parse(edit.dataset.edit); row.is_active = sw.checked; edit.dataset.edit = JSON.stringify(row); }
});
// 결과 이미지를 고르면 서버가 글자 인식으로 매출(틱톡 LIVE 결과 화면의 첫 RM 금액)을 읽어 판매금액 칸에 채운다 — 저장은 사람이 확인 후
const salesInput = form.elements.sales_amount;
if (fileInput && salesInput) fileInput.addEventListener("change", async function () {
const files = Array.from(fileInput.files);
if (!files.length) return;
const save = form.querySelector('button[type="submit"]');
save.disabled = true;
say(tr("이미지에서 매출을 읽는 중…"), true);
let r = null;
for (const f of files) { // 매출을 찾을 때까지 한 장씩
const body = new FormData();
body.set("image", f);
r = await post("/live/broadcasts/read-sales", body);
if (!r.ok || r.data.amount) break;
}
save.disabled = false;
if (r.ok && r.data.amount) salesInput.value = r.data.amount;
say(r.message, r.ok);
});
form.addEventListener("submit", async function (e) {
e.preventDefault();
const save = form.querySelector('button[type="submit"]');
const body = new FormData(form);
if (fileInput && !fileInput.files.length) body.delete("images");
save.disabled = true;
say("");
const r = await post(form.getAttribute("action"), body);
if (r.ok) { reload(); return; }
save.disabled = false;
say(r.message);
});
if (!calWrap) return;
// ── 달력: 날짜로 가기(TIME 열이 고정이라 그 폭만큼 띄움) ──
function jumpTo(iso) {
const col = calWrap.querySelector('thead th[data-day="' + iso + '"]');
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");
if (sideBox && window.ErpDatePop) {
let holidays = {};
try { holidays = JSON.parse(document.getElementById("lv-my-holidays").textContent); } catch (_) {}
let liveDays = {}; // 방송 있는 날 → 점
try { JSON.parse(document.getElementById("lv-live-days").textContent).forEach(function (iso) { liveDays[iso] = true; }); } catch (_) {}
const english = document.querySelector(".lv").lang === "en";
window.ErpDatePop.mountRange(sideBox, {
start: shownDay, end: shownDay, holidays: holidays, single: function () { return true; },
dayClass: function (iso) { return liveDays[iso] ? ["has-live"] : []; },
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 (hasDay(pending)) jumpTo(pending);
else if (left !== null) calWrap.scrollLeft = Number(left);
else if (todayHead) jumpTo(todayHead.dataset.day);
// ── 달력: 카드의 이미지 링크에 마우스를 올리거나 탭으로 가면 오른쪽 달력 아래에 결과 이미지(첫 장), 벗어나면 숨김 ──
const preview = document.getElementById("lv-preview");
if (preview) {
const pImg = preview.querySelector("img"), pCap = preview.querySelector("figcaption");
const linkOf = function (el) { return el && el.closest && el.closest("a[data-preview]"); };
const show = function (a) {
if (pImg.getAttribute("src") !== a.getAttribute("href")) pImg.src = a.getAttribute("href");
pImg.alt = a.title;
pCap.textContent = a.dataset.preview;
preview.hidden = false;
};
calWrap.addEventListener("mouseover", function (e) { const a = linkOf(e.target); if (a) show(a); });
calWrap.addEventListener("mouseout", function (e) { const a = linkOf(e.target); if (a && !a.contains(e.relatedTarget)) preview.hidden = true; });
calWrap.addEventListener("focusin", function (e) { const a = linkOf(e.target); if (a) show(a); });
calWrap.addEventListener("focusout", function (e) { if (linkOf(e.target)) preview.hidden = true; });
}
// ── 달력: 날짜별 광고비 ──
document.addEventListener("click", async function (e) {
const b = e.target.closest("button[data-spend]");
if (!b) return;
const value = await window.erpPrompt(tr("{day} 광고비 (RM) — 비우면 지웁니다").replace("{day}", b.dataset.spend), b.dataset.value || "", dialogText());
if (value === null || value === undefined) return;
const body = new FormData();
body.set("day", b.dataset.spend);
body.set("amount", value);
const r = await post("/live/ad-spend", body);
if (r.ok) reload(); else window.erpAlert(r.message, dialogText());
});
// ── 달력: 카드 머리를 끌어 빈 칸으로 옮기기, 다른 카드 위에 놓아 맞바꾸기 ──
let dragging = null;
calWrap.addEventListener("dragstart", function (e) {
const head = e.target.closest && e.target.closest(".lv-card-head");
if (!head) return;
dragging = head.closest("[data-card]").dataset.card;
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("text/plain", dragging);
});
calWrap.addEventListener("dragend", function () {
dragging = null;
calWrap.querySelectorAll(".is-drop").forEach(function (c) { c.classList.remove("is-drop"); });
});
calWrap.addEventListener("dragover", function (e) {
const cell = dragging && e.target.closest("[data-drop]");
if (!cell) return;
e.preventDefault();
calWrap.querySelectorAll(".is-drop").forEach(function (c) { if (c !== cell) c.classList.remove("is-drop"); });
cell.classList.add("is-drop");
});
calWrap.addEventListener("drop", async function (e) {
const cell = dragging && e.target.closest("[data-drop]");
if (!cell) return;
e.preventDefault();
const id = dragging;
const onto = e.target.closest("[data-card]");
if (onto && onto.dataset.card === id) return;
const body = new FormData();
if (onto) body.set("swap_with", onto.dataset.card);
else { body.set("broadcast_date", cell.dataset.day); body.set("start_time", cell.dataset.start); }
const r = await post("/live/broadcasts/" + id + "/move", body);
if (r.ok) reload(); else window.erpAlert(r.message, dialogText());
});
})();