class AgendamentoManager { constructor() { this.config = { isProd: !window.location.pathname.includes("agendamento-h"), fields: { all: [ "#email", "#matricula", "#nome", "#cpf", "#telefone", ".documentos", ], required: ["#email", "#matricula", "#nome", "#cpf", "#telefone"], }, serviceIds: { prod: { "Revisão de consumo": 36, "Alteração de titularidade": 35, Parcelamento: 37, }, dev: { "Revisão de consumo": 9, "Alteração de titularidade": 10, Parcelamento: 8, }, }, }; this.state = { updateEmail: false, selectedScheduleTime: null, selectedCalendarTime: null, selectedDay: null, selectedMonth: null, selectedYear: null, userId: null, isNewUser: false, isUpdatingData: false, userWithoutEmail: false, userData: null, updateButton: false, serviceError: false, scheduledDates: null, scheduleId: 1, }; this.initializeApp(); } initializeApp() { this.setupMasks(); this.setupEventListeners(); } setupMasks() { this.applyMask(document.querySelector("#telefone"), "(99) 99999-9999"); this.applyMask(document.querySelector("#cpf"), "999.999.999-99"); } applyMask(element, mask) { if (!element) return; element.addEventListener("input", (e) => { let value = e.target.value.replace(/\D/g, ""); let maskedValue = ""; let valueIndex = 0; for (let i = 0; i < mask.length && valueIndex < value.length; i++) { if (mask[i] === "9") { maskedValue += value[valueIndex]; valueIndex++; } else { maskedValue += mask[i]; } } e.target.value = maskedValue; }); } setupEventListeners() { const formFields = [ "#email", "#nome", "#cpf", "#telefone", "#matricula", "#servico", ]; formFields.forEach((field) => { const element = document.querySelector(field); if (element) { element.addEventListener("change", () => { this.validateFormFields(); }); } }); const emailField = document.querySelector("#email"); if (emailField) { emailField.addEventListener("change", async () => { await this.handleEmailChange(); }); } const emailConfField = document.querySelector("#emailConf"); if (emailConfField) { emailConfField.addEventListener("change", () => { if (document.querySelector("#email").value !== "") { document.querySelector("#btn-continuar").style.display = "block"; } }); } const serviceField = document.querySelector("#servico"); if (serviceField) { serviceField.options[0].disabled = true; serviceField.addEventListener("change", (e) => { this.handleServiceChange(e.target.value); }); } const correctDataBtn = document.querySelector("#btn-corrigeDados"); if (correctDataBtn) { correctDataBtn.addEventListener("click", async () => { await this.handleCorrectData(); }); } const continueBtn = document.querySelector("#btn-continuar"); if (continueBtn) { continueBtn.addEventListener("click", async () => { this.state.isUpdatingData = false; await this.handleContinue(); this.checkScheduledServices(this.state.userId); }); } const cpfField = document.querySelector("#cpf"); if (cpfField) { cpfField.addEventListener("blur", async (e) => { await this.validateCPF(e.target); }); } const phoneField = document.querySelector("#telefone"); if (phoneField) { phoneField.addEventListener("blur", (e) => { this.validatePhone(e.target); }); } } validateFormFields() { const email = document.querySelector("#email").value; const nome = document.querySelector("#nome").value; const cpf = document.querySelector("#cpf").value; const telefone = document.querySelector("#telefone").value; const matricula = document.querySelector("#matricula").value; const allFieldsFilled = email && nome && cpf && telefone && matricula; const canShowButton = allFieldsFilled && !this.state.updateEmail && !this.state.userWithoutEmail && !this.state.serviceError; document.querySelector("#btn-continuar").style.display = canShowButton ? "block" : "none"; } async checkScheduledServices(userId) { if (!userId) return; try { const response = await fetch(`/agendamentos-pessoa?id=${userId}`); const appointments = await response.json(); if (!appointments.length) return; this.scheduledDates = appointments; const agora = new Date(); const offset = -3; const dataGTM3 = new Date(agora.getTime() + offset * 60 * 60 * 1000); const dataAtualISO = dataGTM3.toISOString().replace("Z", "-03:00"); const selectedService = document.querySelector("#servico").value; const existingAppointment = appointments.find( (item) => item.tituloAgendamento.toLowerCase() === selectedService.toLowerCase() && item.dataFimEvento >= dataAtualISO, ); if (existingAppointment) { this.state.serviceError = true; this.showAlert( "Já existe um agendamento ativo para o serviço e CPF informado", ); document.querySelector("#btn-continuar").style.display = "none"; this.resetCPFRules(); return; } else { this.state.serviceError = false; document.querySelector("#btn-continuar").style.display = "block"; } } catch (error) { console.error("Erro ao verificar serviços agendados:", error); } } async handleEmailChange() { const email = this.validateAndClearEmail("email"); if (email === null || email === "") { this.showAlert("Digite um email!"); return; } if ( document.querySelector("#email").value === "" || this.state.updateButton ) { try { const response = await fetch("/api/v1/get-usuario", { method: "POST", headers: { "Content-Type": "application/json", prod: Boolean(this.config.isProd), }, body: JSON.stringify({ email }), }); if (response.ok) { const data = await response.json(); if (Object.keys(data).length > 0) { document.querySelector("#email").value = ""; this.showAlert( "E-mail já cadastrado para outro usuário, favor insira um e-mail diferente.", ); document.querySelector("#btn-continuar").style.display = "none"; } else { if (this.state.userWithoutEmail) { document.querySelector("#btn-continuar").style.display = "none"; } else { document.querySelector("#btn-continuar").style.display = "block"; } } } } catch (error) { console.error("Erro ao verificar email:", error); } } if (document.querySelector("#emailConf").value !== "") { document.querySelector("#btn-continuar").style.display = "block"; } } async handleCorrectData() { this.state.updateEmail = true; if (!this.state.userWithoutEmail) { document.querySelector("#email").value = ""; } this.state.isUpdatingData = true; this.state.updateButton = true; document.querySelector("#btn-corrigeDados").style.display = "none"; document.querySelector("#btn-continuar").style.display = "none"; document.querySelector("#emailConfirm").classList.remove("hide"); document.querySelector("#email").removeAttribute("readonly"); document.querySelector("#email").style.backgroundColor = "#fff"; } async handleContinue() { const emptyFields = this.config.fields.required.filter( (field) => document.querySelector(field).value === "", ); if (emptyFields.length > 0) { const fieldLabel = document .querySelector(emptyFields[0]) .parentElement.querySelector("label") .textContent.split(":")[0]; this.showAlert(`Preencha o campo: ${fieldLabel}`); return; } const phoneData = this.buildPhoneData(); if (!this.state.isUpdatingData && !this.state.isNewUser) { await this.updateContact(phoneData); this.showSuccessModal(); } if (this.state.isUpdatingData || this.state.updateEmail) { await this.handleDataUpdate(phoneData); } if (this.state.isNewUser) { await this.handleNewUserRegistration(); } } buildPhoneData() { const phoneValue = document.querySelector("#telefone").value; return { idUsuario: this.state.userId, telefone: [ { tipo: "CELULAR", ddd: phoneValue.substring(1, 3), numero: phoneValue.substring(5).replace(/\D/g, ""), sms: true, preferencial: false, }, ], }; } async updateContact(phoneData) { try { const response = await fetch("/api/v1/atualiza-contato", { method: "POST", headers: { "Content-Type": "application/json", prod: Boolean(this.config.isProd), }, body: JSON.stringify({ dadosPessoaCadastro: phoneData }), }); if (response.ok) { let data = await response.json(); this.state.userId = data.id; } } catch (error) { console.error("Erro ao atualizar contato:", error); } } async handleDataUpdate(phoneData) { const newEmailConfirmation = document .querySelector("#emailConf") .value.trim(); const typedEmail = document.querySelector("#email").value.trim(); if (!newEmailConfirmation || !typedEmail) { this.showAlert("Preencha os dois campos de email para prosseguir!"); return; } if (typedEmail !== newEmailConfirmation) { this.showAlert("Os e-mails não são iguais. Favor informar novamente."); return; } const updateData = { ...phoneData, cpf: document.querySelector("#cpf").value, nome: document.querySelector("#nome").value, email: newEmailConfirmation, method: "PUT", }; try { const response = await fetch("/api/v1/cadastro-usuario", { method: "POST", headers: { "Content-Type": "application/json", prod: Boolean(this.config.isProd), }, body: JSON.stringify({ dadosPessoaCadastro: updateData }), }); if (response.ok) { this.state.userId = updateData.idUsuario; this.showSuccessModal(); } } catch (error) { console.error("Erro ao atualizar dados:", error); } } async handleNewUserRegistration() { const newEmailConfirmation = document .querySelector("#emailConf") .value.trim(); const typedEmail = document.querySelector("#email").value.trim(); if (newEmailConfirmation !== typedEmail) { this.showAlert("Os e-mails não são iguais. Favor informar novamente."); return; } const newUserData = { cpf: document.querySelector("#cpf").value, nome: document.querySelector("#nome").value, email: document.querySelector("#email").value, telefone: document.querySelector("#telefone").value, method: "POST", }; try { const response = await fetch("/api/v1/cadastro-usuario", { method: "POST", headers: { "Content-Type": "application/json", prod: Boolean(this.config.isProd), }, body: JSON.stringify({ dadosPessoaCadastro: newUserData }), }); if (response.ok) { this.state.userId = await response.json(); this.showSuccessModal(); } } catch (error) { console.error("Erro ao cadastrar usuário:", error); } } showFields() { this.config.fields.all.forEach((field) => { const element = document.querySelector(field); if (element) { element.classList.remove("hide"); element.parentElement?.classList.remove("hide"); element.parentElement?.parentElement?.classList.remove("hide"); } }); } hideFields() { this.config.fields.all.forEach((field) => { const element = document.querySelector(field); if (element) { element.classList.add("hide"); element.parentElement?.classList.add("hide"); element.parentElement?.parentElement?.classList.add("hide"); } }); const servicoElement = document.querySelector("#servico"); if (servicoElement) { servicoElement.parentElement.parentElement.parentElement.classList.remove( "hide", ); servicoElement.parentElement.parentElement.classList.remove("hide"); } } handleServiceChange(serviceValue) { if (!serviceValue) return; this.config.fields.all.forEach((field) => { const element = document.querySelector(field); if (element) { element.value = ""; } }); this.hideFields(); document.querySelector("#btn-corrigeDados").style.display = "none"; this.showFields(); this.setDocumentationLinks(serviceValue); const cpfInput = document.querySelector("input#cpf"); if (typeof this.state.userId === "object") { if (this.state.userId == null) return; if (!this.state.userId.id) return; this.state.userId = this.state.userId.id; } cpfInput.value ? this.checkScheduledServices(this.state.userId) : null; } setDocumentationLinks(service) { const links = { "Revisão de consumo": "https://atendimentovirtual.embasa.ba.gov.br/carta-verificar-consumo", Parcelamento: "https://atendimentovirtual.embasa.ba.gov.br/carta-simular-parcelamento", "Alteração de titularidade": "https://atendimentovirtual.embasa.ba.gov.br/carta-de-servico-alteracao-de-titularidade", }; const anchor = document.querySelector("#documentos-button-anchor"); if (anchor && links[service]) { anchor.href = links[service]; } } showSchedulingModal() { setTimeout(() => { this.setupDateChangeHandler(); this.setupDateBlurHandler(); }, 2000); const phone = document.querySelector("#telefone").value ? document.querySelector("#telefone").value : ""; Swal.fire({ title: "Conclua o seu agendamento:", html: this.getSchedulingModalHTML(), confirmButtonColor: "rgb(14, 67, 241)", showCancelButton: true, confirmButtonText: '', cancelButtonText: "Cancelar", }).then((result) => { if (result.isConfirmed) { this.showConfirmationModal(); setTimeout(() => { this.makeAppointment( this.state.selectedDay, this.state.selectedMonth, this.state.selectedYear, this.state.selectedScheduleTime, phone, ); //window.location.reload(); }, 5000); } }); this.setMinMaxDates(); this.setupTimeCheckHandler(); const confirmBtns = document.querySelectorAll(".swal2-confirm"); confirmBtns.forEach((btn) => (btn.style.display = "none")); } getSchedulingModalHTML() { return `

`; } setupDateChangeHandler() { const agendamentoField = document.querySelector("#agendamento"); if (agendamentoField) { agendamentoField.addEventListener("change", () => { const confirmBtns = document.querySelectorAll(".swal2-confirm"); confirmBtns.forEach((btn) => (btn.style.display = "none")); const dataText = document.querySelector("#data-text"); if (dataText) { dataText.textContent = ``; } const horariosElement = document.querySelector("#horariosDisponiveis"); if (horariosElement) { horariosElement.innerHTML = ""; } if (!agendamentoField.value) return; this.state.selectedCalendarTime = agendamentoField.value; const [year, month, day] = this.state.selectedCalendarTime.split("-"); this.state.selectedDay = day; this.state.selectedMonth = month; this.state.selectedYear = year; document .querySelector("#verifica-horarios") .dispatchEvent(new Event("click")); }); } } setupDateBlurHandler() { const agendamentoField = document.querySelector("#agendamento"); if (!agendamentoField.value) return; if (agendamentoField) { agendamentoField.addEventListener("blur", () => { this.state.selectedCalendarTime = agendamentoField.value; const selectedDate = new Date(this.state.selectedCalendarTime).getDay(); if (selectedDate === 5 || selectedDate === 6) { agendamentoField.value = ""; this.showAlert( "Você selecionou um dia do final de semana, onde não há atendimento. Favor selecionar outra data.", ); } }); } } setupTimeCheckHandler() { document.addEventListener("click", (e) => { if (e.target.id === "verifica-horarios") { e.preventDefault(); const agendamentoField = document.querySelector("#agendamento"); if (!agendamentoField.value) return; if (agendamentoField) { this.state.selectedCalendarTime = agendamentoField.value; } const [year, month, day] = this.state.selectedCalendarTime.split("-"); this.state.selectedDay = day; this.state.selectedMonth = month; this.state.selectedYear = year; const horariosElement = document.querySelector("#horariosDisponiveis"); if (horariosElement) { horariosElement.innerHTML = ""; } setInterval(() => { const radioButtons = document.querySelectorAll('input[type="radio"]'); radioButtons.forEach((radio) => { radio.addEventListener("change", (e) => { this.state.selectedScheduleTime = e.target.value; }); }); }, 500); this.checkAvailableTimes(); } }); } showConfirmationModal() { Swal.fire({ html: `

Agendamento confirmado!

Em breve você receberá um e-mail de confirmação.
O link e a senha de acesso serão enviados 15 minutos antes do horário, ou se preferir, acesse diretamente essas informações na opção: Consultar Agendamento.

Atendimento Virtual da Embasa
`, customClass: { htmlContainer: "no-padding-html" }, showCancelButton: false, showConfirmButton: false, }); } watchInputChange() { const confirmBtns = document.querySelectorAll(".swal2-confirm"); confirmBtns.forEach((btn) => (btn.style.display = "none")); setTimeout(() => { const hrElements = document.querySelectorAll( "#horariosDisponiveis .hrDisponiveis", ); hrElements.forEach((element) => { element.addEventListener("click", (e) => { const confirmBtns = document.querySelectorAll(".swal2-confirm"); if (e.target.classList[1] === "false") { confirmBtns.forEach((btn) => (btn.style.display = "none")); } if (e.target.classList[1] === "true") { confirmBtns.forEach((btn) => (btn.style.display = "block")); } }); }); }, 1000); } setMinMaxDates() { const today = new Date(); const year = today.getFullYear(); const month = (today.getUTCMonth() + 1).toString().padStart(2, "0"); const day = today.getDate().toString().padStart(2, "0"); let minutes = today.getMinutes(); if (minutes >= 0 && minutes <= 29) { minutes = 30; } else { minutes = 0; } const todayString = `${year}-${month}-${day}`; const agendamentoField = document.querySelector("#agendamento"); if (agendamentoField) { agendamentoField.setAttribute("value", todayString); agendamentoField.setAttribute("min", todayString); const next30Days = new Date(today.setDate(today.getDate() + 30)); const maxYear = next30Days.getFullYear(); const maxMonth = (next30Days.getUTCMonth() + 1) .toString() .padStart(2, "0"); const maxDay = next30Days.getDate().toString().padStart(2, "0"); const maxString = `${maxYear}-${maxMonth}-${maxDay}`; agendamentoField.setAttribute("max", maxString); } } async checkAvailableTimes() { const agendamentoField = document.querySelector("#agendamento"); const selectedDate = agendamentoField ? agendamentoField.value : ""; const selectedService = document.querySelector("#servico").value; const appointmentTypeId = this.getAppointmentTypeId(selectedService); if (!appointmentTypeId) { this.showAlert("Serviço não encontrado"); return; } try { const response = await fetch("/getAgendas", { method: "POST", headers: { prod: Boolean(this.config.isProd) }, body: JSON.stringify({ data: selectedDate, horario: "16:30:00", agenda: this.state.scheduleId, }), }); const data = await response.json(); this.renderAvailableTimes(data[0].horaAgenda, selectedDate); } catch (error) { const dataText = document.querySelector("#data-text"); if (dataText) { const confirmBtns = document.querySelectorAll(".swal2-confirm"); confirmBtns.forEach((btn) => (btn.style.display = "none")); dataText.textContent = `Não temos horários disponíveis para ${selectedDate.split("-").reverse().join("/")}`; return; } console.error("Erro ao consultar horários:", error); } this.watchInputChange(); } getAppointmentTypeId(service) { const serviceIds = this.config.isProd ? this.config.serviceIds.prod : this.config.serviceIds.dev; return serviceIds[service]; } renderAvailableTimes(timeSlots, selectedDate) { const container = document.querySelector("#horariosDisponiveis"); console.log(selectedDate); const [year, month, day] = selectedDate.split("-"); const dataText = document.querySelector("#data-text"); if (dataText) { dataText.textContent = `Esses são os horários disponíveis para ${day}/${month}/${year}`; } let scheduledInThisDate; if (this.scheduledDates) { scheduledInThisDate = this.scheduledDates.map((item) => { if (item.dataInicioEvento.includes(selectedDate)) { return item.dataInicioEvento.split("T")[1]; } }); timeSlots = timeSlots.map((item) => { if (scheduledInThisDate.includes(item.hora)) { return { ...item, disponivel: false }; } return { ...item }; }); } if (timeSlots.filter((item) => item.disponivel).length == 0) { if (dataText) { dataText.textContent = `Não temos horários disponíveis para ${day}/${month}/${year}`; return; } } timeSlots.forEach((slot) => { const li = document.createElement("li"); const isAvailable = slot.disponivel; li.innerHTML = `
  • `; if (container && isAvailable) { container.appendChild(li); } }); setTimeout(() => { const radioButtons = document.querySelectorAll('input[type="radio"]'); radioButtons.forEach((radio) => { radio.addEventListener("change", (e) => { console.log(e.target.value); this.state.selectedScheduleTime = e.target.value; const confirmBtns = document.querySelectorAll(".swal2-confirm"); confirmBtns.forEach((btn) => (btn.style.display = "block")); }); }); }, 1000); } async makeAppointment(day, month, year, time, phone) { const selectedService = document.querySelector("#servico").value; if (!selectedService) return; const appointmentTypeId = this.getAppointmentTypeId(selectedService); if (!appointmentTypeId) { this.showAlert("Serviço não encontrado"); return; } console.log(this.state); if (typeof this.state.userId === "object") { this.state.userId = this.state.userId.id; } try { await fetch("/setAgendamento", { method: "POST", headers: { prod: Boolean(this.config.isProd) }, body: JSON.stringify({ idAgenda: this.state.scheduleId, idPessoaEvento: this.state.userId, isReagendamento: false, idAgendamentoAntigo: null, idRegistroFormulario: "", data: `${day}/${month}/${year}`, horario: time, perfilAtendimento: 0, idTipoAgendamento: appointmentTypeId, registro: { ip_telefone_agendamento: phone, }, }), }); setTimeout(() => { window.location.href = window.location.href; }, 7000); } catch (error) { console.error("Erro ao fazer agendamento:", error); } } clearField(fieldId) { const field = document.querySelector(`#${fieldId}`); if (field) { field.value = ""; } } resetCPFRules() { const btnCorrigeDados = document.querySelector("#btn-corrigeDados"); const emailConfirm = document.querySelector("#emailConfirm"); const emailField = document.querySelector("#email"); if (btnCorrigeDados) btnCorrigeDados.style.display = "none"; if (emailConfirm) emailConfirm.classList.add("hide"); if (emailField) { emailField.removeAttribute("readonly"); emailField.style.backgroundColor = "#fff"; } } async validateCPF(cpfInput) { let cpf = cpfInput.value.replace(/[^\d]/g, ""); if (!cpf) return; if (cpf.length !== 11 || /^(\d)\1+$/.test(cpf)) { this.showInvalidCPFAlert(); this.clearCPFRelatedFields(); this.resetCPFRules(); return (cpfInput.value = ""); } if (!this.isValidCPFChecksum(cpf)) { this.showInvalidCPFAlert(); this.clearCPFRelatedFields(); this.resetCPFRules(); return (cpfInput.value = ""); } await this.checkUserByCPF(cpf); } isValidCPFChecksum(cpf) { let sum = 0; for (let i = 0; i < 9; i++) { sum += parseInt(cpf.charAt(i)) * (10 - i); } let firstVerifier = 11 - (sum % 11); if (firstVerifier > 9) firstVerifier = 0; if (parseInt(cpf.charAt(9)) !== firstVerifier) return false; sum = 0; for (let i = 0; i < 10; i++) { sum += parseInt(cpf.charAt(i)) * (11 - i); } let secondVerifier = 11 - (sum % 11); if (secondVerifier > 9) secondVerifier = 0; return parseInt(cpf.charAt(10)) === secondVerifier; } showInvalidCPFAlert() { this.showAlert( "O CPF fornecido é inválido. Digite um válido para prosseguir!", ); } clearCPFRelatedFields() { setTimeout(() => { ["email", "telefone", "emailConfirm", "cpf"].forEach((field) => { this.clearField(field); }); }, 200); } async checkUserByCPF(cpf) { try { const response = await fetch("/api/v1/get-usuario", { method: "POST", headers: { "Content-Type": "application/json", prod: Boolean(this.config.isProd), }, body: JSON.stringify({ cpf }), }); if (response.ok) { const data = await response.json(); await this.checkScheduledServices(data.id); if (Object.keys(data).length > 0) { this.handleExistingUser(data); } else { this.handleNewUser(); } } else if (response.status === 404) { this.handleUserNotFound(); } } catch (error) { console.error("Erro ao verificar CPF:", error); } } handleExistingUser(userData) { this.state.isNewUser = false; this.state.updateButton = false; const emailConfirm = document.querySelector("#emailConfirm"); if (emailConfirm) emailConfirm.classList.add("hide"); this.state.userData = { id: userData.id, nome: userData.nome, email: userData.email, telefone: userData.telefones?.length > 0 ? `(${userData.telefones[0].ddd}) ${userData.telefones[0].numero}` : "", }; this.state.userId = this.state.userData.id; const emailField = document.querySelector("#email"); const btnCorrigeDados = document.querySelector("#btn-corrigeDados"); if (!userData.email) { this.state.userWithoutEmail = true; this.state.updateButton = true; } else { this.state.userWithoutEmail = false; if (emailField) { emailField.value = this.formatEmail(userData.email) || ""; emailField.setAttribute("readonly", true); emailField.style.backgroundColor = "#D3D3D3"; } } if (btnCorrigeDados) btnCorrigeDados.style.display = "block"; } handleNewUser() { this.state.isNewUser = true; this.state.updateButton = true; const emailField = document.querySelector("#email"); const emailConfirm = document.querySelector("#emailConfirm"); const emailConf = document.querySelector("#emailConf"); const btnCorrigeDados = document.querySelector("#btn-corrigeDados"); if (emailField) { emailField.removeAttribute("readonly"); emailField.style.backgroundColor = "#fff"; emailField.value = ""; } if (emailConfirm) emailConfirm.classList.remove("hide"); if (emailConf) emailConf.value = ""; if (btnCorrigeDados) btnCorrigeDados.style.display = "none"; } handleUserNotFound() { const emailField = document.querySelector("#email"); if (emailField) { emailField.removeAttribute("readonly"); emailField.style.backgroundColor = "#fff"; } } validateAndClearEmail(inputId) { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; const inputField = document.querySelector(`#${inputId}`); const email = inputField ? inputField.value.trim() : ""; if (!emailRegex.test(email)) { if (!email) return; this.showAlert("E-mail inválido!"); if (inputField) inputField.value = ""; const btnContinuar = document.querySelector("#btn-continuar"); if (btnContinuar) btnContinuar.style.display = "none"; return null; } return email; } formatEmail(email) { if (!email) return; if (!email || !email.includes("@")) return email; const [localPart, domain] = email.split("@"); if (localPart.length <= 3) { return `${localPart}@${domain}`; } const start = localPart.slice(0, 2); const end = localPart.slice(-1); const hidden = "*".repeat(localPart.length - 3); return `${start}${hidden}${end}@${domain}`; } showSuccessModal() { Swal.fire({ title: "Cadastro realizado com sucesso!", text: "Todos os dados pessoais coletados neste formulário são os estritamente necessários para a prestação do serviço e poderão ser compartilhados com as empresas terceirizadas que prestam serviços para a Embasa, tendo como base legal, o art. 7° da Lei Federal n° 13.709/2018.", showCancelButton: false, confirmButtonText: "OK", }).then((result) => { if (result.isConfirmed) { this.showSchedulingModal(); } else if (result.dismiss === Swal.DismissReason.cancel) { this.showAlert( "Não é possível realizar agendamento sem atualizar os dados.", ); } }); } validatePhone(phoneInput) { if (!phoneInput.value) return; const cleaned = phoneInput.value.replace(/[^0-9]/g, ""); const repeatedValues = [ "00000000000", "11111111111", "22222222222", "33333333333", "44444444444", "55555555555", "66666666666", "77777777777", "88888888888", "99999999999", ]; if ( cleaned.length < 10 || cleaned.length > 11 || repeatedValues.includes(cleaned) ) { this.showAlert("Número de telefone inválido."); const btnContinuar = document.querySelector("#btn-continuar"); if (btnContinuar) btnContinuar.style.display = "none"; return (phoneInput.value = ""); } return cleaned; } showAlert(message) { return Swal.fire({ title: "Atenção", text: message, confirmButtonText: "OK", }); } } const agendamentoManager = new AgendamentoManager();