/* 라이브 커머스(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); recalc(); dlg.showModal(); } // Fee(시간 × 시간당 요금)·커미션(판매금액 × %) 자동 계산 — 보기만(저장 안 함), store.session_pay 와 같게 센트 반올림 const feeOut = form.querySelector("[data-fee]"); const comOut = form.querySelector("[data-commission]"); function money(cents) { return (cents / 100).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 }); } function minutesOf(v) { const m = /^(\d{1,2}):(\d{2})/.exec(v || ""); return m ? Number(m[1]) * 60 + Number(m[2]) : null; } function recalc() { if (!feeOut || !comOut) return; const s = minutesOf(form.elements.start_time.value), en = minutesOf(form.elements.end_time.value); const mins = s === null || en === null || s === en ? null : (en - s + 1440) % 1440; // 끝이 더 이르면 자정을 넘긴 방송 feeOut.value = mins === null ? "" : money(Math.round(mins * Number(feeOut.dataset.fee) * 100 / 60)); const sales = Number(String(form.elements.sales_amount.value).replace(/^\s*rm/i, "").replace(/[,\s]/g, "")); const raw = form.elements.sales_amount.value.trim(); comOut.value = !raw || !isFinite(sales) || sales < 0 ? "" : money(Math.round(Math.round(sales * 100) * Number(comOut.dataset.commission) / 100)); } form.addEventListener("input", function (e) { if (["start_time", "end_time", "sales_amount"].indexOf(e.target.name) >= 0) recalc(); }); 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; recalc(); } 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; }); } // ── 달력: 이미지 링크를 누르면 화면 가운데 보기 창 — 원본 크기, 회전(보기만, 90°씩), 다운로드(원본), 여러 장이면 앞뒤 ── const viewer = document.getElementById("lv-viewer"); if (viewer) { const vImg = viewer.querySelector("img"), stage = viewer.querySelector(".lv-viewer-stage"); const vCap = viewer.querySelector(".lv-viewer-cap"), vCount = viewer.querySelector(".lv-viewer-count"); const dl = viewer.querySelector("[data-download]"), steps = viewer.querySelectorAll("[data-step]"); let ids = [], names = [], at = 0, turn = 0; const place = function () { const w = vImg.naturalWidth, h = vImg.naturalHeight, side = turn % 2 === 1; stage.style.width = (side ? h : w) + "px"; stage.style.height = (side ? w : h) + "px"; vImg.style.transform = "translate(-50%, -50%) rotate(" + turn * 90 + "deg)"; }; const load = function () { turn = 0; vImg.src = dl.href = "/live/images/" + ids[at]; dl.download = names[at] || "image-" + ids[at]; vCount.textContent = ids.length > 1 ? at + 1 + " / " + ids.length : ""; steps.forEach(function (b) { b.hidden = ids.length < 2; }); }; vImg.addEventListener("load", place); calWrap.addEventListener("click", function (e) { const a = e.target.closest("a[data-images]"); if (!a || e.ctrlKey || e.metaKey || e.shiftKey || e.button) return; // Ctrl·가운데 클릭 = 예전처럼 새 탭 e.preventDefault(); ids = JSON.parse(a.dataset.images); names = JSON.parse(a.dataset.names || "[]"); at = 0; vCap.textContent = a.dataset.preview.replace(/ · \d+\/\d+$/, ""); vImg.alt = a.title; load(); if (preview) preview.hidden = true; viewer.showModal(); }); viewer.addEventListener("click", function (e) { if (e.target === viewer || e.target.closest("[data-viewer-close]")) { viewer.close(); return; } // 바깥(배경) = 닫기 const step = e.target.closest("[data-step]"); if (step) { at = (at + Number(step.dataset.step) + ids.length) % ids.length; load(); return; } if (e.target.closest("[data-rotate]")) { turn = (turn + 1) % 4; place(); } }); } // ── 달력: 카드 머리를 끌어 빈 칸으로 옮기기, 다른 카드 위에 놓아 맞바꾸기 ── 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()); }); })();