diff --git a/blocks/table/table.css b/blocks/table/table.css index 9497b6e..cce0c5e 100644 --- a/blocks/table/table.css +++ b/blocks/table/table.css @@ -19,6 +19,7 @@ width: 100%; border-top: 2px solid var(--blue); border-bottom: 2px solid var(--blue); + margin-top: var(--spacing-xl); } .table table thead th, diff --git a/blocks/table/table.js b/blocks/table/table.js index 21abb87..6a271e2 100644 --- a/blocks/table/table.js +++ b/blocks/table/table.js @@ -1,4 +1,5 @@ import { decorateIcons } from '../../scripts/aem.js'; +import { getCatalog } from '../../scripts/scripts.js'; const isDesktop = window.matchMedia('(min-width: 900px)'); @@ -23,11 +24,76 @@ function checkInput() { submitButton.disabled = !hasAddedQuantity; } +const wholesaleFields = [ + { + type: 'input', + label: 'Your Business Name', + name: 'businessName', + placeholder: 'your business name', + required: true, + validation: ['no-nums'], + }, + { + type: 'tel', + label: 'Phone Number', + name: 'phone', + required: true, + placeholder: 'your business phone number', + validation: ['phone:US'], + }, + { + type: 'email', + label: 'Email', + name: 'email', + required: true, + placeholder: 'your business email address', + }, + { + type: 'textarea', + label: 'Special Requests / Notes', + name: 'businessNote', + placeholder: 'Notes', + validation: ['no-nums'], + }, + { + type: 'select', + label: 'How would you like to receive your order?', + name: 'orderType', + placeholder: 'How would you like to receive your order?', + options: [ + { + label: 'delivery', + value: 'delivery', + }, + { + label: 'pickup', + value: 'pickup', + }, + ], + }, + { + type: 'date', + label: 'pickup Date', + name: 'pickupdate', + dependsOn: 'orderType', + showWhen: 'pickup', + required: true, + }, + { + type: 'time', + label: 'pickup Time', + name: 'pickuptime', + dependsOn: 'orderType', + showWhen: 'pickup', + required: true, + }, +]; + export default async function decorate(block) { - const wholesale = window.location.pathname.split('/').some((path) => path === 'wholesale'); + const wholesalePath = window.location.pathname.split('/').some((path) => path === 'wholesale'); // If a block has a url in the data-src attribute - if (block.hasAttribute('data-src') && wholesale) { + if (block.hasAttribute('data-src') && wholesalePath) { const link = block.dataset.src; const form = document.querySelector('.table-form'); @@ -39,6 +105,7 @@ export default async function decorate(block) { jsonData.splice(0, 2); const table = document.createElement('table'); + table.id = 'wholesale-table'; const wholesaleMap = {}; jsonData.forEach((product) => { @@ -60,7 +127,7 @@ export default async function decorate(block) { }); // decorate tbody - Object.values(wholesaleMap).forEach((group) => { + Object.values(wholesaleMap).forEach((group, groupIndex) => { // Create a tbody for each group of products (grouped by TYPE). const tbody = document.createElement('tbody'); const labelRow = document.createElement('tr'); @@ -74,26 +141,26 @@ export default async function decorate(block) { // create price header const priceTh = document.createElement('th'); const pricePTag = document.createElement('p'); - pricePTag.textContent = 'price'; + pricePTag.textContent = 'price per case'; priceTh.append(pricePTag); // create price header const availableTh = document.createElement('th'); const availablePTag = document.createElement('p'); - availablePTag.textContent = 'available'; + availablePTag.textContent = 'cases available'; availableTh.append(availablePTag); // create quantity header const quantityTh = document.createElement('th'); const quantityPTag = document.createElement('p'); - quantityPTag.textContent = 'quantity'; + quantityPTag.textContent = 'cases'; quantityTh.append(quantityPTag); labelRow.append(productTh, availableTh, priceTh, quantityTh); tbody.append(labelRow); // Loop over each product within the group and add table row and data - group.forEach((product) => { + group.forEach((product, productIndex) => { const productRow = document.createElement('tr'); // Setting default height to handle CLS error productRow.style.height = isDesktop.matches ? '100px' : '175px'; @@ -140,14 +207,60 @@ export default async function decorate(block) { soldoutElement.textContent = 'sold out'; quantityCell.append(soldoutElement); } else { + const wholesaleData = JSON.parse(localStorage.getItem('wholesale')); + const key = JSON.parse(sessionStorage.getItem('wholesaleKey')).toLowerCase(); + + const itemKey = `${[product.ID]}-${groupIndex}-${productIndex}`; + const quantityInput = document.createElement('input'); + quantityInput.value = wholesaleData[key][itemKey] ? wholesaleData[key][itemKey].amount : ''; quantityInput.type = 'number'; quantityInput.id = product.ID; quantityInput.dataset.itemName = product.ITEM; quantityInput.dataset.itemType = product.TYPE; quantityInput.min = 0; quantityInput.max = product.STOCKREMAINING; - quantityInput.addEventListener('input', () => checkInput()); + quantityInput.addEventListener('change', async (event) => { + const inputValue = Number(event.target.value); + + const wholesale = JSON.parse(localStorage.getItem('wholesale')) || {}; + + // Ensure nesting exists + wholesale[key] ||= {}; + + // If wholesaler added a value greater than 0 + if (inputValue > 0) { + try { + // Get square catalog list + const items = await getCatalog(); + + if (items) { + // Get this Square item data + const item = items?.byId?.[product.ID]; + + if (!item) return; + + wholesale[key][itemKey] = { + amount: inputValue, + }; + + localStorage.setItem('wholesale', JSON.stringify(wholesale)); + } + } catch (error) { + // eslint-disable-next-line no-console + console.error(error.message); + return; + } + // removed an item from the list completely + } else { + delete wholesale[key][itemKey]; + } + + localStorage.setItem('wholesale', JSON.stringify(wholesale)); + + checkInput(); + }); + quantityCell.append(quantityInput); } // Append product and quantity cells to the row. @@ -157,8 +270,82 @@ export default async function decorate(block) { // Append the tbody for this group to the table. table.append(tbody); }); + + // Fetch order form data + const wholesaleOrderFormData = JSON.parse(localStorage.getItem('orderFormData')); + + const wholesaleFieldsContainer = document.createElement('div'); + wholesaleFieldsContainer.classList.add('wholesale-fields-container'); + + wholesaleFields.forEach((field) => { + const fieldWrapper = document.createElement('div'); + fieldWrapper.dataset.fieldName = field.name; + + // hide by default if this field depends on another + if (field.dependsOn) { + fieldWrapper.style.display = 'none'; + } + + const label = document.createElement('label'); + label.textContent = field.label || ''; + label.htmlFor = field.name || ''; + form.append(label); + + let input; + + if (field.type === 'select') { + const select = document.createElement('select'); + select.name = field.name || ''; + select.id = field.name || ''; + + field.options.forEach((opt) => { + const option = document.createElement('option'); + option.value = opt.value; + option.textContent = opt.label; + select.append(option); + }); + + select.addEventListener('change', (e) => { + const isPickup = e.target.value === 'pickup'; + + ['pickupdate', 'pickuptime'].forEach((name) => { + const wrapper = form.querySelector(`[data-field-name="${name}"]`); + const schedulePickupInput = wrapper?.querySelector('input'); + + if (!wrapper || !schedulePickupInput) return; + + wrapper.style.display = isPickup ? '' : 'none'; + schedulePickupInput.disabled = !isPickup; + }); + }); + + input = select; + } else { + input = document.createElement('input'); + input.type = field.type || ''; + input.placeholder = field.placeholder || ''; + input.required = field.required || false; + input.name = field.name || ''; + input.id = field.name || ''; + input.value = wholesaleOrderFormData[field.name] || ''; + + input.addEventListener('input', (event) => { + const orderFormFields = JSON.parse(localStorage.getItem('orderFormData')); + orderFormFields[field.name] = event.target.value; + localStorage.setItem('orderFormData', JSON.stringify(orderFormFields)); + }); + + if (field.dependsOn) { + input.disabled = true; + } + } + + fieldWrapper.append(label, input); + form.append(fieldWrapper); + }); + // Add table to form in table block - form.prepend(table); + form.append(table); } catch (err) { throw new Error('no .json'); } diff --git a/pages/wholesale/wholesale.css b/pages/wholesale/wholesale.css index f4d8315..d3074d1 100644 --- a/pages/wholesale/wholesale.css +++ b/pages/wholesale/wholesale.css @@ -94,4 +94,21 @@ .wholesale .wholesale-form { margin-bottom: 20vh; +} + +.wholesale .wholesale-form label { + font-size: var(--heading-size-xs); + font-family: var(--heading-font-family); + color: var(--blue); + margin: 0; + text-transform: lowercase; +} + +.wholesale .wholesale-form input, textarea, select { + border: solid 2px var(--blue-light); + background-color: transparent; + padding: 20px; + margin-bottom: 6px; + color: var(--blue); + text-transform: lowercase; } \ No newline at end of file diff --git a/pages/wholesale/wholesale.js b/pages/wholesale/wholesale.js index 75d0c86..cada98c 100644 --- a/pages/wholesale/wholesale.js +++ b/pages/wholesale/wholesale.js @@ -1,6 +1,5 @@ /* eslint-disable import/prefer-default-export */ /* eslint-disable import/no-cycle */ -import { removeLeadingZero } from '../../helpers/helpers.js'; import { buildBlock, decorateBlock, @@ -8,20 +7,7 @@ import { loadCSS, } from '../../scripts/aem.js'; import buildForm from '../../utils/forms/forms.js'; -// eslint-disable-next-line import/no-cycle -import { wholesaleOrderForm, resetOrderForm } from '../../utils/order/order.js'; -import { createLineItem } from '../cart/cart.js'; -import { createModal, toggleModal } from '../../utils/modal/modal.js'; -import { getCatalog } from '../../scripts/scripts.js'; - -function buildModal(element, refresh) { - const wholesaleModal = document.createElement('div'); - wholesaleModal.classList.add('wholesale', 'modal'); - createModal(wholesaleModal); - element.append(wholesaleModal); - - toggleModal(wholesaleModal, 'your wholesale order', refresh); -} +import { getOrderFormData } from '../../utils/order/order.js'; function createSubmitButton() { // Create submit button wrapper @@ -224,9 +210,120 @@ async function fetchWholesaleHours() { return shouldDisplay; } -// eslint-disable-next-line consistent-return -async function fetchWholesaleDeliveryMethods() { +function getFormFieldData(form) { + const inputFields = {}; + const lineItems = []; + + const elements = form.querySelectorAll('input, select, textarea'); + + elements.forEach((el) => { + const { name, type, value } = el; + + switch (type) { + case 'checkbox': + inputFields[name] = el.checked; + break; + + case 'radio': + if (el.checked) { + inputFields[name] = value; + } + break; + + case 'number': { + const inputQuantity = Number(value); + const { itemType } = el.dataset; + + if (inputQuantity > 0) { + lineItems.push({ + item_id: el.id, + quantity: inputQuantity, + name: el.dataset.itemName, + type: itemType, + }); + } + break; + } + + case 'date': + case 'time': + case 'datetime-local': + inputFields[name] = value || null; + break; + + default: + inputFields[name] = value; + } + }); + + inputFields.lineItems = lineItems; + + return inputFields; +} + +function setWholesaleLocalStorage() { + // Try to read in existing wholesale data from localStorage + // and if nothing exists yet, set as an empty object. + const wholesaleLS = JSON.parse(localStorage.getItem('wholesale')) || {}; + + // Get wholesale key for this page and set to lowercase. + const wholesaleKey = JSON.parse(sessionStorage.getItem('wholesaleKey'))?.toLowerCase(); + + // Throw error if there is no wholesale key + if (!wholesaleKey) { + // eslint-disable-next-line no-console + console.log('No wholesaleKey found in sessionStorage'); + return; + } + + // add key if it does not exist + if (!wholesaleLS[wholesaleKey]) { + wholesaleLS[wholesaleKey] = {}; + localStorage.setItem('wholesale', JSON.stringify(wholesaleLS)); + } +} + +function resetWholesaleLocalStorageKeyData() { + const wholesaleLS = JSON.parse(localStorage.getItem('wholesale')) || {}; + + // Get wholesale key for this page and set to lowercase. + const wholesaleKey = JSON.parse(sessionStorage.getItem('wholesaleKey'))?.toLowerCase(); + + // Throw error if there is no wholesale key + if (!wholesaleKey) { + // eslint-disable-next-line no-console + console.log('No wholesaleKey found in sessionStorage'); + return; + } + + // add key if it does not exist + if (wholesaleLS[wholesaleKey]) { + wholesaleLS[wholesaleKey] = {}; + localStorage.setItem('wholesale', JSON.stringify(wholesaleLS)); + } +} + +export function buildGQs(params) { + let qs = ''; + Object.keys(params).forEach((key) => { + if (key in params) { + if (key === 'line_items') { + qs += `${key}=${encodeURIComponent(JSON.stringify(params[key]))}`; + } else { + qs += `${key}=${encodeURIComponent(params[key])}`; + } + qs += '&'; + } + }); + return qs; +} + +export async function updateWholesaleGoogleSheet(params) { const url = `${window.location.origin}/admin/wholesale-locations.json`; + const key = JSON.parse(sessionStorage.getItem('wholesaleKey')); + + let res; + try { const response = await fetch(url); if (!response.ok) { @@ -235,19 +332,54 @@ async function fetchWholesaleDeliveryMethods() { const json = await response.json(); if (json.data) { - const wholesaleKey = JSON.parse(sessionStorage.getItem('wholesaleKey')); - const deliverMethods = json.data.find((location) => location.LOCATION === wholesaleKey); - return deliverMethods.DELIVERY_METHOD; + const wholesaleItem = json.data.find((locationKey) => locationKey.LOCATION === key); + if (wholesaleItem) { + try { + const qs = buildGQs(params); + const path = new URL(wholesaleItem.LINK).pathname; + + const wholesaleScriptLinkRes = await fetch(`${wholesaleItem.SCRIPT_LINK}?${qs}`, { method: 'POST' }); + if (!wholesaleScriptLinkRes.ok) { + throw new Error(`Error fetching wholesale script link: ${wholesaleScriptLinkRes.status}`); + } + + const wholesalePrevRes = await fetch(`https://admin.hlx.page/preview/normal-icecream/site/main/${path}`, { method: 'POST' }); + if (!wholesalePrevRes.ok) { + throw new Error(`Error posting to preview: ${wholesalePrevRes.status}`); + } + + const wholesaleLiveRes = await fetch(`https://admin.hlx.page/live/normal-icecream/site/main/${path}`, { method: 'POST' }); + if (!wholesaleLiveRes.ok) { + throw new Error(`Error posting to preview: ${wholesaleLiveRes.status}`); + } + + return { + ok: response.ok, + }; + } catch (error) { + return { + ok: false, + message: error.message, + }; + } + } } } catch (error) { - // eslint-disable-next-line no-console - console.error(error.message); + return { + ok: false, + message: error.message, + }; } + + return res; } async function buildWholesale(main, link) { + // Set up localstorage for wholesale order management + setWholesaleLocalStorage(); + getOrderFormData(); + const showOrderWholesaleForm = await fetchWholesaleHours(); - const wholesaleDeliveryMethods = await fetchWholesaleDeliveryMethods(); const wholesaleFormContainer = main.querySelector('.wholesale-form'); @@ -269,53 +401,49 @@ async function buildWholesale(main, link) { const isValid = validateForm(); if (isValid) { - const inputs = form.querySelectorAll('input[type="number"]'); - - const lineItems = []; - /* eslint-disable-next-line no-restricted-syntax */ - for (const input of inputs) { - if (input.value > 0) { - try { - /* eslint-disable-next-line no-await-in-loop */ - const item = await getCatalog(); - - if (item) { - const squareItem = item.byId[input.id]; - /* eslint-disable-next-line no-await-in-loop */ - const lineItem = await createLineItem( - squareItem.id, - removeLeadingZero(input.value), - ); - lineItem.note = input.dataset.itemName; - lineItem.type = input.dataset.itemType; - lineItems.push(lineItem); - } - } catch (error) { - // eslint-disable-next-line no-console - console.error(error.message); - } - } - } + const placeOrderContainer = form.querySelector('.table-form-submit-wrapper'); - const wholesaleModal = document.querySelector('.wholesale.modal'); - /* eslint-disable-next-line no-inner-declarations */ - function refreshWholesaleContent(element) { - const modalContentSection = element.querySelector('.modal-content'); - modalContentSection.innerHTML = ''; + const placeOrderButton = form.querySelector('.table-form-submit-wrapper button'); + placeOrderButton.disabled = true; - const modalErrorContainer = element.querySelector('.modal-wholesale-content-container'); - if (modalErrorContainer) modalErrorContainer.remove(); + const processingMessage = document.createElement('div'); + processingMessage.textContent = 'we are processing your order..'; + processingMessage.className = 'processing-message'; + placeOrderContainer.append(processingMessage); - wholesaleOrderForm({ - line_items: lineItems, - deliveryMethods: wholesaleDeliveryMethods, - }, element); + const formData = getFormFieldData(form); + + let wholesaleNote = `email: ${formData.email || ''},\nphone #: ${formData.phone || ''},\nnote: ${formData.businessNote || ''}`; + + if (formData.orderType === 'pickup') { + wholesaleNote += `,\npickup date: ${formData.pickupdate},\npickup time: ${formData.pickuptime}`; } - if (!wholesaleModal) { - buildModal(main, refreshWholesaleContent); - } else { - toggleModal(wholesaleModal, 'your wholesale order', refreshWholesaleContent); + const params = { + business_name: formData.businessName || '', + business_email: formData.email || '', + business_note: wholesaleNote, + is_wholesale_order: true, + business_method: formData.orderType || '', + line_items: formData.lineItems, + }; + + try { + const processingOrder = await updateWholesaleGoogleSheet(params); + + const processingMessageDiv = form.querySelector('.table-form-submit-wrapper .processing-message'); + processingMessageDiv.remove(); + + if (processingOrder) { + const successMessage = document.createElement('div'); + successMessage.textContent = 'your order was successfully placed!'; + placeOrderContainer.append(successMessage); + } + + resetWholesaleLocalStorageKeyData(); + } catch (error) { + // eslint-disable-next-line no-console + console.log('error', error); } } }); @@ -325,6 +453,8 @@ async function buildWholesale(main, link) { block.classList.add('section'); const blockContentSection = block.querySelector('.block > div > div'); wholesaleFormContainer.appendChild(block); + + // This hits the table block and builds the form there decorateBlock(block); blockContentSection.append(form); @@ -357,80 +487,6 @@ async function fetchWholesaleKey(main, key) { } } -export function buildGQs(params) { - let qs = ''; - Object.keys(params).forEach((key) => { - if (key in params) { - if (key === 'line_items') { - qs += `${key}=${encodeURIComponent(JSON.stringify(params[key]))}`; - } else { - qs += `${key}=${encodeURIComponent(params[key])}`; - } - qs += '&'; - } - }); - return qs; -} - -export async function updateWholesaleGoogleSheet(orderData, orderFormFields) { - const url = `${window.location.origin}/admin/wholesale-locations.json`; - const key = JSON.parse(sessionStorage.getItem('wholesaleKey')); - - try { - const response = await fetch(url); - if (!response.ok) { - throw new Error(`Response status: ${response.status}`); - } - - const json = await response.json(); - if (json.data) { - const wholesaleItem = json.data.find((locationKey) => locationKey.LOCATION === key); - if (wholesaleItem) { - let wholesaleNote = `email: ${orderFormFields?.email},\nphone #: ${orderFormFields?.phone},\nnote: ${orderFormFields?.businessNote}`; - - if (orderFormFields.isPickupOrder) { - wholesaleNote += `,\npickup date: ${orderFormFields?.pickupdate},\npickup time: ${orderFormFields?.pickuptime}`; - } - - const params = { - business_email: orderFormFields.email, - business_name: orderFormFields.businessName, - business_note: wholesaleNote, - business_method: orderFormFields.isPickupOrder ? 'pickup' : 'delivery', - is_wholesale_order: true, - line_items: orderData.line_items, - }; - - params.line_items.forEach((p) => { - p.name = p.note; - delete p.base_price_money; - delete p.id; - delete p.item_type; - delete p.note; - }); - - try { - const qs = buildGQs(params); - const path = new URL(wholesaleItem.LINK).pathname; - - await fetch(`${wholesaleItem.SCRIPT_LINK}?${qs}`, { method: 'POST' }); - await fetch(`https://admin.hlx.page/preview/normal-icecream/site/main/${path}`, { method: 'POST' }); - await fetch(`https://admin.hlx.page/live/normal-icecream/site/main/${path}`, { method: 'POST' }); - - // Reset form - resetOrderForm(); - } catch (error) { - // eslint-disable-next-line no-console - console.error('Error updating inventory:', error); - } - } - } - } catch (error) { - // eslint-disable-next-line no-console - console.error(error.message); - } -} - async function handleBecomeWholesaler(formData) { const name = formData.find((data) => data.field === 'name').value; const businessName = formData.find((data) => data.field === 'businessName').value; diff --git a/utils/order/order.js b/utils/order/order.js index 534e7ba..201fa6b 100644 --- a/utils/order/order.js +++ b/utils/order/order.js @@ -7,8 +7,6 @@ import { getLastCartKey, getCartLocation, refreshCartContent, - getCartCard, - createCartTotalContent, } from '../../pages/cart/cart.js'; import { SquareOrderWrapper, @@ -22,10 +20,8 @@ import { SquareShippingData, } from '../../constructors/constructors.js'; import { refreshPaymentsContent } from '../customize/customize.js'; -import { getTotals } from '../../helpers/helpers.js'; -import { getCatalog, swapIcons } from '../../scripts/scripts.js'; +import { getCatalog } from '../../scripts/scripts.js'; import { loadCSS, decorateIcons } from '../../scripts/aem.js'; -import { updateWholesaleGoogleSheet } from '../../pages/wholesale/wholesale.js'; import { createCustomer, findCustomer } from '../../scripts/square-client/square/customer.js'; const alwaysVisibleFields = [ @@ -35,13 +31,6 @@ const alwaysVisibleFields = [ 'discountCode', ]; -const wholesaleSpecificFields = [ - 'businessName', - 'phone', - 'email', - 'businessNote', -]; - const addressFields = [ 'address1', 'address2', @@ -84,7 +73,6 @@ const fields = [ label: 'Phone Number', name: 'phone', placeholder: 'your cell', - // required: true, validation: ['phone:US'], }, { @@ -105,13 +93,11 @@ const fields = [ type: 'date', label: 'pickup Date', name: 'pickupdate', - // required: true, }, { type: 'time', label: 'pickup Time', name: 'pickuptime', - // required: true, }, { type: 'checkbox', @@ -209,60 +195,6 @@ async function addDiscountToOrder(order, orderFormData) { } } -function populateWholesaleFormFields(formFields, modal, wholesaleData) { - const orderFormFields = getOrderFormData(); - const fieldsToDisplay = []; - - const wholesaleFields = []; - wholesaleSpecificFields.forEach((field) => { - const wholesaleField = formFields.find((f) => f.name === field); - if (wholesaleField) wholesaleFields.push(wholesaleField); - }); - wholesaleFields.forEach((field) => fieldsToDisplay.push(field)); - - const methods = wholesaleData.deliveryMethods.split(',').map((item) => item.trim()); - const pickupAllowed = methods.includes('pickup'); - - if (pickupAllowed) { - const isPickupField = formFields.find((f) => f.name === 'isPickupOrder'); - fieldsToDisplay.push(isPickupField); - } - - const pickupOrder = getOrderFormData().isPickupOrder; - if ((pickupOrder || !pickupAllowed)) { - const forPickupFields = []; - pickupFields.forEach((field) => { - const pickupField = formFields.find((f) => f.name === field); - if (pickupField) forPickupFields.push(pickupField); - }); - forPickupFields.forEach((field) => fieldsToDisplay.push(field)); - } - - return fieldsToDisplay.map((field) => { - const value = orderFormFields[field.name] || ''; - return { - ...field, - value, - checked: field.type === 'checkbox' ? Boolean(orderFormFields[field.name]) : undefined, - oninput: (event) => { - if (event.target.type === 'checkbox') { - orderFormFields[field.name] = event.target.checked; - localStorage.setItem('orderFormData', JSON.stringify(orderFormFields)); - - // Clearing modal content so we can display the form with the correct shouldShip fields - const modalContentSection = modal.querySelector('.modal-content'); - modalContentSection.innerHTML = ''; - // eslint-disable-next-line no-use-before-define - wholesaleOrderForm(wholesaleData, modal); - } else { - orderFormFields[field.name] = event.target.value; - localStorage.setItem('orderFormData', JSON.stringify(orderFormFields)); - } - }, - }; - }); -} - function populateFormFields(formFields, key, modal) { const orderFormFields = getOrderFormData(); const fieldsToDisplay = []; @@ -430,170 +362,6 @@ export async function handleNewCustomer(idempotencyKey, orderFormData) { return customer; } -export function wholesaleOrderForm(wholesaleData, modal) { - loadCSS(`${window.hlx.codeBasePath}/utils/order/order.css`); - modal.classList.add('order'); - const env = getEnvironment(); - getOrderFormData(); - - const modalContent = modal.querySelector('.modal-content'); - const wholesaleCartCard = getCartCard(wholesaleData); - modalContent.append(wholesaleCartCard); - - async function createSquareWholesaleOrder() { - const orderFormFields = getOrderFormData(); - // eslint-disable-next-line max-len - const orderData = new SquareOrderData(wholesaleData).build(); - - const note = []; - if (wholesaleData.note) note.push(wholesaleData.note); - orderData.note = note.length > 0 ? note.join(' | ') : ''; - orderData.line_items.forEach((item) => { - item.quantity = String(item.quantity); - }); - - if (env === 'sandbox') { - orderData.line_items.forEach((item) => { - item.id = item.catalog_object_id; - delete item.catalog_object_id; - }); - } - - const newOrderObject = new SquareOrderWrapper(orderData).build(); - const cartLocation = getCartLocation(); - - try { - let newOrder; - if (env === 'sandbox') { - newOrder = await hitSandbox(createOrder, JSON.stringify(newOrderObject), '&location=sandbox'); - } else { - newOrder = await createOrder(JSON.stringify(newOrderObject), `&location=${cartLocation}`); - } - - if (newOrder) { - // const customer = await handleNewCustomer(newOrder.idempotency_key, orderFormFields); - // if (customer) { - const wholesaleModalContent = modal.querySelector('.modal-content'); - wholesaleModalContent.querySelector('.wholesale-order-form').remove(); - - getTotals(modal, newOrder, createCartTotalContent); - - const createWholesaleOrderButton = document.createElement('button'); - createWholesaleOrderButton.className = 'wholesale-button'; - createWholesaleOrderButton.textContent = 'submit wholesale order'; - createWholesaleOrderButton.addEventListener('click', async (event) => { - event.preventDefault(); - - try { - // Show loading screen - wholesaleModalContent.innerHTML = ''; // Clear previous content - const loadingContainer = document.createElement('div'); - loadingContainer.className = 'modal-wholesale-content-container'; - - const iconContainer = document.createElement('div'); - const iconSpan = document.createElement('span'); - iconSpan.className = 'icon icon-pints'; - iconContainer.append(iconSpan); - loadingContainer.append(iconContainer); - - // add container to DOM first - wholesaleModalContent.append(loadingContainer); - // then decorate icons - decorateIcons(wholesaleModalContent); - // then swap icons - swapIcons(); - - const loadingMessage = document.createElement('h4'); - loadingMessage.className = 'wholesale-loading-message'; - loadingMessage.textContent = 'We are processing your order :)'; - loadingContainer.append(loadingMessage); - - wholesaleModalContent.append(loadingContainer); - - // update google sheet - await updateWholesaleGoogleSheet( - orderData, - orderFormFields, - ); - - wholesaleModalContent.innerHTML = ''; - - const successContainer = document.createElement('div'); - successContainer.className = 'modal-wholesale-content-container'; - - const successIconContainer = document.createElement('div'); - const successIconSpan = document.createElement('span'); - successIconSpan.className = 'icon icon-logo'; - successIconContainer.append(successIconSpan); - successContainer.append(successIconContainer); - - // add to DOM first - wholesaleModalContent.append(successContainer); - // then decorate - decorateIcons(wholesaleModalContent); - // then swap - swapIcons(); - - const successMessage = document.createElement('h4'); - successMessage.className = 'wholesale-success-message'; - successMessage.textContent = 'great choice! your order has been placed successfully.'; - successContainer.append(successMessage); - - const backButton = document.createElement('button'); - backButton.textContent = 'back to wholesale'; - backButton.className = 'wholesale-button'; - backButton.addEventListener('click', () => { - toggleModal(modal); - window.location.reload(); - }); - successContainer.append(backButton); - wholesaleModalContent.append(successContainer); - - document.querySelector('.wholesale-form').reset(); - } catch (error) { - // eslint-disable-next-line no-console - console.error('Error processing order:', error); - - // Replace loading screen with error message - wholesaleModalContent.innerHTML = ''; - - const errorContainer = document.createElement('div'); - errorContainer.className = 'modal-wholesale-content-container'; - - const iconContainer = document.createElement('div'); - const iconSpan = document.createElement('span'); - iconSpan.className = 'icon icon-error'; - iconContainer.append(iconSpan); - errorContainer.append(iconContainer); - decorateIcons(wholesaleModalContent); - - const errorMessage = document.createElement('h4'); - errorMessage.className = 'wholesale-error-message'; - errorMessage.textContent = 'Oops! Something went wrong while placing your wholesale order. Please try again.'; - errorContainer.append(errorMessage); - - const retryButton = document.createElement('button'); - retryButton.textContent = 'Try Again'; - retryButton.addEventListener('click', () => toggleModal(modal)); - - errorContainer.append(retryButton); - modal.append(errorContainer); - } - }); - - wholesaleModalContent.append(createWholesaleOrderButton); - } - } catch (error) { - // eslint-disable-next-line no-console - console.log('error with creating an order:', error); - } - } - const populatedFields = populateWholesaleFormFields(fields, modal, wholesaleData); - const form = buildForm(populatedFields, createSquareWholesaleOrder, modal); - form.className = 'form wholesale-order-form'; - modalContent.append(form); -} - export function orderForm(cartData) { loadCSS(`${window.hlx.codeBasePath}/utils/order/order.css`); const env = getEnvironment();