var scriptObject42 = document.currentScript; var paramsObject42 = (scriptObject42.getAttribute('data-params') || '').split(/, */); var tokenObject42 = ''; var noCssObject42 = null; //params[4]; const backendUrlObject42 = 'https://app.contrall.app:843/api/admin/dynamic-forms-links/'; const frontendUrlObject42 = 'https://app.contrall.app/'; /*const backendUrlObject42 = 'http://localhost:6969/api/admin/dynamic-forms-links/'; const frontendUrlObject42 = 'http://localhost:4200/';*/ // Get HTML head element var headObject42 = document.getElementsByTagName('HEAD')[0]; //console.log(head); const keyObject42 = paramsObject42[0]; const elementIdObject42 = paramsObject42[1]; const formIdObject42 = paramsObject42[2]; const darkBackgroundObject42 = (paramsObject42[3] ?? '').trim(); if (noCssObject42 != 'noCss') { var linkbObject42 = document.createElement('link'); linkbObject42.rel = 'stylesheet'; linkbObject42.type = 'text/css'; linkbObject42.href = 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'; //linkb.integrity = "sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"; //linkb.href = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'; linkbObject42.crossorigin = 'anonymous'; headObject42.appendChild(linkbObject42); // Create new link Element var linkObject42 = document.createElement('link'); // set the attributes for link element linkObject42.rel = 'stylesheet'; linkObject42.type = 'text/css'; linkObject42.href = frontendUrlObject42 + 'assets/scripts/forms' + (darkBackgroundObject42.trim() === '_dark_background' ? darkBackgroundObject42 : '') + '.css'; //console.log(linkObject42.href); // Append link element to HTML head headObject42.appendChild(linkObject42); } var initialElement42 = document.getElementById(elementIdObject42); var emailObject42 = null; var phoneObject42 = null; var hasValidation42 = 0; //0 = doesn't have validation, 1 = email validation, 2 = phone validation var requestedConfirmation42 = false; var filesArray42 = []; var formData42 = null; var confirmationKey42 = null; var confirmationCode42 = null; var refreshForm42 = false; var submitButton42 = null; var originalOptions42 = { method: 'GET', headers: { //"Content-Type": "application/json", //authentication: "key=" + key, //formId: formId, //token: token }, //mode: 'no-cors' }; if (tokenObject42 !== undefined && tokenObject42 !== '') { originalOptions42.headers.Token = tokenObject42; } fetch(backendUrlObject42 + 'getform/' + formIdObject42 + '/' + keyObject42, originalOptions42) .then(response => response.text()) .then(jsonResponse => { //console.log("Data", jsonResponse); loadFunction42(jsonResponse ? JSON.parse(jsonResponse) : {}); }) .catch(err => { console.log(err); }); function loadFunction42(data) { var controls = []; if (requestedConfirmation42 == false) { if (data.hasEmailValidation) { hasValidation42 = 1; } else { if (data.hasPhoneValidation) { hasValidation42 = 2; } else { hasValidation42 = 0; } } } //console.log(hasValidation42); var container = document.createElement('div'); container.setAttribute('class', 'div-container' + darkBackgroundObject42); container.setAttribute('style', data.style); initialElement42.append(container); var containerTitle = document.createElement('div'); containerTitle.setAttribute('class', ''); var title = document.createElement('h1'); title.setAttribute('class', 'h1_class' + darkBackgroundObject42); title.innerHTML = data.title; if (data.hideTitle !== true) containerTitle.append(title); var subTitle = document.createElement('h3'); subTitle.setAttribute('class', 'h3_class' + darkBackgroundObject42); subTitle.innerHTML = data.header; containerTitle.append(subTitle); container.append(containerTitle); var containerForm = document.createElement('div'); containerForm.setAttribute('class', ''); data.rows.forEach((rowData, i) => { var row = document.createElement('div'); row.setAttribute('id', rowData.id); if (rowData.cssClass != null) row.setAttribute('class', rowData.cssClass); if (rowData.style != null) row.setAttribute('style', rowData.style); if (rowData.formRequestId != null) row.setAttribute('formRequestId', rowData.formRequestId); rowData.columns.forEach((column, i) => { var containerData = column; var containerForm = document.createElement(containerData.htmlTag); if (containerData.id != null) containerForm.setAttribute('id', containerData.id); if (containerData.cssClass != null) containerForm.setAttribute('class', containerData.cssClass); if (containerData.sectionId != null) containerForm.setAttribute('sectionId', containerData.sectionId); // var inputLabelContainer = document.createElementFunction42('div'); // inputLabelContainer.setAttribute('class', 'input-label-container'); //containerForm.append(inputLabelContainer); var labelData = containerData.label; var label = document.createElement('label'); if (labelData.labelFor != null) label.setAttribute('for', labelData.labelFor); if (labelData.style != null) label.setAttribute('style', labelData.style); if (!labelData.hidden === true && labelData.text != null) { label.innerHTML = labelData.text; if (containerData.control.required === true) { label.setAttribute('class', 'red-star ' + 'label_class' + darkBackgroundObject42); } else { label.setAttribute('class', 'label_class' + darkBackgroundObject42) } if (labelData.cssClass != null) { label.setAttribute('class', label.getAttribute('class') + ' ' + labelData.cssClass); } } else { label.innerHTML = ' '; } //inputLabelContainer.append(label); containerForm.append(label); var controlData = containerData.control; controlData['label'] = labelData.text; controls.push(controlData); var control = createElementFunction42(controlData); if (controlData.id != null) control.setAttribute('id', controlData.id); if (controlData.cssClass != null) control.setAttribute('class', controlData.cssClass); if (controlData.value != null) control.setAttribute('value', controlData.value); if (controlData.required === true) control.setAttribute('required', ''); //inputLabelContainer.append(control); containerForm.append(control); row.append(containerForm); }); container.append(row); }); //console.log("Controls", controls); var containerButton = document.createElement('div'); containerButton.setAttribute('class', 'submit-button'); submitButton42 = document.createElement('button'); submitButton42.innerHTML = data.submitText !== null ? data.submitText : 'Trimite'; submitButton42.className = data.submitCssClass !== null ? data.submitCssClass : 'btn btn-default'; submitButton42.onclick = async function () { submitButton42.disabled = true; //console.log("1"); var ok = true; for (let i = 0; i < controls.length && ok; i++) { var control = controls[i]; //console.log("2"); var element = document.getElementById(control.id); var type = element.getAttribute('type'); var value; //console.log(element.checked); // console.log(element.checked, " - ", value); switch (type) { case 'checkbox': { value = element.checked ? true : false; break; } case 'radio': { value = element.checked ? true : false; break; } case 'file': { //console.log(element.value); if (element.value != '') { /*let base64 = await getBase6442(element.files[0]); let name = element.value.split(/(\\|\/)/g).pop(); value = { Name: name, Base64: base64.split(',')[1] };*/ filesArray42.push(element.files[0]); value = "good"; } else { value = null; } break; } case 'email': { value = element.value; break; } default: { value = element.value; break; } } if (control.isForEmailValidation === true) { emailObject42 = value; ok = ok && validateEmail42(emailObject42); //console.log(emailObject42); } if (control.isForPhoneValidation === true) { phoneObject42 = value; } //console.log("4" + " control.type" + control.type); if (control.required != undefined && (control.required == true || control.isForEmailValidation === true) && control.type != null) { if (control.urlValidation != undefined) { var options = { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authentication': 'key=' + keyObject42, 'String': value, }, }; fetch(control.urlValidation, options) .then(response => response.json()) .then(jsonResponse => { //console.log("Api Response", jsonResponse); if (jsonResponse.isValid == false) { showModal42(generateErrorText42(control.label)); ok = false; //console.log("fetch(control.urlValidation, options) --- " + ok); } }); } else { //console.log(value); if (value == undefined || value == null || value == '' || ok == false) { showModal42(generateErrorText42(control.label)); submitButton42.disabled = false; ok = false; // console.log("if (value == undefined || value == null || value == ) { --- " + ok); } } } //console.log("5"); control['value'] = value; if (requestedConfirmation42) confirmationCode42 = value; } // console.log("Controls after", controls); if (ok === true) { if (hasValidation42 != 0) { if (requestedConfirmation42 == false) { //SAVE FORM DATA formData42 = { url: window.location.href, linkId: formIdObject42, controls: controls }; //REQUEST CONFIRMATION var confirmationRequestBody = JSON.stringify({ url: window.location.href, linkId: formIdObject42, email: emailObject42, phone: phoneObject42 }); var options = { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: confirmationRequestBody, }; var confirmationUrl = backendUrlObject42 + 'validate-request'; var response = await fetch(confirmationUrl, options); if (response.ok) { requestedConfirmation42 = true; var json = await response.json(); confirmationKey42 = json.key; //SHOW INSERT CONFIRMATION CODE FORM initialElement42.innerHTML = ''; loadFunction42(json); } else { console.log(response.body); } } else { //TRY TO SEND DATA AND CONFIRMATION CODE formData42['key'] = confirmationKey42; formData42['code'] = confirmationCode42; await sendFormBody42(); } } else { formData42 = { url: window.location.href, linkId: formIdObject42, controls: controls }; await sendFormBody42(); } } }; if (data.hasSubmitButton) { containerButton.append(submitButton42); container.append(containerButton); } var footer = document.createElement('footer'); footer.innerHTML = data.footer; container.append(footer); var modal = document.createElement('div'); modal.setAttribute('class', 'modal'); modal.setAttribute('id', 'errModal'); var modalContent = document.createElement('div'); modalContent.setAttribute('class', 'modal-content'); var span = document.createElement('span'); span.setAttribute('class', 'close'); span.innerHTML = '×'; span.onclick = function () { modal.style.display = 'none'; reloadFormFunction42(); }; modalContent.append(span); var p = document.createElement('p'); p.setAttribute('id', 'errText'); modalContent.append(p); modal.append(modalContent); //IF DATA WAS SENT, CLEAR EVERYTHING AND GET THE FORM AGAIN window.onclick = function (event) { if (event.target == modal) { modal.style.display = 'none'; reloadFormFunction42(); } }; container.append(modal); } function generateErrorText42(label) { return 'Campul ' + label + ' nu a fost completat corect'; } function showModal42(error) { var p = document.getElementById('errText'); p.innerText = error; var modal = document.getElementById('errModal'); modal.style.display = 'block'; } function createElementFunction42(controlData) { let control; switch (controlData.htmlTag) { case 'input': { control = document.createElement('input'); control.setAttribute('type', controlData.type); break; } case 'select': { control = document.createElement('select'); for (var i = 0; i < controlData.options.length; i++) { var option = document.createElement('option'); option.value = controlData.options[i]; option.text = controlData.options[i]; control.appendChild(option); } break; } case 'textarea': { control = document.createElement('textarea'); control.setAttribute('rows', controlData.rows); break; } case 'span': { control = document.createElement('span'); let linkText = document.createTextNode(controlData.text); // control.appendChild(linkText); control.innerHTML = controlData.text; break; } case 'a': { control = document.createElement('a'); let linkText = document.createTextNode(controlData.text); control.appendChild(linkText); control.setAttribute('href', controlData.href); break; } } return control; } function initVariables42() { emailObject42 = null; phoneObject42 = null; hasValidation42 = 0; requestedConfirmation42 = false; filesArray42 = []; formData42 = null; submitButton42 = null; confirmationKey42 = null; confirmationCode42 = null; } async function getBase6442(file) { return new Promise(resolve => { let fileReader = new FileReader(); fileReader.onload = e => resolve(fileReader.result); fileReader.readAsDataURL(file); }); } function validateEmail42(email) { const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } async function sendFormBody42() { var body = new FormData() filesArray42.forEach(file => { body.append("Files", file); }) //body.append("Files", filesArray42[0]); body.append("Body", JSON.stringify(formData42)) var options = { method: 'POST', headers: { }, body: body, }; // if (token !== undefined && token !== '') { // console.log("Are token:" + token); // options.headers.Token = token; // } var url = backendUrlObject42 + 'add-request'; var resp = await fetch(url, options); if (resp.ok) { //console.log("OK"); var valid = await resp.json(); if (valid == true) { refreshForm42 = true; showModal42('Formular completat cu succes. Multumim!'); } else { if (requestedConfirmation42) { showModal42('Codul este incorect!'); submitButton42.disabled = false; } else showModal42('Formularul nu a fost trimis cu succes. Va rugam sa verificati datele completate si sa incercati din nou.'); } } else { //console.log(formBodyResponse.body); } } async function reloadFormFunction42() { if (refreshForm42 == true) { refreshForm42 = false; initVariables42(); initialElement42.innerHTML = ''; fetch(backendUrlObject42 + 'getform/' + formIdObject42 + '/' + keyObject42, originalOptions42) .then(response => response.text()) .then(jsonResponse => { //console.log("Data", jsonResponse); //initialElement42.innerHTML = ""; loadFunction42(jsonResponse ? JSON.parse(jsonResponse) : {}); }) .catch(err => { console.log(err); }); } }