From ff68c09594ff9c8bfc615c38e339d5599f547fbf Mon Sep 17 00:00:00 2001 From: Konstantin Fandelyuk Date: Wed, 18 Sep 2024 23:37:39 +0300 Subject: [PATCH] eds-400 reveted work version --- .../commerce-search-order.js | 50 +++++----- scripts/__dropins__/storefront-order/api.js | 10 +- .../containers/OrderSearch.js | 2 +- scripts/configs.js | 36 +++---- scripts/dropins.js | 93 ++++++++----------- 5 files changed, 79 insertions(+), 112 deletions(-) diff --git a/blocks/commerce-search-order/commerce-search-order.js b/blocks/commerce-search-order/commerce-search-order.js index 8b0e6b8e8b..af8f7011cf 100644 --- a/blocks/commerce-search-order/commerce-search-order.js +++ b/blocks/commerce-search-order/commerce-search-order.js @@ -1,48 +1,42 @@ -/* eslint-disable implicit-arrow-linebreak */ -/* eslint-disable quotes */ /* eslint-disable import/no-unresolved */ /* eslint-disable import/no-extraneous-dependencies */ -import { SignIn } from "@dropins/storefront-auth/containers/SignIn.js"; -import { OrderSearch } from "@dropins/storefront-order/containers/OrderSearch.js"; -import { render as authRenderer } from "@dropins/storefront-auth/render.js"; -import { render as orderRenderer } from "@dropins/storefront-order/render.js"; -import { getCookie } from "../../scripts/configs.js"; +import { SignIn } from '@dropins/storefront-auth/containers/SignIn.js'; +import { OrderSearch } from '@dropins/storefront-order/containers/OrderSearch.js'; +import { render as authRenderer } from '@dropins/storefront-auth/render.js'; +import { render as orderRenderer } from '@dropins/storefront-order/render.js'; +import { getCookie } from '../../scripts/configs.js'; -const renderSignIn = async (element, email, orderNumber) => - authRenderer.render(SignIn, { - initialEmailValue: email, - renderSignUpLink: false, - labels: { - formTitleText: email - ? "Enter your password to view order details" - : "Sign in to view order details", - primaryButtonText: "View order", - }, - routeForgotPassword: () => "reset-password.html", - routeRedirectOnSignIn: () => - `/customer/order-details?orderRef=${orderNumber}`, - })(element); +const renderSignIn = async (element, email, orderNumber) => authRenderer.render(SignIn, { + initialEmailValue: email, + renderSignUpLink: false, + labels: { + formTitleText: email + ? 'Enter your password to view order details' + : 'Sign in to view order details', + primaryButtonText: 'View order', + }, + routeForgotPassword: () => 'reset-password.html', + routeRedirectOnSignIn: () => `/customer/order-details?orderRef=${orderNumber}`, +})(element); export default async function decorate(block) { - const isAuthenticated = !!getCookie("auth_dropin_user_token") || false; + const isAuthenticated = !!getCookie('auth_dropin_user_token') || false; await orderRenderer.render(OrderSearch, { isAuth: isAuthenticated, renderSignIn: async ({ render, formValues }) => { if (render) { - renderSignIn(block, formValues?.email ?? "", formValues?.number ?? ""); + renderSignIn(block, formValues?.email ?? '', formValues?.number ?? ''); return false; } return true; }, - // routeCustomerOrder - routeCustomerOrderDetails: () => "/customer/order-details/1", - // routeGuestOrder - routeOrderDetails: () => "/order-details/", + routeCustomerOrderDetails: () => '/customer/order-details', + routeOrderDetails: () => '/order-details', onError: async (errorInformation) => { - console.info("errorInformation", errorInformation); + console.info('errorInformation', errorInformation); }, })(block); } diff --git a/scripts/__dropins__/storefront-order/api.js b/scripts/__dropins__/storefront-order/api.js index 1e8b660f42..24755d3c6e 100644 --- a/scripts/__dropins__/storefront-order/api.js +++ b/scripts/__dropins__/storefront-order/api.js @@ -1,4 +1,4 @@ -import{Initializer as u}from"@dropins/tools/lib.js";import{events as s}from"@dropins/tools/event-bus.js";import{f as n,h as o,a as m}from"./chunks/fetch-graphql.js";import{g as $,r as w,s as A,b as C,c as N}from"./chunks/fetch-graphql.js";import{O as l,a as _,A as c,t as h,b as O}from"./chunks/getCustomer.js";import{c as F,g as M}from"./chunks/getCustomer.js";import{g as x}from"./chunks/getAttributesForm.js";import"@dropins/tools/fetch-graphql.js";const R=` +import{Initializer as u}from"@dropins/tools/lib.js";import{events as s}from"@dropins/tools/event-bus.js";import{f as n,h as m,a as o}from"./chunks/fetch-graphql.js";import{g as $,r as w,s as A,b as C,c as N}from"./chunks/fetch-graphql.js";import{O as _,a as c,A as l,t as h,b as O}from"./chunks/getCustomer.js";import{c as F,g as M}from"./chunks/getCustomer.js";import{g as x}from"./chunks/getAttributesForm.js";import"@dropins/tools/fetch-graphql.js";const y=` query ORDER_BY_NUMBER($orderNumber: String!) { customer { orders( @@ -77,10 +77,10 @@ query ORDER_BY_NUMBER($orderNumber: String!) { } } } -${l} ${_} ${c} -`,y=async(e,r)=>await n(R,{method:"GET",cache:"force-cache",variables:{orderNumber:e}}).then(t=>{var a;return(a=t.errors)!=null&&a.length?o(t.errors):h(r??"orderData",t)}).catch(m),f=` +${l} +`,f=async(e,r)=>await n(y,{method:"GET",cache:"force-cache",variables:{orderNumber:e}}).then(t=>{var a;return(a=t.errors)!=null&&a.length?m(t.errors):h(r??"orderData",t)}).catch(o),g=` query ORDER_BY_TOKEN($token: String!) { guestOrderByToken(input: { token: $token }) { email @@ -159,7 +159,7 @@ query ORDER_BY_TOKEN($token: String!) { } } } -${l} ${_} ${c} -`,g=async e=>await n(f,{method:"GET",cache:"no-cache",variables:{token:e}}).then(r=>{var t;return(t=r.errors)!=null&&t.length?o(r.errors):O(r)}).catch(m),b=async e=>{var d;let r=null;const t=(e==null?void 0:e.orderRef)??"";console.log("orderRef",t),console.log("config?.orderRef",e==null?void 0:e.orderRef);const a=t&&typeof(e==null?void 0:e.orderRef)=="string"&&((d=e==null?void 0:e.orderRef)==null?void 0:d.length)>20,i=(e==null?void 0:e.orderData)??null;if(i){s.emit("order/data",i);return}if(!t){console.error("Order Token or number not received.");return}a||(r=await y(t)),a&&(r=await g(t)),console.log("responseOrderData",r),r?s.emit("order/data",r):s.emit("order/error",{source:"order",type:"network",error:"The data was not received."})},p=new u({init:async e=>{const r={};p.config.setConfig({...r,...e}),b(e).catch(console.error)},listeners:()=>[]}),T=p.config;export{T as config,n as fetchGraphQl,x as getAttributesForm,$ as getConfig,F as getCustomer,M as getGuestOrder,y as getOrderDetailsById,g as guestOrderByToken,p as initialize,w as removeFetchGraphQlHeader,A as setEndpoint,C as setFetchGraphQlHeader,N as setFetchGraphQlHeaders}; +${l} +`,R=async e=>await n(g,{method:"GET",cache:"no-cache",variables:{token:e}}).then(r=>{var t;return(t=r.errors)!=null&&t.length?m(r.errors):O(r)}).catch(o),b=async e=>{var d;let r=null;const t=(e==null?void 0:e.orderRef)??"",a=t&&typeof(e==null?void 0:e.orderRef)=="string"&&((d=e==null?void 0:e.orderRef)==null?void 0:d.length)>20,i=(e==null?void 0:e.orderData)??null;if(i){s.emit("order/data",i);return}if(!t){console.error("Order Token or number not received.");return}a||(r=await f(t)),a&&(r=await R(t)),r?s.emit("order/data",r):s.emit("order/error",{source:"order",type:"network",error:"The data was not received."})},p=new u({init:async e=>{const r={};p.config.setConfig({...r,...e}),b(e).catch(console.error)},listeners:()=>[]}),T=p.config;export{T as config,n as fetchGraphQl,x as getAttributesForm,$ as getConfig,F as getCustomer,M as getGuestOrder,f as getOrderDetailsById,R as guestOrderByToken,p as initialize,w as removeFetchGraphQlHeader,A as setEndpoint,C as setFetchGraphQlHeader,N as setFetchGraphQlHeaders}; diff --git a/scripts/__dropins__/storefront-order/containers/OrderSearch.js b/scripts/__dropins__/storefront-order/containers/OrderSearch.js index a6ab1494db..bd3cb8ad16 100644 --- a/scripts/__dropins__/storefront-order/containers/OrderSearch.js +++ b/scripts/__dropins__/storefront-order/containers/OrderSearch.js @@ -1 +1 @@ -import{jsxs as v,jsx as c}from"@dropins/tools/preact-jsx-runtime.js";import{classes as D}from"@dropins/tools/lib.js";import{Card as U,InLineAlert as C,Icon as x,Button as V}from"@dropins/tools/components.js";import{F as L}from"../chunks/CustomerDetailsContent.js";import{useState as N,useCallback as R,useEffect as O,useMemo as k}from"@dropins/tools/preact-hooks.js";import*as A from"@dropins/tools/preact-compat.js";import{Text as S,useText as G}from"@dropins/tools/i18n.js";import{events as w}from"@dropins/tools/event-bus.js";import{c as I,g as H}from"../chunks/getCustomer.js";import"../chunks/fetch-graphql.js";import"@dropins/tools/fetch-graphql.js";const P=e=>A.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e},A.createElement("path",{vectorEffect:"non-scaling-stroke",fillRule:"evenodd",clipRule:"evenodd",d:"M1 20.8953L12.1922 1.5L23.395 20.8953H1ZM13.0278 13.9638L13.25 10.0377V9H11.25V10.0377L11.4722 13.9638H13.0278ZM11.2994 16V17.7509H13.2253V16H11.2994Z",fill:"currentColor"})),X=({onSubmit:e,loading:t,inLineAlert:o,fieldsConfig:a})=>v(U,{variant:"secondary",className:"dropin-order-search-form",children:[c("h2",{className:"dropin-order-search-form__title",children:c(S,{id:"Order.OrderSearchForm.title"})}),c("p",{children:c(S,{id:"Order.OrderSearchForm.description"})}),o.text?c(C,{"data-testid":"orderAlert",className:"dropin-order-search-form__alert",type:o.type,variant:"secondary",heading:o.text,icon:c(x,{source:P})}):null,c(L,{className:"dropin-order-search-form__wrapper",name:"orderSearchForm",loading:t,fieldsConfig:a,onSubmit:e,children:c("div",{className:"dropin-order-search-form__button-container",children:c(V,{className:"dropin-order-search-form__button",size:"medium",variant:"primary",type:"submit",disabled:t,children:c(S,{id:"Order.OrderSearchForm.button"})},"logIn")})})]});var h=(e=>(e.BOOLEAN="BOOLEAN",e.DATE="DATE",e.DATETIME="DATETIME",e.DROPDOWN="DROPDOWN",e.FILE="FILE",e.GALLERY="GALLERY",e.HIDDEN="HIDDEN",e.IMAGE="IMAGE",e.MEDIA_IMAGE="MEDIA_IMAGE",e.MULTILINE="MULTILINE",e.MULTISELECT="MULTISELECT",e.PRICE="PRICE",e.SELECT="SELECT",e.TEXT="TEXT",e.TEXTAREA="TEXTAREA",e.UNDEFINED="UNDEFINED",e.VISUAL="VISUAL",e.WEIGHT="WEIGHT",e.EMPTY="",e))(h||{});const B=e=>{if(!e)return null;const t=new FormData(e);if(e.querySelectorAll('input[type="checkbox"]').forEach(a=>{t.has(a.name)||t.set(a.name,"false"),a.checked&&t.set(a.name,"true")}),t&&typeof t.entries=="function"){const a=t.entries();if(a&&typeof a[Symbol.iterator]=="function")return JSON.parse(JSON.stringify(Object.fromEntries(a)))||{}}return{}},d=(e,t)=>{if(typeof e!="function")return;const o=e();if(!t||Object.keys(t).length===0){window.location.href=o;return}const a=new URLSearchParams;Object.entries(t).forEach(([p,m])=>{a.append(p,String(m))});const i=o.includes("?")?"&":"?";window.location.href=`${o}${i}${a.toString()}`},M=e=>{try{return new URL(window.location.href).searchParams.get(e)}catch{return null}},j=({onError:e,isAuth:t,renderSignIn:o,routeCustomerOrderDetails:a,routeOrderDetails:i})=>{const[p,m]=N({text:"",type:"success"}),[T,u]=N(!1),f=G({invalidSearch:"Order.Errors.invalidSearch",email:"Order.OrderSearchForm.email",postcode:"Order.OrderSearchForm.postcode",number:"Order.OrderSearchForm.orderNumber"}),y=R(async r=>{const s=M("orderRef"),l=s&&s.length>20;if(!r||!r.number||!r.token||s)return null;if(t&&r&&r.email){const n=await I();(n==null?void 0:n.email)===r.email?d(a,{orderRef:r==null?void 0:r.number}):l||d(i,{orderRef:r.token})}else l||d(i,{orderRef:r==null?void 0:r.token})},[t,a,i]);O(()=>{const r=w.on("order/data",s=>{console.log("useEffect(() orderSearchRedirect",s),y(s)},{eager:!0});return()=>{r==null||r.off()}},[y]),O(()=>{const r=M("orderRef"),s=r&&r.length>20?r:null;r&&(s?d(i,{orderRef:r}):t?d(a,{orderRef:r}):o({render:!0,formValues:{number:r}}))},[t,a,i,o]);const _=k(()=>[{entityType:"CUSTOMER_ADDRESS",is_unique:!1,label:f.email,options:[],defaultValue:"",fieldType:h.TEXT,className:"",required:!0,orderNumber:1,name:"email",id:"email",code:"email"},{entityType:"CUSTOMER_ADDRESS",is_unique:!1,label:f.postcode,options:[],defaultValue:"",fieldType:h.TEXT,className:"",required:!0,orderNumber:2,name:"postcode",id:"postcode",code:"postcode"},{entityType:"CUSTOMER_ADDRESS",is_unique:!1,label:f.number,options:[],defaultValue:"",fieldType:h.TEXT,className:"",required:!0,orderNumber:3,name:"number",id:"number",code:"number"}],[f]);return{onSubmit:R(async(r,s)=>{if(!s)return null;u(!0);const l=B(r.target);await H(l).then(n=>{n||m({text:f.invalidSearch,type:"warning"}),w.emit("order/data",n)}).catch(async n=>{var g;let b=!0;e==null||e({error:n.message});const E=await I();(E==null?void 0:E.email)===(l==null?void 0:l.email)?d(a,l.number):b=o==null?void 0:o({render:(g=n==null?void 0:n.message)==null?void 0:g.includes("Please login to view the order."),formValues:l}),b&&m({text:n.message,type:"warning"})}).finally(()=>{u(!1)})},[e,o,a,f]),inLineAlert:p,loading:T,normalizeFieldsConfig:_}},te=({className:e,isAuth:t,renderSignIn:o,routeCustomerOrderDetails:a,routeOrderDetails:i,onError:p})=>{const{onSubmit:m,loading:T,inLineAlert:u,normalizeFieldsConfig:f}=j({onError:p,isAuth:t,renderSignIn:o,routeCustomerOrderDetails:a,routeOrderDetails:i});return c("div",{className:D(["dropin-order-search",e]),children:c(X,{onSubmit:m,loading:T,inLineAlert:u,fieldsConfig:f})})};export{te as OrderSearch,te as default}; +import{jsxs as v,jsx as s}from"@dropins/tools/preact-jsx-runtime.js";import{classes as D}from"@dropins/tools/lib.js";import{Card as U,InLineAlert as C,Icon as x,Button as V}from"@dropins/tools/components.js";import{F as L}from"../chunks/CustomerDetailsContent.js";import{useState as N,useCallback as R,useEffect as O,useMemo as G}from"@dropins/tools/preact-hooks.js";import*as A from"@dropins/tools/preact-compat.js";import{Text as S,useText as H}from"@dropins/tools/i18n.js";import{events as w}from"@dropins/tools/event-bus.js";import{c as I,g as k}from"../chunks/getCustomer.js";import"../chunks/fetch-graphql.js";import"@dropins/tools/fetch-graphql.js";const P=e=>A.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e},A.createElement("path",{vectorEffect:"non-scaling-stroke",fillRule:"evenodd",clipRule:"evenodd",d:"M1 20.8953L12.1922 1.5L23.395 20.8953H1ZM13.0278 13.9638L13.25 10.0377V9H11.25V10.0377L11.4722 13.9638H13.0278ZM11.2994 16V17.7509H13.2253V16H11.2994Z",fill:"currentColor"})),X=({onSubmit:e,loading:t,inLineAlert:o,fieldsConfig:a})=>v(U,{variant:"secondary",className:"dropin-order-search-form",children:[s("h2",{className:"dropin-order-search-form__title",children:s(S,{id:"Order.OrderSearchForm.title"})}),s("p",{children:s(S,{id:"Order.OrderSearchForm.description"})}),o.text?s(C,{"data-testid":"orderAlert",className:"dropin-order-search-form__alert",type:o.type,variant:"secondary",heading:o.text,icon:s(x,{source:P})}):null,s(L,{className:"dropin-order-search-form__wrapper",name:"orderSearchForm",loading:t,fieldsConfig:a,onSubmit:e,children:s("div",{className:"dropin-order-search-form__button-container",children:s(V,{className:"dropin-order-search-form__button",size:"medium",variant:"primary",type:"submit",disabled:t,children:s(S,{id:"Order.OrderSearchForm.button"})},"logIn")})})]});var h=(e=>(e.BOOLEAN="BOOLEAN",e.DATE="DATE",e.DATETIME="DATETIME",e.DROPDOWN="DROPDOWN",e.FILE="FILE",e.GALLERY="GALLERY",e.HIDDEN="HIDDEN",e.IMAGE="IMAGE",e.MEDIA_IMAGE="MEDIA_IMAGE",e.MULTILINE="MULTILINE",e.MULTISELECT="MULTISELECT",e.PRICE="PRICE",e.SELECT="SELECT",e.TEXT="TEXT",e.TEXTAREA="TEXTAREA",e.UNDEFINED="UNDEFINED",e.VISUAL="VISUAL",e.WEIGHT="WEIGHT",e.EMPTY="",e))(h||{});const B=e=>{if(!e)return null;const t=new FormData(e);if(e.querySelectorAll('input[type="checkbox"]').forEach(a=>{t.has(a.name)||t.set(a.name,"false"),a.checked&&t.set(a.name,"true")}),t&&typeof t.entries=="function"){const a=t.entries();if(a&&typeof a[Symbol.iterator]=="function")return JSON.parse(JSON.stringify(Object.fromEntries(a)))||{}}return{}},d=(e,t)=>{if(typeof e!="function")return;const o=e();if(!t||Object.keys(t).length===0){window.location.href=o;return}const a=new URLSearchParams;Object.entries(t).forEach(([p,m])=>{a.append(p,String(m))});const c=o.includes("?")?"&":"?";window.location.href=`${o}${c}${a.toString()}`},M=e=>{try{return new URL(window.location.href).searchParams.get(e)}catch{return null}},j=({onError:e,isAuth:t,renderSignIn:o,routeCustomerOrderDetails:a,routeOrderDetails:c})=>{const[p,m]=N({text:"",type:"success"}),[T,u]=N(!1),l=H({invalidSearch:"Order.Errors.invalidSearch",email:"Order.OrderSearchForm.email",postcode:"Order.OrderSearchForm.postcode",number:"Order.OrderSearchForm.orderNumber"}),y=R(async r=>{const f=M("orderRef"),i=f&&f.length>20;if(t&&r&&r.email){const n=await I();(n==null?void 0:n.email)===r.email?d(a,{orderRef:r==null?void 0:r.number}):i||d(c,{orderRef:r.token})}else i||d(c,{orderRef:r==null?void 0:r.token})},[t,a,c]);O(()=>{const r=w.on("order/data",f=>{y(f)},{eager:!0});return()=>{r==null||r.off()}},[y]),O(()=>{const r=M("orderRef"),f=r&&r.length>20?r:null;r&&(f?d(c,{orderRef:r}):t?d(a,{orderRef:r}):o({render:!0,formValues:{number:r}}))},[t,a,c,o]);const _=G(()=>[{entityType:"CUSTOMER_ADDRESS",is_unique:!1,label:l.email,options:[],defaultValue:"",fieldType:h.TEXT,className:"",required:!0,orderNumber:1,name:"email",id:"email",code:"email"},{entityType:"CUSTOMER_ADDRESS",is_unique:!1,label:l.postcode,options:[],defaultValue:"",fieldType:h.TEXT,className:"",required:!0,orderNumber:2,name:"postcode",id:"postcode",code:"postcode"},{entityType:"CUSTOMER_ADDRESS",is_unique:!1,label:l.number,options:[],defaultValue:"",fieldType:h.TEXT,className:"",required:!0,orderNumber:3,name:"number",id:"number",code:"number"}],[l]);return{onSubmit:R(async(r,f)=>{if(!f)return null;u(!0);const i=B(r.target);await k(i).then(n=>{n||m({text:l.invalidSearch,type:"warning"}),w.emit("order/data",n)}).catch(async n=>{var g;let b=!0;e==null||e({error:n.message});const E=await I();(E==null?void 0:E.email)===(i==null?void 0:i.email)?d(a,i.number):b=o==null?void 0:o({render:(g=n==null?void 0:n.message)==null?void 0:g.includes("Please login to view the order."),formValues:i}),b&&m({text:n.message,type:"warning"})}).finally(()=>{u(!1)})},[e,o,a,l]),inLineAlert:p,loading:T,normalizeFieldsConfig:_}},te=({className:e,isAuth:t,renderSignIn:o,routeCustomerOrderDetails:a,routeOrderDetails:c,onError:p})=>{const{onSubmit:m,loading:T,inLineAlert:u,normalizeFieldsConfig:l}=j({onError:p,isAuth:t,renderSignIn:o,routeCustomerOrderDetails:a,routeOrderDetails:c});return s("div",{className:D(["dropin-order-search",e]),children:s(X,{onSubmit:m,loading:T,inLineAlert:u,fieldsConfig:l})})};export{te as OrderSearch,te as default}; diff --git a/scripts/configs.js b/scripts/configs.js index e2bc42c49e..aa5e5f21d4 100644 --- a/scripts/configs.js +++ b/scripts/configs.js @@ -1,6 +1,4 @@ -/* eslint-disable operator-linebreak */ -/* eslint-disable quotes */ -const ALLOWED_CONFIGS = ["prod", "stage", "dev"]; +const ALLOWED_CONFIGS = ['prod', 'stage', 'dev']; /** * This function calculates the environment in which the site is running based on the URL. @@ -11,20 +9,16 @@ const ALLOWED_CONFIGS = ["prod", "stage", "dev"]; */ export const calcEnvironment = () => { const { host, href } = window.location; - let environment = "prod"; - if (href.includes(".aem.page") || host.includes("staging")) { - environment = "stage"; + let environment = 'prod'; + if (href.includes('.aem.page') || host.includes('staging')) { + environment = 'stage'; } - if (href.includes("localhost")) { - environment = "dev"; + if (href.includes('localhost')) { + environment = 'dev'; } - const environmentFromConfig = window.sessionStorage.getItem("environment"); - if ( - environmentFromConfig && - ALLOWED_CONFIGS.includes(environmentFromConfig) && - environment !== "prod" - ) { + const environmentFromConfig = window.sessionStorage.getItem('environment'); + if (environmentFromConfig && ALLOWED_CONFIGS.includes(environmentFromConfig) && environment !== 'prod') { return environmentFromConfig; } @@ -33,8 +27,8 @@ export const calcEnvironment = () => { function buildConfigURL(environment) { const env = environment || calcEnvironment(); - let fileName = "configs.json?sheet=prod"; - if (env !== "prod") { + let fileName = 'configs.json?sheet=prod'; + if (env !== 'prod') { fileName = `configs-${env}.json`; } const configURL = new URL(`${window.location.origin}/${fileName}`); @@ -66,21 +60,15 @@ export const getConfigValue = async (configParam, environment) => { const env = environment || calcEnvironment(); const configJSON = await getConfigForEnvironment(env); const configElements = JSON.parse(configJSON).data; - - if (configParam === "commerce-core-endpoint") { - // return "https://mcprod.aemshop.net/graphql"; - return "https://mcstaging.aemshop.net/graphql"; - } - return configElements.find((c) => c.key === configParam)?.value; }; export const getCookie = (cookieName) => { - const cookies = document.cookie.split(";"); + const cookies = document.cookie.split(';'); let foundValue; cookies.forEach((cookie) => { - const [name, value] = cookie.trim().split("="); + const [name, value] = cookie.trim().split('='); if (name === cookieName) { foundValue = decodeURIComponent(value); } diff --git a/scripts/dropins.js b/scripts/dropins.js index 172f02e4dd..641359cdb7 100644 --- a/scripts/dropins.js +++ b/scripts/dropins.js @@ -1,34 +1,29 @@ -/* eslint-disable operator-linebreak */ -/* eslint-disable no-lonely-if */ -/* eslint-disable no-console */ -/* eslint-disable quotes */ /* eslint-disable import/no-unresolved */ // Drop-in Tools -import { events } from "@dropins/tools/event-bus.js"; +import { events } from '@dropins/tools/event-bus.js'; import { removeFetchGraphQlHeader, setEndpoint, setFetchGraphQlHeader, -} from "@dropins/tools/fetch-graphql.js"; -import { initializers, Initializer } from "@dropins/tools/initializer.js"; +} from '@dropins/tools/fetch-graphql.js'; +import { initializers, Initializer } from '@dropins/tools/initializer.js'; // Drop-ins -import * as authApi from "@dropins/storefront-auth/api.js"; -import * as cartApi from "@dropins/storefront-cart/api.js"; -import * as orderApi from "@dropins/storefront-order/api.js"; +import * as authApi from '@dropins/storefront-auth/api.js'; +import * as cartApi from '@dropins/storefront-cart/api.js'; +import * as orderApi from '@dropins/storefront-order/api.js'; // Recaptcha -import * as recaptcha from "@dropins/tools/recaptcha.js"; +import * as recaptcha from '@dropins/tools/recaptcha.js'; // Libs -import { getConfigValue, getCookie } from "./configs.js"; -import { getMetadata } from "./aem.js"; +import { getConfigValue, getCookie } from './configs.js'; +import { getMetadata } from './aem.js'; -export const getUserTokenCookie = () => getCookie("auth_dropin_user_token"); +export const getUserTokenCookie = () => getCookie('auth_dropin_user_token'); -const setupInitialHandlers = (orderRef) => { - console.log("orderRef", orderRef); +const helderInitializers = (orderRef) => { initializers.register(orderApi.initialize, { orderRef, }); @@ -41,36 +36,32 @@ const redirectTo = (path) => { const handleUserOrdersRedirects = () => { // Get current page template metadata const currentUrl = new URL(window.location.href); - const templateMeta = getMetadata("template"); - const isOrderPage = templateMeta.includes("Order"); - const isAccountPage = currentUrl.pathname.includes("/customer"); - const isAuthenticated = !!getCookie("auth_dropin_user_token") ?? false; + const templateMeta = getMetadata('template'); + const isOrderPage = templateMeta.includes('Order'); + const isAccountPage = currentUrl.pathname.includes('/customer'); + const isAuthenticated = !!getCookie('auth_dropin_user_token') ?? false; - const orderRef = currentUrl.searchParams.get("orderRef"); + const orderRef = currentUrl.searchParams.get('orderRef'); const isToken = orderRef && orderRef.length > 20 ? orderRef : null; - const ORDER_STATUS_PATH = "/order-status"; - const ORDER_DETAILS_PATH = "/order-details"; - const CUSTOMER_ORDER_DETAILS_PATH = "/customer/order-details"; - const CUSTOMER_ORDERS_PATH = "/customer/orders"; + const ORDER_STATUS_PATH = '/order-status'; + const ORDER_DETAILS_PATH = '/order-details'; + const CUSTOMER_ORDER_DETAILS_PATH = '/customer/order-details'; + const CUSTOMER_ORDERS_PATH = '/customer/orders'; const ORDER_REF_URL_QUERY = `?orderRef=${orderRef}`; if (isOrderPage) { - console.log("top"); - console.log("isOrderPage", isOrderPage); let targetPath = null; if (currentUrl.pathname.includes(CUSTOMER_ORDERS_PATH)) { return; } - events.on("order/error", ({ error }) => { + events.on('order/error', ({ error }) => { const defaultErrorMessage = "We couldn't locate an order with the information provided."; - console.log("error", error); - if (error.includes(defaultErrorMessage)) { - window.location.href = `${ORDER_STATUS_PATH}`; + window.location.href = `${ORDER_STATUS_PATH}${ORDER_REF_URL_QUERY}`; } else if (isAuthenticated) { window.location.href = `${CUSTOMER_ORDERS_PATH}`; } else { @@ -85,23 +76,19 @@ const handleUserOrdersRedirects = () => { if (isToken) { targetPath = `${ORDER_DETAILS_PATH}${ORDER_REF_URL_QUERY}`; } else { - setupInitialHandlers(orderRef); + helderInitializers(orderRef); } } else if (isToken) { - setupInitialHandlers(orderRef); + helderInitializers(orderRef); } else { targetPath = `${CUSTOMER_ORDER_DETAILS_PATH}${ORDER_REF_URL_QUERY}`; } + } else if (!orderRef) { + targetPath = ORDER_STATUS_PATH; + } else if (isToken) { + helderInitializers(orderRef); } else { - if (!orderRef) { - targetPath = `${ORDER_STATUS_PATH}`; - } else { - if (isToken) { - setupInitialHandlers(orderRef); - } else { - targetPath = `${ORDER_STATUS_PATH}${ORDER_REF_URL_QUERY}`; - } - } + targetPath = `${ORDER_STATUS_PATH}${ORDER_REF_URL_QUERY}`; } if (targetPath) { @@ -114,17 +101,17 @@ const handleUserOrdersRedirects = () => { const setAuthHeaders = (state) => { if (state) { const token = getUserTokenCookie(); - setFetchGraphQlHeader("Authorization", `Bearer ${token}`); + setFetchGraphQlHeader('Authorization', `Bearer ${token}`); } else { - removeFetchGraphQlHeader("Authorization"); + removeFetchGraphQlHeader('Authorization'); } }; const persistCartDataInSession = (data) => { if (data?.id) { - sessionStorage.setItem("DROPINS_CART_ID", data.id); + sessionStorage.setItem('DROPINS_CART_ID', data.id); } else { - sessionStorage.removeItem("DROPINS_CART_ID"); + sessionStorage.removeItem('DROPINS_CART_ID'); } }; @@ -135,13 +122,13 @@ const initialize = new Initializer({ // set auth headers setAuthHeaders(!!token); // emit authenticated event if token has changed - events.emit("authenticated", !!token); + events.emit('authenticated', !!token); }, listeners: () => [ // Set auth headers on authenticated event - events.on("authenticated", setAuthHeaders), + events.on('authenticated', setAuthHeaders), // Cache cart data in session storage - events.on("cart/data", persistCartDataInSession, { eager: true }), + events.on('cart/data', persistCartDataInSession, { eager: true }), ], }); @@ -151,15 +138,13 @@ export default async function initializeDropins() { initializers.register(authApi.initialize, {}); initializers.register(cartApi.initialize, {}); - console.log("-------------------------------"); handleUserOrdersRedirects(); - console.log("-------------------------------)"); const mount = async () => { // Event Bus Logger events.enableLogger(true); // Set Fetch Endpoint (Global) - setEndpoint(await getConfigValue("commerce-core-endpoint")); + setEndpoint(await getConfigValue('commerce-core-endpoint')); // Recaptcha recaptcha.setConfig(); // Mount all registered drop-ins @@ -167,6 +152,6 @@ export default async function initializeDropins() { }; // Mount Drop-ins - window.addEventListener("pageshow", mount); - document.addEventListener("prerenderingchange", mount); + window.addEventListener('pageshow', mount); + document.addEventListener('prerenderingchange', mount); }