// ========================= / ========================= (function () { // 브라우저 환경이 아니거나 이미 등록된 경우 중단 if ( typeof window === "undefined" || customElements.get("vending-lead-form") ) { return; } // 기본 문의 API const DEFAULT_LEAD_API_URL = "https://api.bunshin.kr/vending/homepage-leads"; // 현재 시각을 한국 표준시(UTC+9)의 YYYY-MM-DD 형식으로 변환 function getKoreaDateString(date = new Date()) { const KOREA_TIME_OFFSET_MS = 9 * 60 * 60 * 1000; return new Date(date.getTime() + KOREA_TIME_OFFSET_MS) .toISOString() .slice(0, 10); } class VendingLeadForm extends HTMLElement { async connectedCallback() { if (this.__rendered) return; this.__rendered = true; // 런타임 설정 준비 await (window.VendingRuntime?.ready ?? Promise.resolve()); const config = this.getLeadConfig(); const source = this.getAttribute("data-source") || "default"; const today = getKoreaDateString(); // 폼 렌더링 this.innerHTML = `

방문예약 상담문의

상담을 남겨주시면 담당자가 확인 후 안내드립니다.

`; this.bindForm(config); } // 문의 설정 가져오기 getLeadConfig() { const base = window.VendingConfig?.lead || {}; const runtimeLead = this.readRuntimeLeadConfig(); return { ...base, ...runtimeLead }; } // 런타임 문의 설정 읽기 readRuntimeLeadConfig() { try { const value = window.VendingRuntime?.value?.("lead", null); return value && typeof value === "object" ? value : {}; } catch (error) { return {}; } } // 이벤트 바인딩 bindForm(config) { const form = this.querySelector(".vending-inquiry-form"); const feedback = this.querySelector(".form-feedback"); const submitButton = this.querySelector(".form-submit"); const phoneInput = this.querySelector('input[name="phone"]'); const privacyModal = this.querySelector(".privacy-modal-wrap"); const successModal = this.querySelector(".submit-success-modal"); const privacyLink = this.querySelector(".privacy-link"); const privacyClose = this.querySelector(".privacy-modal-close"); const successClose = this.querySelector(".submit-success-modal__close"); // 모달 이벤트 privacyLink?.addEventListener("click", () => this.openModal(privacyModal), ); privacyClose?.addEventListener("click", () => this.closeModal(privacyModal), ); successClose?.addEventListener("click", () => this.closeModal(successModal), ); privacyModal?.addEventListener("click", (event) => { if (event.target === privacyModal) this.closeModal(privacyModal); }); successModal?.addEventListener("click", (event) => { if (event.target === successModal) this.closeModal(successModal); }); // 연락처 자동 포맷 phoneInput?.addEventListener("input", () => { phoneInput.value = this.formatPhone(phoneInput.value); }); // 폼 제출 form?.addEventListener("submit", async (event) => { event.preventDefault(); if (!form || !feedback || !submitButton) return; const formData = new FormData(form); const payload = { publicFormKey: this.readText(config.publicFormKey), name: this.readText(formData.get("name")), phone: this.normalizePhone(formData.get("phone")), visitDate: this.readText(formData.get("visitDate")), visitTime: this.readText(formData.get("visitTime")), privacyAgreed: formData.get("privacyAgreed") === "on", note: [ this.readText(formData.get("note")), form.dataset.source ? `유입위치: ${form.dataset.source}` : "", ] .filter(Boolean) .join("\n"), homepageUrl: window.location.href, honeypot: this.readText(formData.get("company")), }; const validationMessage = this.validatePayload(payload); if (validationMessage) { this.setFeedback(feedback, "error", validationMessage); return; } submitButton.disabled = true; this.setFeedback(feedback, "", ""); try { const response = await fetch( this.readText(config.apiUrl) || DEFAULT_LEAD_API_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }, ); if (!response.ok) throw new Error("request_failed"); form.reset(); this.openModal(successModal); } catch (error) { console.error("[VendingLead] 문의 접수 실패", error); this.setFeedback( feedback, "error", this.readText(config.failureMessage) || "문의 접수에 실패했습니다. 잠시 후 다시 시도해 주세요.", ); } finally { submitButton.disabled = false; } }); } // 필수값 검증 validatePayload(payload) { if (!payload.publicFormKey) return "문의 설정이 없습니다."; if (!payload.name) return "성함을 입력해 주세요."; if (!payload.phone) return "연락처를 입력해 주세요."; if (!payload.visitDate) return "방문예정일을 선택해 주세요."; if (!payload.privacyAgreed) return "개인정보 수집 및 이용에 동의해 주세요."; return ""; } // 문자열 정리 readText(value) { if (typeof value !== "string") return ""; return value.trim(); } // 숫자 연락처 변환 normalizePhone(value) { return this.readText(value).replace(/\D/g, ""); } // 연락처 하이픈 처리 formatPhone(value) { const digits = this.normalizePhone(value).slice(0, 11); if (digits.length < 4) return digits; if (digits.length < 8) return `${digits.slice(0, 3)}-${digits.slice(3)}`; return `${digits.slice(0, 3)}-${digits.slice(3, 7)}-${digits.slice(7)}`; } // 피드백 표시 setFeedback(target, state, message) { target.dataset.state = state; target.textContent = message; } // 모달 열기 openModal(modal) { if (!modal) return; // 원래 위치를 기억한 뒤 body의 마지막 자식으로 옮겨 최상단에 표시 if (modal.parentElement !== document.body) { modal.__originalParent = modal.parentElement; } document.body.appendChild(modal); modal.style.setProperty("position", "fixed", "important"); modal.style.setProperty("z-index", "2147483647", "important"); modal.classList.add("open"); modal.setAttribute("aria-hidden", "false"); document.body.style.overflow = "hidden"; } // 모달 닫기 closeModal(modal) { if (!modal) return; modal.classList.remove("open"); modal.setAttribute("aria-hidden", "true"); modal.style.removeProperty("position"); modal.style.removeProperty("z-index"); // 원래 문의 폼 위치로 복귀 if (modal.__originalParent?.isConnected) { modal.__originalParent.appendChild(modal); } const anotherModalIsOpen = document.querySelector( ".privacy-modal-wrap.open, .submit-success-modal.open", ); if (!anotherModalIsOpen) document.body.style.overflow = ""; } // HTML 속성 이스케이프 escapeAttribute(value) { return String(value) .replace(/&/g, "&") .replace(/"/g, """) .replace(/