From 34a2ba3b058dce30f4a6bc068f10692c3f55672b Mon Sep 17 00:00:00 2001 From: Oliver Date: Thu, 9 Oct 2025 08:32:20 -0300 Subject: [PATCH] try --- public/tryModal.js | 362 ++++++++++++++++++++--------------------- public/tryModal.min.js | 2 +- 2 files changed, 173 insertions(+), 191 deletions(-) diff --git a/public/tryModal.js b/public/tryModal.js index aeccec6..453e809 100644 --- a/public/tryModal.js +++ b/public/tryModal.js @@ -1,215 +1,197 @@ -const TRYNOW_WEBHOOK_URL = "https://002-001-5dd6e535-4d1c-46bc-9bd9-42ad4bc5f082.odoo4projects.com/webhook/c25169c6-4234-4b47-8e74-612b9539da0a"; +// --- Category Configuration --- +const CATEGORY_CONFIG = { + 3: { showLocation: false, webhook: "" }, // services + 4: { showLocation: true, webhook: "https://002-001-5dd6e535-4d1c-46bc-9bd9-42ad4bc5f082.odoo4projects.com/webhook/c76e6b4e-af2f-4bc3-9875-6460d0ffc8e3" }, // hosting + 5: { showLocation: false, webhook: "https://002-001-5dd6e535-4d1c-46bc-9bd9-42ad4bc5f082.odoo4projects.com/webhook/fd20e194-b821-4b1f-814f-7bb93ae16046" }, // Workshops + 7: { showLocation: false, webhook: "" }, // modules +}; -// --- Helper: Get URL parameters --- -function getUrlParams() { - const params = {}; - window.location.search - .substring(1) - .split("&") - .forEach(pair => { - if (pair) { - const [key, value] = pair.split("="); - params[decodeURIComponent(key)] = decodeURIComponent(value || ""); - } - }); - return params; +// --- Helper: Get cookie by name --- +function getCookie(name) { + const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)')); + return match ? decodeURIComponent(match[2]) : null; } -// --- Add UTM fields to form --- +// --- Add UTM fields to form using cookies --- function addUtmFields(form) { - const utmParams = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"]; - const urlParams = getUrlParams(); + const utmParams = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"]; + const defaults = { + utm_source: "homepage", + utm_medium: "direct", + utm_campaign: "none", + utm_term: "", + utm_content: "" + }; - const defaults = { - utm_source: "homepage", - utm_medium: "direct", - utm_campaign: "none" - }; - - utmParams.forEach(param => { - let input = form.querySelector(`input[name="${param}"]`); - if (!input) { - input = document.createElement("input"); - input.type = "hidden"; - input.name = param; - form.appendChild(input); - } - input.value = urlParams[param] || defaults[param] || ""; - }); + utmParams.forEach(param => { + let input = form.querySelector(`input[name="${param}"]`); + if (!input) { + input = document.createElement("input"); + input.type = "hidden"; + input.name = param; + form.appendChild(input); + } + // Get value from cookie or fallback to default + input.value = getCookie(param) || defaults[param]; + }); } -// --- Create modal --- -function tryNow_createModal() { - const modal = document.createElement("div"); - modal.id = "trynowModal"; - modal.style.position = "fixed"; - modal.style.top = "0"; - modal.style.left = "0"; - modal.style.width = "100%"; - modal.style.height = "100%"; - modal.style.backgroundColor = "rgba(0,0,0,0.6)"; - modal.style.display = "none"; - modal.style.justifyContent = "center"; - modal.style.alignItems = "center"; - modal.style.zIndex = "1000"; +// --- Create Modal --- +function createModal() { + const modal = document.createElement("div"); + modal.id = "buyNowModal"; + Object.assign(modal.style, { + position: "fixed", + top: "0", + left: "0", + width: "100%", + height: "100%", + backgroundColor: "rgba(0,0,0,0.6)", + display: "none", + justifyContent: "center", + alignItems: "center", + zIndex: "1000" + }); - modal.innerHTML = ` -
- × - -

Order Details

+ modal.innerHTML = ` +
+ × +

Order Details

+

-
- + + - - - - - -
- -
-

Thank you for your submission! 🎉

- -
+ + + + +
+ +
- `; + + + + + - document.body.appendChild(modal); + + - // Add UTM fields after form exists - const form = modal.querySelector("#trynowForm"); + +
+ `; + + document.body.appendChild(modal); + document.getElementById("closeModal").onclick = () => modal.style.display = "none"; + document.getElementById("closeConfirmation").onclick = () => { + document.getElementById("confirmation").style.display = "none"; + modal.style.display = "none"; + }; + modal.onclick = e => { if (e.target === modal) modal.style.display = "none"; }; + return modal; +} + +// --- Open Modal --- +function openModal(productHref) { + const modal = document.getElementById("buyNowModal"); + const form = modal.querySelector("#buyForm"); + const confirmation = modal.querySelector("#confirmation"); + modal.style.display = "flex"; + form.style.display = "flex"; + confirmation.style.display = "none"; + + const parts = productHref.split("/").filter(Boolean); + const [id, price, category, ...productParts] = parts; + const product = decodeURIComponent(productParts.join("/")); + const categoryNum = parseInt(category, 10); + const config = CATEGORY_CONFIG[categoryNum] || { showLocation: false, webhook: "" }; + + const locationSelect = document.getElementById("locationSelect"); + if (config.showLocation) { + locationSelect.style.display = "block"; + locationSelect.setAttribute("required", "true"); + } else { + locationSelect.style.display = "none"; + locationSelect.removeAttribute("required"); + locationSelect.value = ""; + } + + form.querySelector('input[name="id"]').value = id || ""; + form.querySelector('input[name="price"]').value = price || "0"; + form.querySelector('input[name="category"]').value = category || ""; + form.querySelector('input[name="product"]').value = product || "Unknown"; + form.dataset.webhook = config.webhook || ""; + modal.querySelector("#productText").textContent = `You will buy ${product} for $${price}.`; + + addUtmFields(form); // Read values from cookies +} + +// --- Handle Form Submit --- +function handleFormSubmit() { + const form = document.getElementById("buyForm"); + const confirmation = document.getElementById("confirmation"); + + form.addEventListener("submit", async (e) => { + e.preventDefault(); addUtmFields(form); - // Close modal handlers - document.getElementById("trynowCloseModal").onclick = () => { modal.style.display = "none"; }; - document.getElementById("trynowCloseConfirmation").onclick = () => { - document.getElementById("trynowConfirmation").style.display = "none"; - modal.style.display = "none"; - }; - modal.onclick = (e) => { if (e.target === modal) modal.style.display = "none"; }; + const data = Object.fromEntries(new FormData(form).entries()); + const webhookUrl = form.dataset.webhook; - return modal; + if (!webhookUrl) { + alert("No webhook configured for this category."); + return; + } + + try { + const res = await fetch(webhookUrl, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(data), + }); + + if (res.ok) { + form.style.display = "none"; + confirmation.style.display = "block"; + form.reset(); + } else { + alert("Failed to submit form."); + } + } catch (err) { + console.error(err); + alert("Error submitting form."); + } + }); } -// --- Handle form submission --- -function tryNow_handleFormSubmit() { - const form = document.getElementById("trynowForm"); - const confirmation = document.getElementById("trynowConfirmation"); - - form.addEventListener("submit", async (e) => { +// --- Attach Buttons --- +function attachButtons() { + const buttons = Array.from(document.querySelectorAll("button, a")); + buttons.forEach(btn => { + const text = btn.textContent.trim(); + if (text === "Buy Now" || text === "Book Now") { + btn.addEventListener("click", (e) => { e.preventDefault(); - - // Update UTM fields in case URL changed - addUtmFields(form); - - const data = {}; - new FormData(form).forEach((value, key) => (data[key] = value)); - - try { - const res = await fetch(TRYNOW_WEBHOOK_URL, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(data) - }); - - if (res.ok) { - form.style.display = "none"; - confirmation.style.display = "block"; - form.reset(); - } else { - alert("Failed to submit form."); - } - } catch (err) { - console.error(err); - alert("Error submitting form."); - } - }); -} - -// --- Attach "Try Now" buttons --- -function tryNow_attachButtons() { - const buttons = Array.from(document.querySelectorAll("a, button")); - buttons.forEach(btn => { - if (btn.textContent && btn.textContent.trim() === "Try Now") { - btn.addEventListener("click", (e) => { - e.preventDefault(); - const modal = document.getElementById("trynowModal"); - if (modal) { - modal.style.display = "flex"; - - // Reset modal state - const form = document.getElementById("trynowForm"); - const confirmation = document.getElementById("trynowConfirmation"); - if (form && confirmation) { - form.style.display = "flex"; - confirmation.style.display = "none"; - addUtmFields(form); // refresh UTM fields each open - } - } - }); - } - }); + const href = btn.getAttribute("href") || btn.dataset.product || "Unknown/0/0"; + openModal(href); + }); + } + }); } // --- Initialize --- document.addEventListener("DOMContentLoaded", () => { - tryNow_createModal(); - tryNow_handleFormSubmit(); - tryNow_attachButtons(); + createModal(); + handleFormSubmit(); + attachButtons(); }); diff --git a/public/tryModal.min.js b/public/tryModal.min.js index 49dd43a..e5e6a3a 100644 --- a/public/tryModal.min.js +++ b/public/tryModal.min.js @@ -1 +1 @@ -const TRYNOW_WEBHOOK_URL="https://002-001-5dd6e535-4d1c-46bc-9bd9-42ad4bc5f082.odoo4projects.com/webhook/c25169c6-4234-4b47-8e74-612b9539da0a";function getUrlParams(){const n={};return window.location.search.substring(1).split("&").forEach(t=>{if(t){const[e,o]=t.split("=");n[decodeURIComponent(e)]=decodeURIComponent(o||"")}}),n}function addUtmFields(n){const t=getUrlParams(),e={utm_source:"homepage",utm_medium:"direct",utm_campaign:"none"};["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(o=>{let r=n.querySelector(`input[name="${o}"]`);r||(r=document.createElement("input"),r.type="hidden",r.name=o,n.appendChild(r)),r.value=t[o]||e[o]||""})}function tryNow_createModal(){const n=document.createElement("div");n.id="trynowModal",n.style.position="fixed",n.style.top="0",n.style.left="0",n.style.width="100%",n.style.height="100%",n.style.backgroundColor="rgba(0,0,0,0.6)",n.style.display="none",n.style.justifyContent="center",n.style.alignItems="center",n.style.zIndex="1000",n.innerHTML='\n
\n ×\n \n

Order Details

\n\n
\n \n\n \n\n \n\n \n
\n\n
\n

Thank you for your submission! 🎉

\n \n
\n
\n ',document.body.appendChild(n);return addUtmFields(n.querySelector("#trynowForm")),document.getElementById("trynowCloseModal").onclick=()=>{n.style.display="none"},document.getElementById("trynowCloseConfirmation").onclick=()=>{document.getElementById("trynowConfirmation").style.display="none",n.style.display="none"},n.onclick=t=>{t.target===n&&(n.style.display="none")},n}function tryNow_handleFormSubmit(){const n=document.getElementById("trynowForm"),t=document.getElementById("trynowConfirmation");n.addEventListener("submit",async e=>{e.preventDefault(),addUtmFields(n);const o={};new FormData(n).forEach((n,t)=>o[t]=n);try{(await fetch(TRYNOW_WEBHOOK_URL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).ok?(n.style.display="none",t.style.display="block",n.reset()):alert("Failed to submit form.")}catch(n){console.error(n),alert("Error submitting form.")}})}function tryNow_attachButtons(){Array.from(document.querySelectorAll("a, button")).forEach(n=>{n.textContent&&"Try Now"===n.textContent.trim()&&n.addEventListener("click",n=>{n.preventDefault();const t=document.getElementById("trynowModal");if(t){t.style.display="flex";const n=document.getElementById("trynowForm"),e=document.getElementById("trynowConfirmation");n&&e&&(n.style.display="flex",e.style.display="none",addUtmFields(n))}})})}document.addEventListener("DOMContentLoaded",()=>{tryNow_createModal(),tryNow_handleFormSubmit(),tryNow_attachButtons()}); \ No newline at end of file +const CATEGORY_CONFIG={3:{showLocation:!1,webhook:""},4:{showLocation:!0,webhook:"https://002-001-5dd6e535-4d1c-46bc-9bd9-42ad4bc5f082.odoo4projects.com/webhook/c76e6b4e-af2f-4bc3-9875-6460d0ffc8e3"},5:{showLocation:!1,webhook:"https://002-001-5dd6e535-4d1c-46bc-9bd9-42ad4bc5f082.odoo4projects.com/webhook/fd20e194-b821-4b1f-814f-7bb93ae16046"},7:{showLocation:!1,webhook:""}};function getCookie(e){const t=document.cookie.match(new RegExp("(^| )"+e+"=([^;]+)"));return t?decodeURIComponent(t[2]):null}function addUtmFields(e){const t={utm_source:"homepage",utm_medium:"direct",utm_campaign:"none",utm_term:"",utm_content:""};["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(o=>{let n=e.querySelector(`input[name="${o}"]`);n||(n=document.createElement("input"),n.type="hidden",n.name=o,e.appendChild(n)),n.value=getCookie(o)||t[o]})}function createModal(){const e=document.createElement("div");return e.id="buyNowModal",Object.assign(e.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(0,0,0,0.6)",display:"none",justifyContent:"center",alignItems:"center",zIndex:"1000"}),e.innerHTML='\n
\n ×\n

Order Details

\n

\n\n
\n \n\n \n \n \n \n
\n \n \n
\n \n \n \n \n \n\n \n
\n\n \n
\n ',document.body.appendChild(e),document.getElementById("closeModal").onclick=()=>e.style.display="none",document.getElementById("closeConfirmation").onclick=()=>{document.getElementById("confirmation").style.display="none",e.style.display="none"},e.onclick=t=>{t.target===e&&(e.style.display="none")},e}function openModal(e){const t=document.getElementById("buyNowModal"),o=t.querySelector("#buyForm"),n=t.querySelector("#confirmation");t.style.display="flex",o.style.display="flex",n.style.display="none";const d=e.split("/").filter(Boolean),[r,i,a,...p]=d,c=decodeURIComponent(p.join("/")),l=parseInt(a,10),s=CATEGORY_CONFIG[l]||{showLocation:!1,webhook:""},u=document.getElementById("locationSelect");s.showLocation?(u.style.display="block",u.setAttribute("required","true")):(u.style.display="none",u.removeAttribute("required"),u.value=""),o.querySelector('input[name="id"]').value=r||"",o.querySelector('input[name="price"]').value=i||"0",o.querySelector('input[name="category"]').value=a||"",o.querySelector('input[name="product"]').value=c||"Unknown",o.dataset.webhook=s.webhook||"",t.querySelector("#productText").textContent=`You will buy ${c} for $${i}.`,addUtmFields(o)}function handleFormSubmit(){const e=document.getElementById("buyForm"),t=document.getElementById("confirmation");e.addEventListener("submit",async o=>{o.preventDefault(),addUtmFields(e);const n=Object.fromEntries(new FormData(e).entries()),d=e.dataset.webhook;if(d)try{(await fetch(d,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).ok?(e.style.display="none",t.style.display="block",e.reset()):alert("Failed to submit form.")}catch(e){console.error(e),alert("Error submitting form.")}else alert("No webhook configured for this category.")})}function attachButtons(){Array.from(document.querySelectorAll("button, a")).forEach(e=>{const t=e.textContent.trim();"Buy Now"!==t&&"Book Now"!==t||e.addEventListener("click",t=>{t.preventDefault();openModal(e.getAttribute("href")||e.dataset.product||"Unknown/0/0")})})}document.addEventListener("DOMContentLoaded",()=>{createModal(),handleFormSubmit(),attachButtons()}); \ No newline at end of file