@dropins/storefront-checkout 2.2.0-alpha4 → 2.2.0-beta2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chunks/PaymentOnAccount2.js +1 -1
- package/chunks/PaymentOnAccount2.js.map +1 -1
- package/chunks/fetch-graphql.js +2 -2
- package/chunks/fetch-graphql.js.map +1 -1
- package/chunks/setGuestEmailOnCart.js +1 -1
- package/chunks/setShippingAddress.js +3 -3
- package/chunks/synchronizeCheckout.js +2 -2
- package/chunks/synchronizeCheckout.js.map +1 -1
- package/containers/BillToShippingAddress.js +1 -1
- package/containers/BillToShippingAddress.js.map +1 -1
- package/containers/PaymentMethods.js +1 -1
- package/containers/PaymentMethods.js.map +1 -1
- package/containers/ShippingMethods.js +1 -1
- package/containers/ShippingMethods.js.map +1 -1
- package/data/models/cart.d.ts +1 -0
- package/data/models/quote.d.ts +1 -0
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
/*! Copyright 2025 Adobe
|
|
2
2
|
All Rights Reserved. */
|
|
3
|
-
import{jsxs as x,jsx as n}from"@dropins/tools/preact-jsx-runtime.js";import{useState as f,useCallback as b,useEffect as k}from"@dropins/tools/preact-compat.js";import{W as
|
|
3
|
+
import{jsxs as x,jsx as n}from"@dropins/tools/preact-jsx-runtime.js";import{useState as f,useCallback as b,useEffect as k}from"@dropins/tools/preact-compat.js";import{W as T}from"./ConditionalWrapper.js";/* empty css */import{Skeleton as V,SkeletonRow as A,Price as p,Field as q,Input as F,InLineAlert as S}from"@dropins/tools/components.js";import{getPriceFormatter as y,classes as H}from"@dropins/tools/lib.js";import{useText as j,Text as w}from"@dropins/tools/i18n.js";import{s as g}from"./fetch-graphql.js";import{events as I}from"@dropins/tools/event-bus.js";import{g as Q}from"./getCompanyCredit.js";const $=()=>x(V,{"data-testid":"payment-on-account-skeleton",children:[n(A,{fullWidth:!0,size:"medium"}),n(A,{fullWidth:!0,size:"medium"})]}),B=(a,c)=>{if(!(a!=null&&a.availableCredit)||!c)return null;const l=a.availableCredit.value,e=c.value-l;return e<=0?null:{value:e,currency:a.availableCredit.currency}},D=({className:a,referenceNumber:c="",onReferenceNumberChange:l,onReferenceNumberBlur:h,companyCredit:e=null,totalAmount:s=null,...v})=>{const u=B(e,s),m=e==null?void 0:e.availableCredit,d=y({currency:(s==null?void 0:s.currency)??""}),r=j({referenceNumberLabel:"Checkout.PaymentOnAccount.referenceNumberLabel",referenceNumberPlaceholder:"Checkout.PaymentOnAccount.referenceNumberPlaceholder",referenceNumberHint:"Checkout.PaymentOnAccount.referenceNumberHint",availableCreditLabel:"Checkout.PaymentOnAccount.availableCreditLabel",exceedLimitError:"Checkout.PaymentOnAccount.exceedLimitError",exceedLimitWarning:u?n(w,{fields:{creditLimit:d.format((m==null?void 0:m.value)??0),exceededAmount:d.format((u==null?void 0:u.value)??0)},id:"Checkout.PaymentOnAccount.exceedLimitWarning"}):""});return n("div",{className:"checkout-payment-on-account","data-testid":"checkout-payment-on-account",children:x("form",{...v,noValidate:!0,className:H(["checkout-payment-on-account__form",a]),"data-testid":"checkout-payment-on-account-form",name:"checkout-payment-on-account__form",children:[e&&e.availableCredit&&x("div",{className:"checkout-payment-on-account__credit","data-testid":"checkout-payment-on-account-credit",children:[n("span",{className:"checkout-payment-on-account__credit-label",children:r.availableCreditLabel}),n("span",{className:"checkout-payment-on-account__credit-amount",children:n(p,{amount:e==null?void 0:e.availableCredit.value,currency:e==null?void 0:e.availableCredit.currency})})]}),n(q,{hint:r.referenceNumberHint,children:n(F,{"aria-label":r.referenceNumberLabel,floatingLabel:r.referenceNumberLabel,id:"reference-number",name:"reference-number",placeholder:r.referenceNumberPlaceholder,type:"text",value:c,onBlur:h,onChange:l})}),u&&n("div",{className:"checkout-payment-on-account__exceed-message","data-testid":"checkout-payment-on-account-exceed-message",children:n(S,{heading:e!=null&&e.exceedLimit?r.exceedLimitWarning:r.exceedLimitError,type:e!=null&&e.exceedLimit?"warning":"error",variant:"primary"})})]})})},G=T(D,$),te=({initialReferenceNumber:a="",onReferenceNumberChange:c,onReferenceNumberBlur:l,...h})=>{const[e,s]=f(!1),[v,u]=f(null),[m,d]=f(null),[r,W]=f(a),L=g.authenticated,P=!!g.cartId,N=!!g.quoteId,_=b(t=>{var o;d(((o=t==null?void 0:t.total)==null?void 0:o.includingTax)||null)},[]),O=b(t=>{var o,i;d(((i=(o=t==null?void 0:t.quote)==null?void 0:o.prices)==null?void 0:i.grandTotal)||null)},[]),z=b(t=>{const i=t.target.value;W(i),c==null||c(i)},[c]),E=b(t=>{const i=t.target.value;l==null||l(i)},[l]);return k(()=>{if(!P)return;const t=I.on("cart/data",_,{eager:!0});return()=>{t==null||t.off()}},[P,_]),k(()=>{if(!N)return;const t=I.on("quote-management/quote-data",O,{eager:!0});return()=>{t==null||t.off()}},[N,O]),k(()=>{L&&Q().then(t=>{u(t)}).catch(t=>{console.error("Failed to fetch company credit:",t),u(null)}).finally(()=>{s(!0)})},[L]),n("div",{...h,children:n(G,{companyCredit:v,initialized:e,referenceNumber:r,totalAmount:m,onReferenceNumberBlur:E,onReferenceNumberChange:z})})};export{te as P};
|
|
4
4
|
//# sourceMappingURL=PaymentOnAccount2.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PaymentOnAccount2.js","sources":["/@dropins/storefront-checkout/src/components/PaymentOnAccount/PaymentOnAccountSkeleton.tsx","/@dropins/storefront-checkout/src/components/PaymentOnAccount/PaymentOnAccount.tsx","/@dropins/storefront-checkout/src/containers/PaymentOnAccount/PaymentOnAccount.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { FunctionComponent } from 'preact';\nimport { Skeleton, SkeletonRow } from '@adobe-commerce/elsie/components';\n\nexport const PaymentOnAccountSkeleton: FunctionComponent = () => {\n return (\n <Skeleton data-testid=\"payment-on-account-skeleton\">\n <SkeletonRow fullWidth={true} size=\"medium\" />\n <SkeletonRow fullWidth={true} size=\"medium\" />\n </Skeleton>\n );\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { WithConditionals } from '@/checkout/components/ConditionalWrapper/ConditionalWrapper';\nimport '@/checkout/components/PaymentOnAccount/PaymentOnAccount.css';\nimport { PaymentOnAccountSkeleton } from '@/checkout/components/PaymentOnAccount/PaymentOnAccountSkeleton';\nimport { Money } from '@/checkout/data/models';\nimport {\n Field,\n InLineAlert,\n Input,\n Price,\n} from '@adobe-commerce/elsie/components';\nimport { Text, useText } from '@adobe-commerce/elsie/i18n';\nimport { classes, getPriceFormatter } from '@adobe-commerce/elsie/lib';\nimport { FunctionComponent } from 'preact';\nimport { HTMLAttributes } from 'preact/compat';\n\nexport type CompanyCredit = {\n availableCredit: Money;\n exceedLimit?: boolean;\n};\n\nexport interface PaymentOnAccountProps extends HTMLAttributes<HTMLFormElement> {\n referenceNumber?: string;\n onReferenceNumberChange?: (event: Event) => void;\n onReferenceNumberBlur?: (event: Event) => void;\n companyCredit?: CompanyCredit | null;\n totalAmount?: Money | null;\n}\n\nconst calculateExceededAmount = (\n companyCredit: CompanyCredit | null,\n totalAmount: Money | null\n): Money | null => {\n if (!companyCredit?.availableCredit || !totalAmount) return null;\n\n const availableValue = companyCredit.availableCredit.value;\n const cartValue = totalAmount.value;\n const exceededValue = cartValue - availableValue;\n\n if (exceededValue <= 0) return null;\n\n return {\n value: exceededValue,\n currency: companyCredit.availableCredit.currency,\n };\n};\n\nconst PaymentOnAccountComponent: FunctionComponent<PaymentOnAccountProps> = ({\n className,\n referenceNumber = '',\n onReferenceNumberChange,\n onReferenceNumberBlur,\n companyCredit = null,\n totalAmount = null,\n ...props\n}) => {\n const exceededAmount = calculateExceededAmount(companyCredit, totalAmount);\n const creditLimit = companyCredit?.availableCredit;\n\n const priceFormatter = getPriceFormatter({\n currency: totalAmount?.currency ?? '',\n });\n\n const translations = useText({\n referenceNumberLabel: 'Checkout.PaymentOnAccount.referenceNumberLabel',\n referenceNumberPlaceholder:\n 'Checkout.PaymentOnAccount.referenceNumberPlaceholder',\n referenceNumberHint: 'Checkout.PaymentOnAccount.referenceNumberHint',\n availableCreditLabel: 'Checkout.PaymentOnAccount.availableCreditLabel',\n exceedLimitError: 'Checkout.PaymentOnAccount.exceedLimitError',\n exceedLimitWarning: (exceededAmount ? (\n <Text\n fields={{\n creditLimit: priceFormatter.format(creditLimit?.value ?? 0),\n exceededAmount: priceFormatter.format(exceededAmount?.value ?? 0),\n }}\n id=\"Checkout.PaymentOnAccount.exceedLimitWarning\"\n />\n ) : (\n ''\n )) as any,\n });\n\n console.debug('Translations:', translations);\n\n return (\n <div\n className=\"checkout-payment-on-account\"\n data-testid=\"checkout-payment-on-account\"\n >\n <form\n {...props}\n noValidate\n className={classes(['checkout-payment-on-account__form', className])}\n data-testid=\"checkout-payment-on-account-form\"\n name=\"checkout-payment-on-account__form\"\n >\n {companyCredit && companyCredit.availableCredit && (\n <div\n className=\"checkout-payment-on-account__credit\"\n data-testid=\"checkout-payment-on-account-credit\"\n >\n <span className=\"checkout-payment-on-account__credit-label\">\n {translations.availableCreditLabel}\n </span>\n <span className=\"checkout-payment-on-account__credit-amount\">\n <Price\n amount={companyCredit?.availableCredit.value}\n currency={companyCredit?.availableCredit.currency}\n />\n </span>\n </div>\n )}\n\n <Field hint={translations.referenceNumberHint}>\n <Input\n aria-label={translations.referenceNumberLabel}\n floatingLabel={translations.referenceNumberLabel}\n id=\"reference-number\"\n name=\"reference-number\"\n placeholder={translations.referenceNumberPlaceholder}\n type=\"text\"\n value={referenceNumber}\n onBlur={onReferenceNumberBlur}\n onChange={onReferenceNumberChange}\n />\n </Field>\n\n {exceededAmount && (\n <div\n className=\"checkout-payment-on-account__exceed-message\"\n data-testid=\"checkout-payment-on-account-exceed-message\"\n >\n <InLineAlert\n heading={\n companyCredit?.exceedLimit\n ? translations.exceedLimitWarning\n : translations.exceedLimitError\n }\n type={companyCredit?.exceedLimit ? 'warning' : 'error'}\n variant=\"primary\"\n />\n </div>\n )}\n </form>\n </div>\n );\n};\n\nexport const PaymentOnAccount = WithConditionals(\n PaymentOnAccountComponent,\n PaymentOnAccountSkeleton\n);\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport {\n HTMLAttributes,\n useCallback,\n useEffect,\n useState,\n} from 'preact/compat';\nimport { Container } from '@adobe-commerce/elsie/lib';\nimport { PaymentOnAccount as PaymentOnAccountComponent } from '@/checkout/components/PaymentOnAccount';\nimport { Money, CompanyCredit } from '@/checkout/data/models';\nimport { getCompanyCredit } from '@/checkout/api';\nimport { events } from '@adobe-commerce/event-bus';\nimport { state } from '@/checkout/lib';\nimport { CartModel, NegotiableQuoteModel } from '@/checkout/types/storefront';\n\nexport interface PaymentOnAccountProps extends HTMLAttributes<HTMLDivElement> {\n initialReferenceNumber?: string;\n onReferenceNumberChange?: (referenceNumber: string) => void;\n onReferenceNumberBlur?: (referenceNumber: string) => void;\n}\n\nexport const PaymentOnAccount: Container<PaymentOnAccountProps> = ({\n initialReferenceNumber = '',\n onReferenceNumberChange,\n onReferenceNumberBlur,\n ...props\n}) => {\n const [isInitialized, setIsInitialized] = useState(false);\n const [companyCredit, setCompanyCredit] = useState<CompanyCredit | null>(\n null\n );\n const [totalAmount, setTotalAmount] = useState<Money | null>(null);\n const [referenceNumber, setReferenceNumber] = useState<string>(\n initialReferenceNumber\n );\n\n const isAuthenticated = state.authenticated;\n const hasCartRef = Boolean(state.cartId);\n const hasQuoteRef = Boolean(state.quoteId);\n\n const handleCartData = useCallback((data: CartModel | null) => {\n setTotalAmount(data?.total?.includingTax || null);\n }, []);\n\n const handleQuoteData = useCallback(\n (data: { quote: NegotiableQuoteModel }) => {\n setTotalAmount(data?.quote?.prices?.grandTotal || null);\n },\n []\n );\n\n const handleReferenceNumberChange = useCallback(\n (event: Event) => {\n const target = event.target as HTMLInputElement;\n const value = target.value;\n setReferenceNumber(value);\n onReferenceNumberChange?.(value);\n },\n [onReferenceNumberChange]\n );\n\n const handleReferenceNumberBlur = useCallback(\n (event: Event) => {\n const target = event.target as HTMLInputElement;\n const value = target.value;\n onReferenceNumberBlur?.(value);\n },\n [onReferenceNumberBlur]\n );\n\n useEffect(() => {\n if (!hasCartRef) return;\n\n // @ts-ignore\n const onCartData = events.on('cart/data', handleCartData, { eager: true });\n\n return () => {\n onCartData?.off();\n };\n }, [hasCartRef, handleCartData]);\n\n useEffect(() => {\n if (!hasQuoteRef) return;\n\n const onQuoteData = events.on(\n 'quote-management/quote-data',\n handleQuoteData,\n { eager: true }\n );\n\n return () => {\n onQuoteData?.off();\n };\n }, [hasQuoteRef, handleQuoteData]);\n\n useEffect(() => {\n if (!isAuthenticated) return;\n\n getCompanyCredit()\n .then((credit) => {\n setCompanyCredit(credit);\n })\n .catch((error) => {\n console.error('Failed to fetch company credit:', error);\n setCompanyCredit(null);\n })\n .finally(() => {\n setIsInitialized(true);\n });\n }, [isAuthenticated]);\n\n return (\n <div {...props}>\n <PaymentOnAccountComponent\n companyCredit={companyCredit}\n initialized={isInitialized}\n referenceNumber={referenceNumber}\n totalAmount={totalAmount}\n onReferenceNumberBlur={handleReferenceNumberBlur}\n onReferenceNumberChange={handleReferenceNumberChange}\n />\n </div>\n );\n};\n"],"names":["PaymentOnAccountSkeleton","jsxs","Skeleton","jsx","SkeletonRow","calculateExceededAmount","companyCredit","totalAmount","availableValue","exceededValue","PaymentOnAccountComponent","className","referenceNumber","onReferenceNumberChange","onReferenceNumberBlur","props","exceededAmount","creditLimit","priceFormatter","getPriceFormatter","translations","useText","Text","classes","Price","Field","Input","InLineAlert","PaymentOnAccount","WithConditionals","initialReferenceNumber","isInitialized","setIsInitialized","useState","setCompanyCredit","setTotalAmount","setReferenceNumber","isAuthenticated","state","hasCartRef","hasQuoteRef","handleCartData","useCallback","data","_a","handleQuoteData","_b","handleReferenceNumberChange","event","value","handleReferenceNumberBlur","useEffect","onCartData","events","onQuoteData","getCompanyCredit","credit","error"],"mappings":"6mBAoBO,MAAMA,EAA8C,IAEvDC,EAACC,EAAS,CAAA,cAAY,8BACpB,SAAA,CAAAC,EAACC,EAAY,CAAA,UAAW,GAAM,KAAK,SAAS,EAC3CD,EAAAC,EAAA,CAAY,UAAW,GAAM,KAAK,QAAS,CAAA,CAAA,EAC9C,ECoBEC,EAA0B,CAC9BC,EACAC,IACiB,CACjB,GAAI,EAACD,GAAA,MAAAA,EAAe,kBAAmB,CAACC,EAAoB,OAAA,KAEtD,MAAAC,EAAiBF,EAAc,gBAAgB,MAE/CG,EADYF,EAAY,MACIC,EAE9B,OAAAC,GAAiB,EAAU,KAExB,CACL,MAAOA,EACP,SAAUH,EAAc,gBAAgB,QAC1C,CACF,EAEMI,EAAsE,CAAC,CAC3E,UAAAC,EACA,gBAAAC,EAAkB,GAClB,wBAAAC,EACA,sBAAAC,EACA,cAAA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,EACA,CAACnC,CAAqB,CACxB,EAEA,OAAAqC,EAAU,IAAM,CACd,GAAI,CAACZ,EAAY,OAGX,MAAAa,EAAaC,EAAO,GAAG,YAAaZ,EAAgB,CAAE,MAAO,GAAM,EAEzE,MAAO,IAAM,CACXW,GAAA,MAAAA,EAAY,KACd,CAAA,EACC,CAACb,EAAYE,CAAc,CAAC,EAE/BU,EAAU,IAAM,CACd,GAAI,CAACX,EAAa,OAElB,MAAMc,EAAcD,EAAO,GACzB,8BACAR,EACA,CAAE,MAAO,EAAK,CAChB,EAEA,MAAO,IAAM,CACXS,GAAA,MAAAA,EAAa,KACf,CAAA,EACC,CAACd,EAAaK,CAAe,CAAC,EAEjCM,EAAU,IAAM,CACTd,GAEYkB,EAAA,EACd,KAAMC,GAAW,CAChBtB,EAAiBsB,CAAM,CAAA,CACxB,EACA,MAAOC,GAAU,CACR,QAAA,MAAM,kCAAmCA,CAAK,EACtDvB,EAAiB,IAAI,CAAA,CACtB,EACA,QAAQ,IAAM,CACbF,EAAiB,EAAI,CAAA,CACtB,CAAA,EACF,CAACK,CAAe,CAAC,EAGlBlC,EAAC,MAAK,CAAA,GAAGY,EACP,SAAAZ,EAACO,EAAA,CACC,cAAAJ,EACA,YAAayB,EACb,gBAAAnB,EACA,YAAAL,EACA,sBAAuB2C,EACvB,wBAAyBH,CAAA,CAAA,EAE7B,CAEJ"}
|
|
1
|
+
{"version":3,"file":"PaymentOnAccount2.js","sources":["/@dropins/storefront-checkout/src/components/PaymentOnAccount/PaymentOnAccountSkeleton.tsx","/@dropins/storefront-checkout/src/components/PaymentOnAccount/PaymentOnAccount.tsx","/@dropins/storefront-checkout/src/containers/PaymentOnAccount/PaymentOnAccount.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { FunctionComponent } from 'preact';\nimport { Skeleton, SkeletonRow } from '@adobe-commerce/elsie/components';\n\nexport const PaymentOnAccountSkeleton: FunctionComponent = () => {\n return (\n <Skeleton data-testid=\"payment-on-account-skeleton\">\n <SkeletonRow fullWidth={true} size=\"medium\" />\n <SkeletonRow fullWidth={true} size=\"medium\" />\n </Skeleton>\n );\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { WithConditionals } from '@/checkout/components/ConditionalWrapper/ConditionalWrapper';\nimport '@/checkout/components/PaymentOnAccount/PaymentOnAccount.css';\nimport { PaymentOnAccountSkeleton } from '@/checkout/components/PaymentOnAccount/PaymentOnAccountSkeleton';\nimport { Money } from '@/checkout/data/models';\nimport {\n Field,\n InLineAlert,\n Input,\n Price,\n} from '@adobe-commerce/elsie/components';\nimport { Text, useText } from '@adobe-commerce/elsie/i18n';\nimport { classes, getPriceFormatter } from '@adobe-commerce/elsie/lib';\nimport { FunctionComponent } from 'preact';\nimport { HTMLAttributes } from 'preact/compat';\n\nexport type CompanyCredit = {\n availableCredit: Money;\n exceedLimit?: boolean;\n};\n\nexport interface PaymentOnAccountProps extends HTMLAttributes<HTMLFormElement> {\n referenceNumber?: string;\n onReferenceNumberChange?: (event: Event) => void;\n onReferenceNumberBlur?: (event: Event) => void;\n companyCredit?: CompanyCredit | null;\n totalAmount?: Money | null;\n}\n\nconst calculateExceededAmount = (\n companyCredit: CompanyCredit | null,\n totalAmount: Money | null\n): Money | null => {\n if (!companyCredit?.availableCredit || !totalAmount) return null;\n\n const availableValue = companyCredit.availableCredit.value;\n const cartValue = totalAmount.value;\n const exceededValue = cartValue - availableValue;\n\n if (exceededValue <= 0) return null;\n\n return {\n value: exceededValue,\n currency: companyCredit.availableCredit.currency,\n };\n};\n\nconst PaymentOnAccountComponent: FunctionComponent<PaymentOnAccountProps> = ({\n className,\n referenceNumber = '',\n onReferenceNumberChange,\n onReferenceNumberBlur,\n companyCredit = null,\n totalAmount = null,\n ...props\n}) => {\n const exceededAmount = calculateExceededAmount(companyCredit, totalAmount);\n const creditLimit = companyCredit?.availableCredit;\n\n const priceFormatter = getPriceFormatter({\n currency: totalAmount?.currency ?? '',\n });\n\n const translations = useText({\n referenceNumberLabel: 'Checkout.PaymentOnAccount.referenceNumberLabel',\n referenceNumberPlaceholder:\n 'Checkout.PaymentOnAccount.referenceNumberPlaceholder',\n referenceNumberHint: 'Checkout.PaymentOnAccount.referenceNumberHint',\n availableCreditLabel: 'Checkout.PaymentOnAccount.availableCreditLabel',\n exceedLimitError: 'Checkout.PaymentOnAccount.exceedLimitError',\n exceedLimitWarning: (exceededAmount ? (\n <Text\n fields={{\n creditLimit: priceFormatter.format(creditLimit?.value ?? 0),\n exceededAmount: priceFormatter.format(exceededAmount?.value ?? 0),\n }}\n id=\"Checkout.PaymentOnAccount.exceedLimitWarning\"\n />\n ) : (\n ''\n )) as any,\n });\n\n return (\n <div\n className=\"checkout-payment-on-account\"\n data-testid=\"checkout-payment-on-account\"\n >\n <form\n {...props}\n noValidate\n className={classes(['checkout-payment-on-account__form', className])}\n data-testid=\"checkout-payment-on-account-form\"\n name=\"checkout-payment-on-account__form\"\n >\n {companyCredit && companyCredit.availableCredit && (\n <div\n className=\"checkout-payment-on-account__credit\"\n data-testid=\"checkout-payment-on-account-credit\"\n >\n <span className=\"checkout-payment-on-account__credit-label\">\n {translations.availableCreditLabel}\n </span>\n <span className=\"checkout-payment-on-account__credit-amount\">\n <Price\n amount={companyCredit?.availableCredit.value}\n currency={companyCredit?.availableCredit.currency}\n />\n </span>\n </div>\n )}\n\n <Field hint={translations.referenceNumberHint}>\n <Input\n aria-label={translations.referenceNumberLabel}\n floatingLabel={translations.referenceNumberLabel}\n id=\"reference-number\"\n name=\"reference-number\"\n placeholder={translations.referenceNumberPlaceholder}\n type=\"text\"\n value={referenceNumber}\n onBlur={onReferenceNumberBlur}\n onChange={onReferenceNumberChange}\n />\n </Field>\n\n {exceededAmount && (\n <div\n className=\"checkout-payment-on-account__exceed-message\"\n data-testid=\"checkout-payment-on-account-exceed-message\"\n >\n <InLineAlert\n heading={\n companyCredit?.exceedLimit\n ? translations.exceedLimitWarning\n : translations.exceedLimitError\n }\n type={companyCredit?.exceedLimit ? 'warning' : 'error'}\n variant=\"primary\"\n />\n </div>\n )}\n </form>\n </div>\n );\n};\n\nexport const PaymentOnAccount = WithConditionals(\n PaymentOnAccountComponent,\n PaymentOnAccountSkeleton\n);\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport {\n HTMLAttributes,\n useCallback,\n useEffect,\n useState,\n} from 'preact/compat';\nimport { Container } from '@adobe-commerce/elsie/lib';\nimport { PaymentOnAccount as PaymentOnAccountComponent } from '@/checkout/components/PaymentOnAccount';\nimport { Money, CompanyCredit } from '@/checkout/data/models';\nimport { getCompanyCredit } from '@/checkout/api';\nimport { events } from '@adobe-commerce/event-bus';\nimport { state } from '@/checkout/lib';\nimport { CartModel, NegotiableQuoteModel } from '@/checkout/types/storefront';\n\nexport interface PaymentOnAccountProps extends HTMLAttributes<HTMLDivElement> {\n initialReferenceNumber?: string;\n onReferenceNumberChange?: (referenceNumber: string) => void;\n onReferenceNumberBlur?: (referenceNumber: string) => void;\n}\n\nexport const PaymentOnAccount: Container<PaymentOnAccountProps> = ({\n initialReferenceNumber = '',\n onReferenceNumberChange,\n onReferenceNumberBlur,\n ...props\n}) => {\n const [isInitialized, setIsInitialized] = useState(false);\n const [companyCredit, setCompanyCredit] = useState<CompanyCredit | null>(\n null\n );\n const [totalAmount, setTotalAmount] = useState<Money | null>(null);\n const [referenceNumber, setReferenceNumber] = useState<string>(\n initialReferenceNumber\n );\n\n const isAuthenticated = state.authenticated;\n const hasCartRef = Boolean(state.cartId);\n const hasQuoteRef = Boolean(state.quoteId);\n\n const handleCartData = useCallback((data: CartModel | null) => {\n setTotalAmount(data?.total?.includingTax || null);\n }, []);\n\n const handleQuoteData = useCallback(\n (data: { quote: NegotiableQuoteModel }) => {\n setTotalAmount(data?.quote?.prices?.grandTotal || null);\n },\n []\n );\n\n const handleReferenceNumberChange = useCallback(\n (event: Event) => {\n const target = event.target as HTMLInputElement;\n const value = target.value;\n setReferenceNumber(value);\n onReferenceNumberChange?.(value);\n },\n [onReferenceNumberChange]\n );\n\n const handleReferenceNumberBlur = useCallback(\n (event: Event) => {\n const target = event.target as HTMLInputElement;\n const value = target.value;\n onReferenceNumberBlur?.(value);\n },\n [onReferenceNumberBlur]\n );\n\n useEffect(() => {\n if (!hasCartRef) return;\n\n // @ts-ignore\n const onCartData = events.on('cart/data', handleCartData, { eager: true });\n\n return () => {\n onCartData?.off();\n };\n }, [hasCartRef, handleCartData]);\n\n useEffect(() => {\n if (!hasQuoteRef) return;\n\n const onQuoteData = events.on(\n 'quote-management/quote-data',\n handleQuoteData,\n { eager: true }\n );\n\n return () => {\n onQuoteData?.off();\n };\n }, [hasQuoteRef, handleQuoteData]);\n\n useEffect(() => {\n if (!isAuthenticated) return;\n\n getCompanyCredit()\n .then((credit) => {\n setCompanyCredit(credit);\n })\n .catch((error) => {\n console.error('Failed to fetch company credit:', error);\n setCompanyCredit(null);\n })\n .finally(() => {\n setIsInitialized(true);\n });\n }, [isAuthenticated]);\n\n return (\n <div {...props}>\n <PaymentOnAccountComponent\n companyCredit={companyCredit}\n initialized={isInitialized}\n referenceNumber={referenceNumber}\n totalAmount={totalAmount}\n onReferenceNumberBlur={handleReferenceNumberBlur}\n onReferenceNumberChange={handleReferenceNumberChange}\n />\n </div>\n );\n};\n"],"names":["PaymentOnAccountSkeleton","jsxs","Skeleton","jsx","SkeletonRow","calculateExceededAmount","companyCredit","totalAmount","availableValue","exceededValue","PaymentOnAccountComponent","className","referenceNumber","onReferenceNumberChange","onReferenceNumberBlur","props","exceededAmount","creditLimit","priceFormatter","getPriceFormatter","translations","useText","Text","classes","Price","Field","Input","InLineAlert","PaymentOnAccount","WithConditionals","initialReferenceNumber","isInitialized","setIsInitialized","useState","setCompanyCredit","setTotalAmount","setReferenceNumber","isAuthenticated","state","hasCartRef","hasQuoteRef","handleCartData","useCallback","data","_a","handleQuoteData","_b","handleReferenceNumberChange","event","value","handleReferenceNumberBlur","useEffect","onCartData","events","onQuoteData","getCompanyCredit","credit","error"],"mappings":"6mBAoBO,MAAMA,EAA8C,IAEvDC,EAACC,EAAS,CAAA,cAAY,8BACpB,SAAA,CAAAC,EAACC,EAAY,CAAA,UAAW,GAAM,KAAK,SAAS,EAC3CD,EAAAC,EAAA,CAAY,UAAW,GAAM,KAAK,QAAS,CAAA,CAAA,EAC9C,ECoBEC,EAA0B,CAC9BC,EACAC,IACiB,CACjB,GAAI,EAACD,GAAA,MAAAA,EAAe,kBAAmB,CAACC,EAAoB,OAAA,KAEtD,MAAAC,EAAiBF,EAAc,gBAAgB,MAE/CG,EADYF,EAAY,MACIC,EAE9B,OAAAC,GAAiB,EAAU,KAExB,CACL,MAAOA,EACP,SAAUH,EAAc,gBAAgB,QAC1C,CACF,EAEMI,EAAsE,CAAC,CAC3E,UAAAC,EACA,g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AAAA,EAAwBmC,EAC1B,EACA,CAACnC,CAAqB,CACxB,EAEA,OAAAqC,EAAU,IAAM,CACd,GAAI,CAACZ,EAAY,OAGX,MAAAa,EAAaC,EAAO,GAAG,YAAaZ,EAAgB,CAAE,MAAO,GAAM,EAEzE,MAAO,IAAM,CACXW,GAAA,MAAAA,EAAY,KACd,CAAA,EACC,CAACb,EAAYE,CAAc,CAAC,EAE/BU,EAAU,IAAM,CACd,GAAI,CAACX,EAAa,OAElB,MAAMc,EAAcD,EAAO,GACzB,8BACAR,EACA,CAAE,MAAO,EAAK,CAChB,EAEA,MAAO,IAAM,CACXS,GAAA,MAAAA,EAAa,KACf,CAAA,EACC,CAACd,EAAaK,CAAe,CAAC,EAEjCM,EAAU,IAAM,CACTd,GAEYkB,EAAA,EACd,KAAMC,GAAW,CAChBtB,EAAiBsB,CAAM,CAAA,CACxB,EACA,MAAOC,GAAU,CACR,QAAA,MAAM,kCAAmCA,CAAK,EACtDvB,EAAiB,IAAI,CAAA,CACtB,EACA,QAAQ,IAAM,CACbF,EAAiB,EAAI,CAAA,CACtB,CAAA,EACF,CAACK,CAAe,CAAC,EAGlBlC,EAAC,MAAK,CAAA,GAAGY,EACP,SAAAZ,EAACO,EAAA,CACC,cAAAJ,EACA,YAAayB,EACb,gBAAAnB,EACA,YAAAL,EACA,sBAAuB2C,EACvB,wBAAyBH,CAAA,CAAA,EAE7B,CAEJ"}
|
package/chunks/fetch-graphql.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/*! Copyright 2025 Adobe
|
|
2
2
|
All Rights Reserved. */
|
|
3
|
-
import"@dropins/tools/lib.js";import{events as
|
|
3
|
+
import"@dropins/tools/lib.js";import{events as D}from"@dropins/tools/event-bus.js";import{signal as S,computed as m}from"@dropins/tools/signals.js";import{FetchGraphQL as U}from"@dropins/tools/fetch-graphql.js";const G={authenticated:!1,cartId:null,config:null,initialized:!1,quoteId:null},I=new Proxy(G,{set(e,t,s){return e[t]=s,!0},get(e,t){return e[t]}});function V(){return I.quoteId!==null}var u=(e=>(e.EXCLUDING_TAX="EXCLUDING_TAX",e.INCLUDING_EXCLUDING_TAX="INCLUDING_AND_EXCLUDING_TAX",e.INCLUDING_TAX="INCLUDING_TAX",e))(u||{}),w=(e=>(e.Updates="updates",e.Default="default",e.ShippingEstimate="shippingEstimate",e))(w||{});const d=new Map,g=new Map,c=S(new Set),E=new Map;E.set("updates",e=>{D.emit("checkout/updated",e)});async function A(e){g.set(e,!0);const t=d.get(e);let s;for(;t.length>0;){const i=t.shift();try{const r=await i.requestFn();i.resolve(r),s=r}catch(r){i.reject(r)}}g.set(e,!1);const n=new Set(c.value);n.delete(e),c.value=n;const a=E.get(e);a&&s&&a(s)}function q(e,t="default"){d.has(t)||d.set(t,[]);const s=d.get(t),n=new Promise((i,r)=>{s.push({requestFn:e,resolve:i,reject:r})}),a=new Set(c.value);return a.add(t),c.value=a,g.get(t)||A(t),n}const B=m(()=>c.value.has("updates")),$=m(()=>c.value.has("shippingEstimate")),X=["sender_email","recipient_email"];function v(e){return e.filter(t=>!t.path||!X.some(s=>{var n;return((n=t.path)==null?void 0:n.at(-1))===s}))}class T extends Error{constructor(t){super(t.map(s=>s.message).join(" ")),this.name="FetchError"}}class N extends Error{constructor(t){super(t),this.name="InvalidInput"}}class o extends N{constructor(t){super(`${t} is required.`)}}class z extends o{constructor(){super("Cart ID")}}class Y extends N{constructor(){super("Either Cart ID or Quote ID is required.")}}class J extends Error{constructor(){super("User is not authenticated")}}class K extends o{constructor(){super("Negotiable Quote ID")}}class W extends o{constructor(){super("Email")}}class Z extends o{constructor(){super("Payment method code")}}class ee extends o{constructor(){super("Shipping address")}}class te extends o{constructor(){super("Shipping method")}}class se extends o{constructor(){super("Billing address")}}class ne extends o{constructor(){super("Country Code")}}function L(e,t){return t.split(".").reduce((s,n)=>s&&s[n]!==void 0?s[n]:void 0,e)}async function M(e){const{defaultValueOnFail:t,options:s,path:n,query:a,queueName:i,transformer:r,type:p}=e;try{const l=async()=>{const{data:y,errors:C}=await P(a,{method:p==="query"?"GET":"POST",cache:p==="query"?"no-cache":void 0,...s});if(C){const _=v(C);if(_.length>0)throw new T(_)}let h=L(y,n);if(h===void 0)throw new Error(`No data found at path: ${n}`);return r?r(h):h};return p==="mutation"?await q(l,i):await l()}catch(l){if(t!==void 0)return t;throw l}}const x=`
|
|
4
4
|
query getStoreConfig {
|
|
5
5
|
storeConfig {
|
|
6
6
|
default_country
|
|
@@ -10,5 +10,5 @@ import"@dropins/tools/lib.js";import{events as y}from"@dropins/tools/event-bus.j
|
|
|
10
10
|
shopping_cart_display_shipping
|
|
11
11
|
}
|
|
12
12
|
}
|
|
13
|
-
`,F="US",f={defaultCountry:F,agreementsEnabled:!0,shoppingCartDisplaySetting:{shipping:u.EXCLUDING_TAX}},re=async()=>await M({defaultValueOnFail:f,options:{method:"GET",cache:"no-cache"},path:"storeConfig",query:x,transformer:b,type:"query"}),
|
|
13
|
+
`,F="US",f={defaultCountry:F,agreementsEnabled:!0,shoppingCartDisplaySetting:{shipping:u.EXCLUDING_TAX}},re=async()=>await M({defaultValueOnFail:f,options:{method:"GET",cache:"no-cache"},path:"storeConfig",query:x,transformer:b,type:"query"}),oe=()=>I.config;function Q(e){switch(e){case 1:return u.EXCLUDING_TAX;case 2:return u.INCLUDING_TAX;case 3:return u.INCLUDING_EXCLUDING_TAX;default:return u.EXCLUDING_TAX}}function b(e){if(!e)return f;const{default_country:t,is_checkout_agreements_enabled:s,shopping_cart_display_shipping:n}=e;return{defaultCountry:t||f.defaultCountry,agreementsEnabled:s,shoppingCartDisplaySetting:{shipping:Q(n)}}}const{setEndpoint:ae,setFetchGraphQlHeader:ie,removeFetchGraphQlHeader:ue,setFetchGraphQlHeaders:ce,fetchGraphQl:P,getConfig:le}=new U().getMethods();export{F as D,N as I,Y as M,w as Q,f as S,u as T,J as U,ae as a,ie as b,ce as c,M as d,re as e,P as f,le as g,B as h,oe as i,te as j,Z as k,se as l,$ as m,V as n,z as o,ne as p,ee as q,ue as r,I as s,W as t,K as u};
|
|
14
14
|
//# sourceMappingURL=fetch-graphql.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-graphql.js","sources":["/@dropins/storefront-checkout/src/lib/state.ts","/@dropins/storefront-checkout/src/data/models/store-config.ts","/@dropins/storefront-checkout/src/lib/enqueueRequest.ts","/@dropins/storefront-checkout/src/lib/filterControlledErrors.ts","/@dropins/storefront-checkout/src/lib/errors/customErrors.ts","/@dropins/storefront-checkout/src/lib/dispatchApiCall.ts","/@dropins/storefront-checkout/src/api/getStoreConfig/graphql/getStoreConfig.graphql.ts","/@dropins/storefront-checkout/src/api/getStoreConfig/getStoreConfig.ts","/@dropins/storefront-checkout/src/data/transforms/transform-store-config.ts","/@dropins/storefront-checkout/src/api/fetch-graphql/fetch-graphql.ts"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { StoreConfig } from '@/checkout/data/models';\n\ntype State = {\n authenticated: boolean;\n cartId?: string | null;\n config: StoreConfig | null;\n initialized: boolean;\n quoteId?: string | null;\n};\n\nconst _state: State = (() => ({\n authenticated: false,\n cartId: null,\n config: null,\n initialized: false,\n quoteId: null,\n}))();\n\n// Proxy state to allow reactivity\nexport const state = new Proxy(_state, {\n set(target, key, value) {\n // @ts-ignore\n target[key] = value;\n return true;\n },\n get(target, key) {\n return target[key as keyof State];\n },\n});\n\nexport function isQuoteCheckout(): boolean {\n return state.quoteId !== null;\n}\n\nexport function isCartCheckout(): boolean {\n return state.cartId !== null;\n}\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nexport enum TaxDisplay {\n EXCLUDING_TAX = 'EXCLUDING_TAX',\n INCLUDING_EXCLUDING_TAX = 'INCLUDING_AND_EXCLUDING_TAX',\n INCLUDING_TAX = 'INCLUDING_TAX',\n}\n\nexport interface StoreConfig {\n defaultCountry: string;\n agreementsEnabled: boolean;\n shoppingCartDisplaySetting: {\n shipping: TaxDisplay;\n };\n}\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { Cart, NegotiableQuote } from '@/checkout/data/models';\nimport {\n computed,\n ReadonlySignal,\n signal,\n} from '@adobe-commerce/elsie/lib/signals';\nimport { events } from '@adobe-commerce/event-bus';\n\nexport enum QueueName {\n Updates = 'updates',\n Default = 'default',\n ShippingEstimate = 'shippingEstimate',\n}\n\ntype Request<T> = () => Promise<T>;\ntype QueueCompletedHandler<T> = (result: T) => void;\n\ninterface QueuedRequest<T> {\n requestFn: Request<T>;\n resolve: (value: T) => void;\n reject: (error: any) => void;\n}\n\nconst queues = new Map<QueueName, QueuedRequest<any>[]>();\nconst processing = new Map<QueueName, boolean>();\nconst pendingRequests = signal<Set<QueueName>>(new Set());\nconst onQueueCompleted = new Map<QueueName, QueueCompletedHandler<any>>();\n\nonQueueCompleted.set(\n QueueName.Updates,\n (latestResult: Cart | NegotiableQuote) => {\n events.emit('checkout/updated', latestResult);\n }\n);\n\nasync function processQueue(type: QueueName): Promise<void> {\n processing.set(type, true);\n\n const queue = queues.get(type)!;\n let latestSuccessResult: any;\n\n while (queue.length > 0) {\n const request = queue.shift()!;\n\n try {\n const result = await request.requestFn();\n request.resolve(result);\n latestSuccessResult = result;\n } catch (error) {\n request.reject(error);\n }\n }\n\n processing.set(type, false);\n\n const pendingSet = new Set(pendingRequests.value);\n pendingSet.delete(type);\n pendingRequests.value = pendingSet;\n\n const handler = onQueueCompleted.get(type);\n\n if (handler && latestSuccessResult) {\n handler(latestSuccessResult);\n }\n}\n\nexport function enqueueRequest<T>(\n requestFn: Request<T>,\n name: QueueName = QueueName.Default\n): Promise<T> {\n if (!queues.has(name)) {\n queues.set(name, []);\n }\n\n const queue = queues.get(name)!;\n\n const promise = new Promise<T>((resolve, reject) => {\n queue.push({ requestFn, resolve, reject });\n });\n\n const pendingSet = new Set(pendingRequests.value);\n pendingSet.add(name);\n pendingRequests.value = pendingSet;\n\n if (!processing.get(name)) {\n processQueue(name);\n }\n\n return promise;\n}\n\nexport const hasPendingUpdates: ReadonlySignal<boolean> = computed(() => {\n return pendingRequests.value.has(QueueName.Updates);\n});\n\nexport const hasPendingShippingEstimate: ReadonlySignal<boolean> = computed(\n () => {\n return pendingRequests.value.has(QueueName.ShippingEstimate);\n }\n);\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { FetchQueryError } from '@/checkout/api/fetch-graphql';\n\ntype ErrorPath = (string | number)[];\n\nexport type ErrorWithPath = FetchQueryError[number] & {\n path?: ErrorPath;\n};\n\nconst controlledErrorProps: string[] = ['sender_email', 'recipient_email'];\n\n/**\n * Filters out errors with known paths from a list of errors generated by a GraphQL query.\n *\n * Known issue: The query does not differentiate between physical and virtual gift cards, leading\n * to errors for physical ones as they don't have 'sender_email' and 'recipient_email' properties.\n *\n * @param {ErrorWithPath[]} errors - Array of errors to be filtered.\n * @return {ErrorWithPath[]} Uncontrolled (unexpected) errors not matching predefined paths.\n */\n\nexport function filterControlledErrors(errors: ErrorWithPath[]) {\n return errors.filter(\n (error) =>\n !error.path ||\n !controlledErrorProps.some((controlledErrorProp) => {\n return error.path?.at(-1) === controlledErrorProp;\n })\n );\n}\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { FetchQueryError } from '@/checkout/api/fetch-graphql';\n\nexport class FetchError extends Error {\n constructor(reasons: FetchQueryError) {\n super(reasons.map((e: any) => e.message).join(' '));\n this.name = 'FetchError';\n }\n}\n\nexport class InvalidInput extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'InvalidInput';\n }\n}\n\nexport class MissingArgument extends InvalidInput {\n constructor(argumentName: string) {\n super(`${argumentName} is required.`);\n }\n}\n\nexport class MissingCart extends MissingArgument {\n constructor() {\n super('Cart ID');\n }\n}\n\nexport class MissingCartAndQuote extends InvalidInput {\n constructor() {\n super('Either Cart ID or Quote ID is required.');\n }\n}\n\nexport class Unauthenticated extends Error {\n constructor() {\n super('User is not authenticated');\n }\n}\n\nexport class MissingNegotiableQuoteId extends MissingArgument {\n constructor() {\n super('Negotiable Quote ID');\n }\n}\n\nexport class MissingEmail extends MissingArgument {\n constructor() {\n super('Email');\n }\n}\n\nexport class MissingPaymentMethod extends MissingArgument {\n constructor() {\n super('Payment method code');\n }\n}\n\nexport class MissingShippingAddress extends MissingArgument {\n constructor() {\n super('Shipping address');\n }\n}\n\nexport class MissingShippingMethod extends MissingArgument {\n constructor() {\n super('Shipping method');\n }\n}\n\nexport class MissingBillingAddress extends MissingArgument {\n constructor() {\n super('Billing address');\n }\n}\n\nexport class MissingCountry extends MissingArgument {\n constructor() {\n super('Country Code');\n }\n}\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { fetchGraphQl, FetchOptions, FetchQueryError } from '@/checkout/api';\nimport { enqueueRequest, QueueName } from '@/checkout/lib/enqueueRequest';\nimport { filterControlledErrors } from '@/checkout/lib/filterControlledErrors';\nimport { FetchError } from '@/checkout/lib/errors';\n\ntype DispatchApiCallParams<T> = {\n defaultValueOnFail?: T;\n options?: FetchOptions;\n path: string;\n query: string;\n queueName?: QueueName;\n transformer?: (data: any) => T;\n type: 'query' | 'mutation';\n};\n\nexport function getValueAtPath(obj: any, path: string) {\n return path\n .split('.')\n .reduce(\n (acc, part) => (acc && acc[part] !== undefined ? acc[part] : undefined),\n obj\n );\n}\n\nasync function dispatchApiCall<T>(\n params: DispatchApiCallParams<T>\n): Promise<T> {\n const {\n defaultValueOnFail,\n options,\n path,\n query,\n queueName,\n transformer,\n type,\n } = params;\n\n try {\n const processApiCall = async () => {\n const { data, errors } = await fetchGraphQl<T>(query, {\n method: type === 'query' ? 'GET' : 'POST',\n cache: type === 'query' ? 'no-cache' : undefined,\n ...options,\n });\n\n if (errors) {\n const uncontrolledErrors = filterControlledErrors(errors);\n\n if (uncontrolledErrors.length > 0) {\n throw new FetchError(uncontrolledErrors as FetchQueryError);\n }\n }\n\n let result = getValueAtPath(data, path);\n\n if (result === undefined) {\n throw new Error(`No data found at path: ${path}`);\n }\n\n return transformer ? transformer(result) : result;\n };\n\n // Execute the API call, either directly or through the queue\n const result =\n type === 'mutation'\n ? await enqueueRequest<T>(processApiCall, queueName)\n : await processApiCall();\n\n return result;\n } catch (error: any) {\n if (defaultValueOnFail !== undefined) return defaultValueOnFail;\n throw error;\n }\n}\n\nexport { dispatchApiCall };\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nexport const getStoreConfigQuery = /* GraphQL */ `\n query getStoreConfig {\n storeConfig {\n default_country\n is_checkout_agreements_enabled\n is_guest_checkout_enabled\n is_one_page_checkout_enabled\n shopping_cart_display_shipping\n }\n }\n`;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { StoreConfig, TaxDisplay } from '@/checkout/data/models';\nimport { transformStoreConfig } from '@/checkout/data/transforms';\nimport { dispatchApiCall, state } from '@/checkout/lib';\nimport { getStoreConfigQuery } from './graphql/getStoreConfig.graphql';\n\nexport const DEFAULT_COUNTRY = 'US';\n\nexport const STORE_CONFIG_DEFAULTS: StoreConfig = {\n defaultCountry: DEFAULT_COUNTRY,\n agreementsEnabled: true,\n shoppingCartDisplaySetting: {\n shipping: TaxDisplay.EXCLUDING_TAX,\n },\n};\n\nexport const getStoreConfig = async () => {\n return await dispatchApiCall({\n defaultValueOnFail: STORE_CONFIG_DEFAULTS,\n options: { method: 'GET', cache: 'no-cache' },\n path: 'storeConfig',\n query: getStoreConfigQuery,\n transformer: transformStoreConfig,\n type: 'query',\n });\n};\n\nexport const getStoreConfigCache = () => state.config;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { GetStoreConfigQuery } from '@/checkout/__generated__/types';\nimport { STORE_CONFIG_DEFAULTS } from '@/checkout/api/getStoreConfig';\nimport { StoreConfig, TaxDisplay } from '@/checkout/data/models';\n\nexport function transformTaxDisplay(data: number | null | undefined) {\n switch (data) {\n case 1:\n return TaxDisplay.EXCLUDING_TAX;\n case 2:\n return TaxDisplay.INCLUDING_TAX;\n case 3:\n return TaxDisplay.INCLUDING_EXCLUDING_TAX;\n default:\n return TaxDisplay.EXCLUDING_TAX;\n }\n}\n\nexport function transformStoreConfig(\n data: GetStoreConfigQuery['storeConfig']\n): StoreConfig {\n if (!data) return STORE_CONFIG_DEFAULTS;\n\n const {\n default_country,\n is_checkout_agreements_enabled,\n shopping_cart_display_shipping,\n } = data;\n\n return {\n defaultCountry: default_country || STORE_CONFIG_DEFAULTS.defaultCountry,\n agreementsEnabled: is_checkout_agreements_enabled,\n shoppingCartDisplaySetting: {\n shipping: transformTaxDisplay(shopping_cart_display_shipping),\n },\n };\n}\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { FetchGraphQL } from '@adobe-commerce/fetch-graphql';\n\nexport const {\n setEndpoint,\n setFetchGraphQlHeader,\n removeFetchGraphQlHeader,\n setFetchGraphQlHeaders,\n fetchGraphQl,\n getConfig,\n} = new FetchGraphQL().getMethods();\n\nexport type {\n FetchOptions,\n FetchQueryError,\n} from '@adobe-commerce/fetch-graphql';\n"],"names":["_state","state","target","key","value","TaxDisplay","QueueName","queues","processing","pendingRequests","signal","onQueueCompleted","latestResult","events","processQueue","type","queue","latestSuccessResult","request","result","error","pendingSet","handler","enqueueRequest","requestFn","name","promise","resolve","reject","hasPendingUpdates","computed","hasPendingShippingEstimate","controlledErrorProps","filterControlledErrors","errors","controlledErrorProp","_a","FetchError","reasons","e","InvalidInput","message","MissingArgument","argumentName","MissingCart","MissingCartAndQuote","Unauthenticated","MissingNegotiableQuoteId","MissingEmail","MissingPaymentMethod","MissingShippingAddress","MissingShippingMethod","MissingBillingAddress","MissingCountry","getValueAtPath","obj","path","acc","part","dispatchApiCall","params","defaultValueOnFail","options","query","queueName","transformer","processApiCall","data","fetchGraphQl","uncontrolledErrors","getStoreConfigQuery","DEFAULT_COUNTRY","STORE_CONFIG_DEFAULTS","getStoreConfig","transformStoreConfig","getStoreConfigCache","transformTaxDisplay","default_country","is_checkout_agreements_enabled","shopping_cart_display_shipping","setEndpoint","setFet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,GACA,uBAAAC,GACA,aAAAf,EACA,UAAAgB,EACF,EAAI,IAAIC,EAAa,EAAE,WAAW"}
|
|
1
|
+
{"version":3,"file":"fetch-graphql.js","sources":["/@dropins/storefront-checkout/src/lib/state.ts","/@dropins/storefront-checkout/src/data/models/store-config.ts","/@dropins/storefront-checkout/src/lib/enqueueRequest.ts","/@dropins/storefront-checkout/src/lib/filterControlledErrors.ts","/@dropins/storefront-checkout/src/lib/errors/customErrors.ts","/@dropins/storefront-checkout/src/lib/dispatchApiCall.ts","/@dropins/storefront-checkout/src/api/getStoreConfig/graphql/getStoreConfig.graphql.ts","/@dropins/storefront-checkout/src/api/getStoreConfig/getStoreConfig.ts","/@dropins/storefront-checkout/src/data/transforms/transform-store-config.ts","/@dropins/storefront-checkout/src/api/fetch-graphql/fetch-graphql.ts"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { StoreConfig } from '@/checkout/data/models';\n\ntype State = {\n authenticated: boolean;\n cartId?: string | null;\n config: StoreConfig | null;\n initialized: boolean;\n quoteId?: string | null;\n};\n\nconst _state: State = (() => ({\n authenticated: false,\n cartId: null,\n config: null,\n initialized: false,\n quoteId: null,\n}))();\n\n// Proxy state to allow reactivity\nexport const state = new Proxy(_state, {\n set(target, key, value) {\n // @ts-ignore\n target[key] = value;\n return true;\n },\n get(target, key) {\n return target[key as keyof State];\n },\n});\n\nexport function isQuoteCheckout(): boolean {\n return state.quoteId !== null;\n}\n\nexport function isCartCheckout(): boolean {\n return state.cartId !== null;\n}\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nexport enum TaxDisplay {\n EXCLUDING_TAX = 'EXCLUDING_TAX',\n INCLUDING_EXCLUDING_TAX = 'INCLUDING_AND_EXCLUDING_TAX',\n INCLUDING_TAX = 'INCLUDING_TAX',\n}\n\nexport interface StoreConfig {\n defaultCountry: string;\n agreementsEnabled: boolean;\n shoppingCartDisplaySetting: {\n shipping: TaxDisplay;\n };\n}\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { Cart, NegotiableQuote } from '@/checkout/data/models';\nimport {\n computed,\n ReadonlySignal,\n signal,\n} from '@adobe-commerce/elsie/lib/signals';\nimport { events } from '@adobe-commerce/event-bus';\n\nexport enum QueueName {\n Updates = 'updates',\n Default = 'default',\n ShippingEstimate = 'shippingEstimate',\n}\n\ntype Request<T> = () => Promise<T>;\ntype QueueCompletedHandler<T> = (result: T) => void;\n\ninterface QueuedRequest<T> {\n requestFn: Request<T>;\n resolve: (value: T) => void;\n reject: (error: any) => void;\n}\n\nconst queues = new Map<QueueName, QueuedRequest<any>[]>();\nconst processing = new Map<QueueName, boolean>();\nconst pendingRequests = signal<Set<QueueName>>(new Set());\nconst onQueueCompleted = new Map<QueueName, QueueCompletedHandler<any>>();\n\nonQueueCompleted.set(\n QueueName.Updates,\n (latestResult: Cart | NegotiableQuote) => {\n events.emit('checkout/updated', latestResult);\n }\n);\n\nasync function processQueue(type: QueueName): Promise<void> {\n processing.set(type, true);\n\n const queue = queues.get(type)!;\n let latestSuccessResult: any;\n\n while (queue.length > 0) {\n const request = queue.shift()!;\n\n try {\n const result = await request.requestFn();\n request.resolve(result);\n latestSuccessResult = result;\n } catch (error) {\n request.reject(error);\n }\n }\n\n processing.set(type, false);\n\n const pendingSet = new Set(pendingRequests.value);\n pendingSet.delete(type);\n pendingRequests.value = pendingSet;\n\n const handler = onQueueCompleted.get(type);\n\n if (handler && latestSuccessResult) {\n handler(latestSuccessResult);\n }\n}\n\nexport function enqueueRequest<T>(\n requestFn: Request<T>,\n name: QueueName = QueueName.Default\n): Promise<T> {\n if (!queues.has(name)) {\n queues.set(name, []);\n }\n\n const queue = queues.get(name)!;\n\n const promise = new Promise<T>((resolve, reject) => {\n queue.push({ requestFn, resolve, reject });\n });\n\n const pendingSet = new Set(pendingRequests.value);\n pendingSet.add(name);\n pendingRequests.value = pendingSet;\n\n if (!processing.get(name)) {\n processQueue(name);\n }\n\n return promise;\n}\n\nexport const hasPendingUpdates: ReadonlySignal<boolean> = computed(() => {\n return pendingRequests.value.has(QueueName.Updates);\n});\n\nexport const hasPendingShippingEstimate: ReadonlySignal<boolean> = computed(\n () => {\n return pendingRequests.value.has(QueueName.ShippingEstimate);\n }\n);\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { FetchQueryError } from '@/checkout/api/fetch-graphql';\n\ntype ErrorPath = (string | number)[];\n\nexport type ErrorWithPath = FetchQueryError[number] & {\n path?: ErrorPath;\n};\n\nconst controlledErrorProps: string[] = ['sender_email', 'recipient_email'];\n\n/**\n * Filters out errors with known paths from a list of errors generated by a GraphQL query.\n *\n * Known issue: The query does not differentiate between physical and virtual gift cards, leading\n * to errors for physical ones as they don't have 'sender_email' and 'recipient_email' properties.\n *\n * @param {ErrorWithPath[]} errors - Array of errors to be filtered.\n * @return {ErrorWithPath[]} Uncontrolled (unexpected) errors not matching predefined paths.\n */\n\nexport function filterControlledErrors(errors: ErrorWithPath[]) {\n return errors.filter(\n (error) =>\n !error.path ||\n !controlledErrorProps.some((controlledErrorProp) => {\n return error.path?.at(-1) === controlledErrorProp;\n })\n );\n}\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { FetchQueryError } from '@/checkout/api/fetch-graphql';\n\nexport class FetchError extends Error {\n constructor(reasons: FetchQueryError) {\n super(reasons.map((e: any) => e.message).join(' '));\n this.name = 'FetchError';\n }\n}\n\nexport class InvalidInput extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'InvalidInput';\n }\n}\n\nexport class MissingArgument extends InvalidInput {\n constructor(argumentName: string) {\n super(`${argumentName} is required.`);\n }\n}\n\nexport class MissingCart extends MissingArgument {\n constructor() {\n super('Cart ID');\n }\n}\n\nexport class MissingCartAndQuote extends InvalidInput {\n constructor() {\n super('Either Cart ID or Quote ID is required.');\n }\n}\n\nexport class Unauthenticated extends Error {\n constructor() {\n super('User is not authenticated');\n }\n}\n\nexport class MissingNegotiableQuoteId extends MissingArgument {\n constructor() {\n super('Negotiable Quote ID');\n }\n}\n\nexport class MissingEmail extends MissingArgument {\n constructor() {\n super('Email');\n }\n}\n\nexport class MissingPaymentMethod extends MissingArgument {\n constructor() {\n super('Payment method code');\n }\n}\n\nexport class MissingShippingAddress extends MissingArgument {\n constructor() {\n super('Shipping address');\n }\n}\n\nexport class MissingShippingMethod extends MissingArgument {\n constructor() {\n super('Shipping method');\n }\n}\n\nexport class MissingBillingAddress extends MissingArgument {\n constructor() {\n super('Billing address');\n }\n}\n\nexport class MissingCountry extends MissingArgument {\n constructor() {\n super('Country Code');\n }\n}\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { fetchGraphQl, FetchOptions, FetchQueryError } from '@/checkout/api';\nimport { enqueueRequest, QueueName } from '@/checkout/lib/enqueueRequest';\nimport { filterControlledErrors } from '@/checkout/lib/filterControlledErrors';\nimport { FetchError } from '@/checkout/lib/errors';\n\ntype DispatchApiCallParams<T> = {\n defaultValueOnFail?: T;\n options?: FetchOptions;\n path: string;\n query: string;\n queueName?: QueueName;\n transformer?: (data: any) => T;\n type: 'query' | 'mutation';\n};\n\nexport function getValueAtPath(obj: any, path: string) {\n return path\n .split('.')\n .reduce(\n (acc, part) => (acc && acc[part] !== undefined ? acc[part] : undefined),\n obj\n );\n}\n\nasync function dispatchApiCall<T>(\n params: DispatchApiCallParams<T>\n): Promise<T> {\n const {\n defaultValueOnFail,\n options,\n path,\n query,\n queueName,\n transformer,\n type,\n } = params;\n\n try {\n const processApiCall = async () => {\n const { data, errors } = await fetchGraphQl<T>(query, {\n method: type === 'query' ? 'GET' : 'POST',\n cache: type === 'query' ? 'no-cache' : undefined,\n ...options,\n });\n\n if (errors) {\n const uncontrolledErrors = filterControlledErrors(errors);\n\n if (uncontrolledErrors.length > 0) {\n throw new FetchError(uncontrolledErrors as FetchQueryError);\n }\n }\n\n let result = getValueAtPath(data, path);\n\n if (result === undefined) {\n throw new Error(`No data found at path: ${path}`);\n }\n\n return transformer ? transformer(result) : result;\n };\n\n // Execute the API call, either directly or through the queue\n const result =\n type === 'mutation'\n ? await enqueueRequest<T>(processApiCall, queueName)\n : await processApiCall();\n\n return result;\n } catch (error: any) {\n if (defaultValueOnFail !== undefined) return defaultValueOnFail;\n throw error;\n }\n}\n\nexport { dispatchApiCall };\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nexport const getStoreConfigQuery = /* GraphQL */ `\n query getStoreConfig {\n storeConfig {\n default_country\n is_checkout_agreements_enabled\n is_guest_checkout_enabled\n is_one_page_checkout_enabled\n shopping_cart_display_shipping\n }\n }\n`;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { StoreConfig, TaxDisplay } from '@/checkout/data/models';\nimport { transformStoreConfig } from '@/checkout/data/transforms';\nimport { dispatchApiCall, state } from '@/checkout/lib';\nimport { getStoreConfigQuery } from './graphql/getStoreConfig.graphql';\n\nexport const DEFAULT_COUNTRY = 'US';\n\nexport const STORE_CONFIG_DEFAULTS: StoreConfig = {\n defaultCountry: DEFAULT_COUNTRY,\n agreementsEnabled: true,\n shoppingCartDisplaySetting: {\n shipping: TaxDisplay.EXCLUDING_TAX,\n },\n};\n\nexport const getStoreConfig = async () => {\n return await dispatchApiCall({\n defaultValueOnFail: STORE_CONFIG_DEFAULTS,\n options: { method: 'GET', cache: 'no-cache' },\n path: 'storeConfig',\n query: getStoreConfigQuery,\n transformer: transformStoreConfig,\n type: 'query',\n });\n};\n\nexport const getStoreConfigCache = () => state.config;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { GetStoreConfigQuery } from '@/checkout/__generated__/types';\nimport { STORE_CONFIG_DEFAULTS } from '@/checkout/api/getStoreConfig';\nimport { StoreConfig, TaxDisplay } from '@/checkout/data/models';\n\nexport function transformTaxDisplay(data: number | null | undefined) {\n switch (data) {\n case 1:\n return TaxDisplay.EXCLUDING_TAX;\n case 2:\n return TaxDisplay.INCLUDING_TAX;\n case 3:\n return TaxDisplay.INCLUDING_EXCLUDING_TAX;\n default:\n return TaxDisplay.EXCLUDING_TAX;\n }\n}\n\nexport function transformStoreConfig(\n data: GetStoreConfigQuery['storeConfig']\n): StoreConfig {\n if (!data) return STORE_CONFIG_DEFAULTS;\n\n const {\n default_country,\n is_checkout_agreements_enabled,\n shopping_cart_display_shipping,\n } = data;\n\n return {\n defaultCountry: default_country || STORE_CONFIG_DEFAULTS.defaultCountry,\n agreementsEnabled: is_checkout_agreements_enabled,\n shoppingCartDisplaySetting: {\n shipping: transformTaxDisplay(shopping_cart_display_shipping),\n },\n };\n}\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { FetchGraphQL } from '@adobe-commerce/fetch-graphql';\n\nexport const {\n setEndpoint,\n setFetchGraphQlHeader,\n removeFetchGraphQlHeader,\n setFetchGraphQlHeaders,\n fetchGraphQl,\n getConfig,\n} = new FetchGraphQL().getMethods();\n\nexport type {\n FetchOptions,\n FetchQueryError,\n} from '@adobe-commerce/fetch-graphql';\n"],"names":["_state","state","target","key","value","isQuoteCheckout","TaxDisplay","QueueName","queues","processing","pendingRequests","signal","onQueueCompleted","latestResult","events","processQueue","type","queue","latestSuccessResult","request","result","error","pendingSet","handler","enqueueRequest","requestFn","name","promise","resolve","reject","hasPendingUpdates","computed","hasPendingShippingEstimate","controlledErrorProps","filterControlledErrors","errors","controlledErrorProp","_a","FetchError","reasons","e","InvalidInput","message","MissingArgument","argumentName","MissingCart","MissingCartAndQuote","Unauthenticated","MissingNegotiableQuoteId","MissingEmail","MissingPaymentMethod","MissingShippingAddress","MissingShippingMethod","MissingBillingAddress","MissingCountry","getValueAtPath","obj","path","acc","part","dispatchApiCall","params","defaultValueOnFail","options","query","queueName","transformer","processApiCall","data","fetchGraphQl","uncontrolledErrors","getStoreConfigQuery","DEFAULT_COUNTRY","STORE_CONFIG_DEFAULTS","getStoreConfig","transformStoreConfig","getStoreConfigCache","transformTaxDisplay","default_country","is_checkout_agreements_enabled","shopping_cart_display_shipping","setEndpoint","setFetchG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CjCa,KAAA,CACX,YAAAC,GACA,sBAAAC,GACA,yBAAAC,GACA,uBAAAC,GACA,aAAAf,EACA,UAAAgB,EACF,EAAI,IAAIC,EAAa,EAAE,WAAW"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/*! Copyright 2025 Adobe
|
|
2
2
|
All Rights Reserved. */
|
|
3
|
-
import{CUSTOMER_FRAGMENT as o,CHECKOUT_DATA_FRAGMENT as n}from"../fragments.js";import{s as m,d as r,
|
|
3
|
+
import{CUSTOMER_FRAGMENT as o,CHECKOUT_DATA_FRAGMENT as n}from"../fragments.js";import{s as m,d as r,t as l,o as u,Q as c}from"./fetch-graphql.js";import{merge as E}from"@dropins/tools/lib.js";import"@dropins/tools/event-bus.js";import{c as f,t as p}from"./synchronizeCheckout.js";const C=t=>{var i,a,s;if(!t)return null;const e={firstName:t.firstname||"",lastName:t.lastname||"",email:t.email||""};return E(e,(s=(a=(i=f.getConfig().models)==null?void 0:i.CustomerModel)==null?void 0:a.transformer)==null?void 0:s.call(a,t))},y=t=>!!(t!=null&&t.is_email_available),A=`
|
|
4
4
|
query getCustomer {
|
|
5
5
|
customer {
|
|
6
6
|
...CUSTOMER_FRAGMENT
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/*! Copyright 2025 Adobe
|
|
2
2
|
All Rights Reserved. */
|
|
3
|
-
import{s as o,
|
|
3
|
+
import{s as o,o as G,p as D,d as T,Q as E,I as l,q as Q}from"./fetch-graphql.js";import"@dropins/tools/lib.js";import{t as F,a as O}from"./transform-shipping-estimate.js";import{a as R}from"./transform-shipping-methods.js";import{events as $}from"@dropins/tools/event-bus.js";import{g as N}from"./values.js";import{c as w,t as x,e as H}from"./synchronizeCheckout.js";import{e as V,f as K,g as L}from"./guards.js";import{CHECKOUT_DATA_FRAGMENT as y,NEGOTIABLE_QUOTE_FRAGMENT as B}from"../fragments.js";const k=`
|
|
4
4
|
mutation estimateShippingMethods(
|
|
5
5
|
$cartId: String!
|
|
6
6
|
$address: EstimateAddressInput!
|
|
@@ -26,7 +26,7 @@ import{s as o,n as G,o as D,d as q,Q as E,I as l,p as Q}from"./fetch-graphql.js"
|
|
|
26
26
|
error_message
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
|
-
`,ae=async e=>{var _,m,I,S;const s=o.cartId,t=((_=e==null?void 0:e.criteria)==null?void 0:_.country_code)??((m=o.config)==null?void 0:m.defaultCountry);if(!s)throw new G;if(!t)throw new D;const{region_id:i,region_name:a,zip:p}=(e==null?void 0:e.criteria)??{},n=i||a?{region_id:typeof i=="string"?parseInt(i,10):i,region_code:a}:void 0,h={country_code:t,...p&&{postcode:p},...n&&{region:{...n.region_id&&{region_id:n.region_id},...n.region_code&&{region_code:n.region_code}}}},A={country_id:t,region:(I=h.region)==null?void 0:I.region_code,region_id:(S=h.region)==null?void 0:S.region_id,postcode:p},b=O(A);return
|
|
29
|
+
`,ae=async e=>{var _,m,I,S;const s=o.cartId,t=((_=e==null?void 0:e.criteria)==null?void 0:_.country_code)??((m=o.config)==null?void 0:m.defaultCountry);if(!s)throw new G;if(!t)throw new D;const{region_id:i,region_name:a,zip:p}=(e==null?void 0:e.criteria)??{},n=i||a?{region_id:typeof i=="string"?parseInt(i,10):i,region_code:a}:void 0,h={country_code:t,...p&&{postcode:p},...n&&{region:{...n.region_id&&{region_id:n.region_id},...n.region_code&&{region_code:n.region_code}}}},A={country_id:t,region:(I=h.region)==null?void 0:I.region_code,region_id:(S=h.region)==null?void 0:S.region_id,postcode:p},b=O(A);return T({options:{variables:{cartId:s,address:h}},path:"estimateShippingMethods",query:k,queueName:E.ShippingEstimate,transformer:R,type:"mutation"}).then(r=>{const{defaults:c,shipping:u}=w.getConfig(),f=u!=null&&u.filterOptions?r.filter(u.filterOptions):r,v=f.length>0,U=O(A);let M=null;if(v){const d=N("selectedShippingMethod");let g=r.find(C=>C.code===(d==null?void 0:d.code)&&C.carrier.code===(d==null?void 0:d.carrier.code));!g&&(c!=null&&c.selectedShippingMethod)&&(g=c.selectedShippingMethod(r)??void 0),g||(g=r[0]),M=F(g)}return $.emit("shipping/estimate",{address:U,availableShippingMethods:r,shippingMethod:M,success:!0}),f}).catch(r=>{throw $.emit("shipping/estimate",{address:b,shippingMethod:null,availableShippingMethods:[],success:!1}),r})},z=`
|
|
30
30
|
mutation setShippingAddressOnCartAndUseAsBilling(
|
|
31
31
|
$cartId: String!
|
|
32
32
|
$shippingAddress: ShippingAddressInput!
|
|
@@ -105,5 +105,5 @@ import{s as o,n as G,o as D,d as q,Q as E,I as l,p as Q}from"./fetch-graphql.js"
|
|
|
105
105
|
}
|
|
106
106
|
|
|
107
107
|
${B}
|
|
108
|
-
`,W=({address:e,customerAddressId:s,customerAddressUid:t,pickupLocationCode:i})=>{if(!s&&t)throw new l("customerAddressUid is not supported");if(!s&&!i&&!e)throw new Q},X=({address:e,customerAddressId:s,customerAddressUid:t,pickupLocationCode:i})=>{if(i)throw new l("pickup location is not supported in quotes");if(!t&&s)throw new l("customerAddressId is not supported in quotes");if(!t&&!e)throw new Q},Y=e=>{const s=!!o.cartId,t=!!o.quoteId;s?W(e):t&&X(e)},
|
|
108
|
+
`,W=({address:e,customerAddressId:s,customerAddressUid:t,pickupLocationCode:i})=>{if(!s&&t)throw new l("customerAddressUid is not supported");if(!s&&!i&&!e)throw new Q},X=({address:e,customerAddressId:s,customerAddressUid:t,pickupLocationCode:i})=>{if(i)throw new l("pickup location is not supported in quotes");if(!t&&s)throw new l("customerAddressId is not supported in quotes");if(!t&&!e)throw new Q},Y=e=>{const s=!!o.cartId,t=!!o.quoteId;s?W(e):t&&X(e)},q=(e,s,t,i,a,p)=>async n=>await T({type:"mutation",query:t,options:{variables:{[s]:e,shippingAddress:a(n)}},path:p,queueName:E.Updates,transformer:i}),pe=async e=>{V(),Y(e);const{defaults:s}=w.getConfig(),t=N("isBillToShipping")??(s==null?void 0:s.isBillToShipping);return await(!!o.cartId?q(o.cartId,"cartId",t?z:P,x,K,t?"setBillingAddressOnCart.cart":"setShippingAddressesOnCart.cart"):q(o.quoteId,"quoteId",t?J:j,H,L,t?"setNegotiableQuoteBillingAddress.quote":"setNegotiableQuoteShippingAddress.quote"))(e)};export{ae as e,pe as s};
|
|
109
109
|
//# sourceMappingURL=setShippingAddress.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/*! Copyright 2025 Adobe
|
|
2
2
|
All Rights Reserved. */
|
|
3
|
-
import{s as r,
|
|
3
|
+
import{s as r,o as D,d as _,U as S,u as N,e as Q}from"./fetch-graphql.js";import{merge as k,Initializer as z,deepmerge as O}from"@dropins/tools/lib.js";import{events as d}from"@dropins/tools/event-bus.js";import{CHECKOUT_DATA_FRAGMENT as C,NEGOTIABLE_QUOTE_FRAGMENT as G}from"../fragments.js";import{b as P,c as R,d as U,a as L,e as x,f as B,g as $}from"./transform-shipping-methods.js";import{E as p}from"./classifiers.js";const F=async(e=!1)=>{r.authenticated=e},b=e=>{if(!e)return;const{code:t,title:a,...s}=e;return{code:t,title:a,additionalData:s}},I=e=>{if(e)return e.filter(t=>!!t).map(t=>{const{code:a,title:s,...c}=t;return{code:a,title:s,additionalData:c}})},H=e=>{var a,s,c;if(!e)return;const t={type:"cart",availablePaymentMethods:I(e.available_payment_methods),billingAddress:R(e.billing_address),email:e.email??void 0,id:e.id,isEmpty:e.total_quantity===0,isVirtual:e.is_virtual,selectedPaymentMethod:b(e.selected_payment_method),shippingAddresses:P(e.shipping_addresses),isGuest:!r.authenticated};return k(t,(c=(s=(a=te.getConfig().models)==null?void 0:a.CartModel)==null?void 0:s.transformer)==null?void 0:c.call(s,e))},q=e=>{const t=e.street.filter(Boolean);return{city:e.city,company:e.company||void 0,country:$(e.country),customAttributes:B(e.custom_attributes),customerAddressUid:e.customer_address_uid||void 0,fax:e.fax||void 0,firstName:e.firstname,lastName:e.lastname,middleName:e.middlename||void 0,postCode:e.postcode||void 0,prefix:e.prefix||void 0,region:x(e.region),street:t,suffix:e.suffix||void 0,telephone:e.telephone||void 0,uid:e.uid,vatId:e.vat_id||void 0}},K=e=>{if(e)return q(e)},V=e=>e.filter(t=>!!t).map(t=>{const{available_shipping_methods:a,selected_shipping_method:s,...c}=t;return{...q(c),availableShippingMethods:L(a),selectedShippingMethod:U(s)}}),Y=e=>e?{type:"quote",availablePaymentMethods:I(e.available_payment_methods),billingAddress:K(e.billing_address),email:e.email??"",isEmpty:e.total_quantity===0,isVirtual:e.is_virtual,name:e.name,selectedPaymentMethod:b(e.selected_payment_method),shippingAddresses:V(e.shipping_addresses),status:e.status,uid:e.uid}:null,W=`
|
|
4
4
|
query getCart($cartId: String!) {
|
|
5
5
|
cart(cart_id: $cartId) {
|
|
6
6
|
...CHECKOUT_DATA_FRAGMENT
|
|
@@ -24,5 +24,5 @@ import{s as r,n as D,d as _,U as S,t as N,e as Q}from"./fetch-graphql.js";import
|
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
${G}
|
|
27
|
-
`,E=async(e={})=>{const t=e.uid??r.quoteId;if(r.authenticated===!1)throw new S;if(!t)throw new N;return await _({type:"query",query:J,options:{method:"GET",cache:"no-cache",variables:{quoteId:t}},path:"negotiableQuote",transformer:Y})},m={eager:!0},X=e=>{var g
|
|
27
|
+
`,E=async(e={})=>{const t=e.uid??r.quoteId;if(r.authenticated===!1)throw new S;if(!t)throw new N;return await _({type:"query",query:J,options:{method:"GET",cache:"no-cache",variables:{quoteId:t}},path:"negotiableQuote",transformer:Y})},m={eager:!0},X=e=>{var y,g;const t=((g=(y=e==null?void 0:e.features)==null?void 0:y.b2b)==null?void 0:g.quotes)??!1;return[["authenticated",(u=!1)=>{var o,n,l;if(F(u),!t||u)return;const i=(l=(n=(o=e==null?void 0:e.features)==null?void 0:o.b2b)==null?void 0:n.routeLogin)==null?void 0:l.call(n);i&&window.location.assign(i)},m],...t?[["quote-management/quote-data/initialized",u=>{var i,o,n,l;if(!u.quote.canCheckout){const h=((l=(n=(o=(i=e==null?void 0:e.langDefinitions)==null?void 0:i.default)==null?void 0:o.Checkout)==null?void 0:n.Quote)==null?void 0:l.permissionDenied)||"You do not have permission to checkout with this quote.";d.emit("checkout/error",{message:h,code:p.QUOTE_PERMISSION_DENIED});return}f(u.quote)},m],["quote-management/quote-data/error",()=>{var i,o,n,l;const u=((l=(n=(o=(i=e==null?void 0:e.langDefinitions)==null?void 0:i.default)==null?void 0:o.Checkout)==null?void 0:n.Quote)==null?void 0:l.dataError)||"We were unable to retrieve the quote data. Please try again later.";d.emit("checkout/error",{message:u,code:p.QUOTE_DATA_ERROR})}]]:[["cart/initialized",f,m],["cart/reset",M],["cart/updated",T],["auth/permissions",u=>{var i,o,n,l;if(u.admin!==!0&&!u["Magento_Sales::place_order"]){const h=((l=(n=(o=(i=e==null?void 0:e.langDefinitions)==null?void 0:i.default)==null?void 0:o.Checkout)==null?void 0:n.ServerError)==null?void 0:l.permissionDenied)||"You do not have permission to complete checkout. Please contact your administrator for assistance.";d.emit("checkout/error",{message:h,code:p.PERMISSION_DENIED})}},m]]].map(([u,i,o])=>d.on(u,i,o))},Z=new URL(window.location.href),ee=Z.searchParams.get("quoteId");r.quoteId=ee;const v=new z({init:async(e={})=>{v.config.setConfig(O({defaults:{isBillToShipping:!0,selectedShippingMethod:t=>t.length>0?t[0]:null},features:{b2b:{quotes:!1}}},e))},listeners:X}),te=v.config,w=e=>"id"in e,re=async e=>{try{return w(e)?(r.cartId=e.id,r.quoteId=null,await A()??null):(r.cartId=null,r.quoteId=e.uid,await E()??null)}catch(t){return console.error("Checkout initialization failed:",t),null}},f=async e=>{if(r.initialized){await T(e);return}r.config||(r.config=await Q());const t=e?await re(e):null;r.initialized=!0,d.emit("checkout/initialized",t)},M=()=>{r.initialized&&(r.cartId=null,r.quoteId=null,d.emit("checkout/updated",null))},se=async e=>{try{return w(e)?(r.cartId=e.id,r.quoteId=null,await A()??null):(r.cartId=null,r.quoteId=e.uid,await E()??null)}catch(t){return console.error("Checkout synchronization failed:",t),null}},T=async e=>{if(!r.initialized)return f(e);if(e===null){M();return}const t=await se(e);d.emit("checkout/updated",t)};export{F as a,E as b,te as c,f as d,Y as e,A as g,v as i,M as r,T as s,H as t};
|
|
28
28
|
//# sourceMappingURL=synchronizeCheckout.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"synchronizeCheckout.js","sources":["/@dropins/storefront-checkout/src/api/authenticateCustomer/authenticateCustomer.ts","/@dropins/storefront-checkout/src/data/transforms/transform-payment-methods.ts","/@dropins/storefront-checkout/src/data/transforms/transform-cart.ts","/@dropins/storefront-checkout/src/data/transforms/transform-quote-address.ts","/@dropins/storefront-checkout/src/data/transforms/transform-negotiable-quote.ts","/@dropins/storefront-checkout/src/api/getCart/graphql/getCart.graphql.ts","/@dropins/storefront-checkout/src/api/getCart/getCart.ts","/@dropins/storefront-checkout/src/api/getNegotiableQuote/graphql/getNegotiableQuote.graphql.ts","/@dropins/storefront-checkout/src/api/getNegotiableQuote/getNegotiableQuote.ts","/@dropins/storefront-checkout/src/api/initialize/listeners.ts","/@dropins/storefront-checkout/src/api/initialize/initialize.ts","/@dropins/storefront-checkout/src/types/guards.ts","/@dropins/storefront-checkout/src/api/initializeCheckout/initializeCheckout.ts","/@dropins/storefront-checkout/src/api/resetCheckout/resetCheckout.ts","/@dropins/storefront-checkout/src/api/synchronizeCheckout/synchronizeCheckout.ts"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { state } from '@/checkout/lib/state';\n\nexport const authenticateCustomer = async (authenticated = false) => {\n state.authenticated = authenticated;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { PaymentMethod } from '@/checkout/data/models/payment-method';\nimport { GetCartQuery } from '@/checkout/__generated__/types';\n\ntype SelectedPaymentMethod = NonNullable<\n GetCartQuery['cart']\n>['selected_payment_method'];\n\ntype AvailablePaymentMethods = NonNullable<\n GetCartQuery['cart']\n>['available_payment_methods'];\n\ntype AvailablePaymentMethod = NonNullable<AvailablePaymentMethods>[number];\n\ntype NonNullabePaymentMethod = NonNullable<AvailablePaymentMethod>;\n\nconst transformSelectedPaymentMethod = (\n data: SelectedPaymentMethod\n): PaymentMethod | undefined => {\n if (!data) return;\n const { code, title, ...additionalData } = data;\n return { code, title, additionalData };\n};\n\nconst transformAvailablePaymentMethods = (\n data: AvailablePaymentMethods\n): PaymentMethod[] | undefined => {\n if (!data) return;\n\n return data\n .filter((method) => !!method)\n .map((method) => {\n const { code, title, ...additionalData } =\n method as NonNullabePaymentMethod;\n return { code, title, additionalData };\n });\n};\n\nexport { transformAvailablePaymentMethods, transformSelectedPaymentMethod };\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { config } from '@/checkout/api';\nimport { Cart as CartModel } from '@/checkout/data/models';\nimport {\n transformAvailablePaymentMethods,\n transformSelectedPaymentMethod,\n} from '@/checkout/data/transforms/transform-payment-methods';\nimport { GetCartQuery } from '@/checkout/__generated__/types';\nimport { merge } from '@adobe-commerce/elsie/lib';\n\nimport {\n transformCartBillingAddress,\n transformCartShippingAddress,\n} from '@/checkout/data/transforms/transform-cart-address';\nimport { state } from '@/checkout/lib/state';\n\ntype Cart = GetCartQuery['cart'];\n\nconst transformCart = (data: Cart): CartModel | undefined => {\n if (!data) return;\n\n const model = {\n availablePaymentMethods: transformAvailablePaymentMethods(\n data.available_payment_methods\n ),\n billingAddress: transformCartBillingAddress(data.billing_address),\n email: data.email ?? undefined,\n id: data.id,\n isEmpty: data.total_quantity === 0,\n isVirtual: data.is_virtual,\n selectedPaymentMethod: transformSelectedPaymentMethod(\n data.selected_payment_method\n ),\n shippingAddresses: transformCartShippingAddress(data.shipping_addresses),\n isGuest: !state.authenticated,\n };\n\n // Extend the model merging custom transformer, if provided\n return merge(\n model, // default transformer\n config.getConfig().models?.CartModel?.transformer?.(data) // custom transformer\n );\n};\n\nexport { Cart, transformCart };\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport {\n Address as AddressModel,\n ShippingAddress as ShippingAddressModel,\n} from '@/checkout/data/models';\n\nimport {\n transformAddressCountry,\n transformAddressRegion,\n transformCustomAttributes,\n transformSelectedShippingMethod,\n transformShippingMethods,\n} from '@/checkout/data/transforms';\nimport { GetNegotiableQuoteQuery } from '@/checkout/__generated__/types';\n\ntype QuoteShippingAddresses = NonNullable<\n GetNegotiableQuoteQuery['negotiableQuote']\n>['shipping_addresses'];\ntype QuoteShippingAddress = QuoteShippingAddresses[0];\ntype NonNullableShippingAddress = NonNullable<QuoteShippingAddress>;\n\ntype QuoteBillingAddress = NonNullable<\n GetNegotiableQuoteQuery['negotiableQuote']\n>['billing_address'];\ntype NonNullableBillingAddress = NonNullable<QuoteBillingAddress>;\n\nconst transformAddress = (\n data: NonNullableShippingAddress | NonNullableBillingAddress\n): AddressModel => {\n const street = data.street.filter(Boolean) as string[];\n\n return {\n city: data.city,\n company: data.company || undefined,\n country: transformAddressCountry(data.country),\n customAttributes: transformCustomAttributes(data.custom_attributes),\n customerAddressUid: data.customer_address_uid || undefined,\n fax: data.fax || undefined,\n firstName: data.firstname,\n lastName: data.lastname,\n middleName: data.middlename || undefined,\n postCode: data.postcode || undefined,\n prefix: data.prefix || undefined,\n region: transformAddressRegion(data.region),\n street,\n suffix: data.suffix || undefined,\n telephone: data.telephone || undefined,\n uid: data.uid,\n vatId: data.vat_id || undefined,\n };\n};\n\nconst transformQuoteBillingAddress = (\n data: QuoteBillingAddress\n): AddressModel | undefined => {\n if (!data) return;\n return transformAddress(data);\n};\n\nconst transformQuoteShippingAddress = (\n data: QuoteShippingAddresses\n): ShippingAddressModel[] => {\n return data\n .filter((address) => !!address)\n .map((address) => {\n const {\n available_shipping_methods,\n selected_shipping_method,\n ...baseData\n } = address as NonNullableShippingAddress;\n\n return {\n ...transformAddress(baseData as NonNullableShippingAddress),\n availableShippingMethods: transformShippingMethods(\n available_shipping_methods\n ),\n selectedShippingMethod: transformSelectedShippingMethod(\n selected_shipping_method\n ),\n };\n });\n};\n\nexport {\n QuoteBillingAddress,\n QuoteShippingAddress,\n transformQuoteBillingAddress,\n transformQuoteShippingAddress,\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { NegotiableQuote as NegotiableQuoteModel } from '@/checkout/data/models/';\nimport { GetNegotiableQuoteQuery } from '@/checkout/__generated__/types';\n\nimport {\n transformAvailablePaymentMethods,\n transformQuoteBillingAddress,\n transformQuoteShippingAddress,\n transformSelectedPaymentMethod,\n} from '@/checkout/data/transforms';\n\ntype NegotiableQuote = GetNegotiableQuoteQuery['negotiableQuote'];\n\nexport const transformNegotiableQuote = (\n data: NegotiableQuote | undefined\n): NegotiableQuoteModel | null => {\n if (!data) return null;\n\n return {\n availablePaymentMethods: transformAvailablePaymentMethods(\n data.available_payment_methods\n ),\n billingAddress: transformQuoteBillingAddress(data.billing_address),\n email: data.email ?? '',\n isEmpty: data.total_quantity === 0,\n isVirtual: data.is_virtual,\n name: data.name,\n selectedPaymentMethod: transformSelectedPaymentMethod(\n data.selected_payment_method\n ),\n shippingAddresses: transformQuoteShippingAddress(data.shipping_addresses),\n status: data.status,\n uid: data.uid,\n };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { CHECKOUT_DATA_FRAGMENT } from '@/checkout/api/graphql/CheckoutDataFragment.graphql';\n\nexport const getCartQuery = /* GraphQL */ `\n query getCart($cartId: String!) {\n cart(cart_id: $cartId) {\n ...CHECKOUT_DATA_FRAGMENT\n }\n }\n\n ${CHECKOUT_DATA_FRAGMENT}\n`;\n\nexport const getCustomerCartQuery = /* GraphQL */ `\n query getCustomerCart {\n cart: customerCart {\n ...CHECKOUT_DATA_FRAGMENT\n }\n }\n\n ${CHECKOUT_DATA_FRAGMENT}\n`;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport {\n getCartQuery,\n getCustomerCartQuery,\n} from '@/checkout/api/getCart/graphql';\nimport { transformCart } from '@/checkout/data/transforms';\nimport { dispatchApiCall } from '@/checkout/lib/dispatchApiCall';\nimport { state } from '@/checkout/lib';\nimport { MissingCart } from '@/checkout/lib/errors';\n\nexport const getCart = async () => {\n const cartId = state.cartId;\n const isGuest = state.authenticated === false;\n const query = isGuest ? getCartQuery : getCustomerCartQuery;\n const variables = isGuest ? { cartId } : {};\n\n if (isGuest && !cartId) throw new MissingCart();\n\n return await dispatchApiCall({\n type: 'query',\n query,\n options: { method: 'POST', cache: 'no-cache', variables },\n path: 'cart',\n transformer: transformCart,\n });\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { NEGOTIABLE_QUOTE_FRAGMENT } from '@/checkout/api/graphql/NegotiableQuoteFragment.graphql';\n\nexport const getNegotiableQuoteQuery = /* GraphQL */ `\n query getNegotiableQuote($quoteId: ID!) {\n negotiableQuote(uid: $quoteId) {\n ...NEGOTIABLE_QUOTE_FRAGMENT\n }\n }\n\n ${NEGOTIABLE_QUOTE_FRAGMENT}\n`;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { getNegotiableQuoteQuery } from '@/checkout/api/getNegotiableQuote/graphql';\nimport { transformNegotiableQuote as transformer } from '@/checkout/data/transforms';\nimport { state } from '@/checkout/lib';\nimport { dispatchApiCall } from '@/checkout/lib/dispatchApiCall';\nimport {\n MissingNegotiableQuoteId,\n Unauthenticated,\n} from '@/checkout/lib/errors';\n\ntype GetNegotiableQuoteInput = {\n uid?: string;\n};\n\nexport const getNegotiableQuote = async (\n input: GetNegotiableQuoteInput = {}\n) => {\n const quoteId = input.uid ?? state.quoteId;\n const isGuest = state.authenticated === false;\n\n if (isGuest) throw new Unauthenticated();\n if (!quoteId) throw new MissingNegotiableQuoteId();\n\n const variables = { quoteId };\n\n return await dispatchApiCall({\n type: 'query',\n query: getNegotiableQuoteQuery,\n options: { method: 'GET', cache: 'no-cache', variables },\n path: 'negotiableQuote',\n transformer,\n });\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport {\n authenticateCustomer,\n ConfigProps,\n initializeCheckout,\n resetCheckout,\n synchronizeCheckout,\n} from '@/checkout/api';\nimport { ErrorCodes } from '@/checkout/lib/errors';\nimport { PermissionsModel } from '@/checkout/types';\nimport { events, Events } from '@adobe-commerce/event-bus';\n\ntype Listener = [keyof Events, (...args: any[]) => void, { eager: boolean }?];\n\nconst asEager = { eager: true };\n\nexport const addCheckoutEventListeners = (config: ConfigProps | undefined) => {\n const useB2bQuotes = config?.features?.b2b?.quotes ?? false;\n\n const handleAuthenticated = (isAuthenticated = false) => {\n authenticateCustomer(isAuthenticated);\n\n if (!useB2bQuotes) return;\n if (isAuthenticated) return;\n\n const destination = config?.features?.b2b?.routeLogin?.();\n if (destination) {\n window.location.assign(destination);\n }\n };\n\n const cartListeners: Listener[] = [\n ['cart/initialized', initializeCheckout, asEager],\n ['cart/reset', resetCheckout],\n ['cart/updated', synchronizeCheckout],\n [\n 'auth/permissions',\n (permissions: PermissionsModel) => {\n if (!permissions['Magento_Sales::place_order']) {\n const message =\n config?.langDefinitions?.default?.Checkout?.ServerError\n ?.permissionDenied ||\n 'You do not have permission to complete checkout. Please contact your administrator for assistance.';\n events.emit('checkout/error', {\n message,\n code: ErrorCodes.PERMISSION_DENIED,\n });\n }\n },\n asEager,\n ],\n ];\n\n const quoteListeners: Listener[] = [\n [\n 'quote-management/quote-data/initialized',\n (data) => {\n if (!data.quote.canCheckout) {\n const message =\n config?.langDefinitions?.default?.Checkout?.Quote\n ?.permissionDenied ||\n 'You do not have permission to checkout with this quote.';\n events.emit('checkout/error', {\n message,\n code: ErrorCodes.QUOTE_PERMISSION_DENIED,\n });\n return;\n }\n\n initializeCheckout(data.quote);\n },\n asEager,\n ],\n [\n 'quote-management/quote-data/error',\n () => {\n const message =\n config?.langDefinitions?.default?.Checkout?.Quote?.dataError ||\n 'We were unable to retrieve the quote data. Please try again later.';\n events.emit('checkout/error', {\n message,\n code: ErrorCodes.QUOTE_DATA_ERROR,\n });\n },\n ],\n ];\n\n const listeners: Listener[] = [\n ['authenticated', handleAuthenticated, asEager],\n ...(useB2bQuotes ? quoteListeners : cartListeners),\n ];\n\n return listeners.map(([eventName, handler, options]) => {\n return events.on(eventName, handler, options);\n });\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { addCheckoutEventListeners } from '@/checkout/api/initialize/listeners';\nimport {\n Cart as CartModel,\n Customer as CustomerModel,\n ShippingMethod,\n} from '@/checkout/data/models';\nimport { state } from '@/checkout/lib';\nimport { Filter, Selector } from '@/checkout/types/utils';\nimport { definition } from '@adobe-commerce/elsie/i18n';\nimport { deepmerge, Initializer, Model } from '@adobe-commerce/elsie/lib';\n\nconst url = new URL(window.location.href);\nconst quoteId = url.searchParams.get('quoteId');\nstate.quoteId = quoteId;\n\nexport type ConfigProps = {\n defaults?: {\n isBillToShipping?: boolean;\n selectedShippingMethod?: Selector<ShippingMethod>;\n };\n shipping?: {\n filterOptions?: Filter<ShippingMethod>;\n };\n features?: {\n b2b?: {\n quotes?: boolean;\n routeLogin?: () => string | void;\n };\n };\n langDefinitions?: typeof definition & { default: { Checkout: any } };\n models?: {\n CartModel?: Model<CartModel>;\n CustomerModel?: Model<CustomerModel>;\n };\n};\n\nexport const initialize = new Initializer<ConfigProps>({\n init: async (_config = {}) => {\n initialize.config.setConfig(\n deepmerge(\n {\n defaults: {\n isBillToShipping: true,\n selectedShippingMethod: (options) => {\n return options.length > 0 ? options[0] : null;\n },\n },\n features: {\n b2b: { quotes: false },\n },\n },\n _config\n )\n );\n },\n listeners: addCheckoutEventListeners,\n});\n\nexport const config = initialize.config;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport {\n CartModel,\n InitializeInput,\n NegotiableQuoteModel,\n SynchronizeInput,\n} from '@/checkout/types';\n\nexport const isCartInput = (\n input: NonNullable<InitializeInput | SynchronizeInput>\n): input is CartModel => {\n return 'id' in input;\n};\n\nexport const isNegotiableQuoteInput = (\n input: NonNullable<InitializeInput | SynchronizeInput>\n): input is NegotiableQuoteModel => {\n return 'uid' in input;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport {\n getCart,\n getNegotiableQuote,\n getStoreConfig,\n synchronizeCheckout,\n} from '@/checkout/api';\nimport { state } from '@/checkout/lib';\nimport { InitializeInput, isCartInput } from '@/checkout/types';\nimport { events } from '@adobe-commerce/event-bus';\n\nconst getInitialData = async (input: NonNullable<InitializeInput>) => {\n try {\n if (isCartInput(input)) {\n state.cartId = input.id;\n state.quoteId = null;\n return (await getCart()) ?? null;\n }\n state.cartId = null;\n state.quoteId = input.uid;\n return (await getNegotiableQuote()) ?? null;\n } catch (error) {\n console.error('Checkout initialization failed:', error);\n return null;\n }\n};\n\nexport const initializeCheckout = async (input: InitializeInput) => {\n if (state.initialized) {\n await synchronizeCheckout(input);\n return;\n }\n\n if (!state.config) {\n state.config = await getStoreConfig();\n }\n\n const initialData = input ? await getInitialData(input) : null;\n\n state.initialized = true;\n events.emit('checkout/initialized', initialData);\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { state } from '@/checkout/lib/state';\nimport { events } from '@adobe-commerce/event-bus';\n\nexport const resetCheckout = () => {\n if (!state.initialized) return;\n state.cartId = null;\n state.quoteId = null;\n events.emit('checkout/updated', null);\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport {\n getCart,\n getNegotiableQuote,\n initializeCheckout,\n resetCheckout,\n} from '@/checkout/api';\nimport { state } from '@/checkout/lib/state';\nimport { isCartInput, SynchronizeInput } from '@/checkout/types';\nimport { events } from '@adobe-commerce/event-bus';\n\nconst getSynchronizedData = async (input: NonNullable<SynchronizeInput>) => {\n try {\n if (isCartInput(input)) {\n state.cartId = input.id;\n state.quoteId = null;\n return (await getCart()) ?? null;\n }\n state.cartId = null;\n state.quoteId = input.uid;\n return (await getNegotiableQuote()) ?? null;\n } catch (error) {\n console.error('Checkout synchronization failed:', error);\n return null;\n }\n};\n\nexport const synchronizeCheckout = async (data: SynchronizeInput) => {\n if (!state.initialized) return initializeCheckout(data);\n\n if (data === null) {\n resetCheckout();\n return;\n }\n\n const update = await getSynchronizedData(data);\n\n events.emit('checkout/updated', update);\n};\n"],"names":["authenticateCustomer","authenticated","state","transformSelectedPaymentMethod","data","code","title","additionalData","transformAvailablePaymentMethods","method","transformCart","model","transformCartBillingAddress","transformCartShippingAddress","merge","_c","_b","_a","config","transformAddress","street","transformAddressCountry","transformCustomAttributes","transformAddressRegion","transformQuoteBillingAddress","transformQuoteShippingAddress","address","available_shipping_methods","selected_shipping_method","baseData","transformShippingMethods","transformSelectedShippingMethod","transformNegotiableQuote","getCartQuery","CHECKOUT_DATA_FRAGMENT","getCustomerCartQuery","getCart","cartId","isGuest","query","variables","MissingCart","dispatchApiCall","getNegotiableQuoteQuery","NEGOTIABLE_QUOTE_FRAGMENT","getNegotiableQuote","input","quoteId","Unauthenticated","MissingNegotiableQuoteId","transformer","asEager","addCheckoutEventListeners","useB2bQuotes","isAuthenticated","destination","message","_d","events","ErrorCodes","initializeCheckout","resetCheckout","synchronizeCheckout","permissions","eventName","handler","options","url","initialize","Initializer","_config","deepmerge","isCartInput","getInitialData","error","getStoreConfig","initialData","getSynchronizedData","update"],"mappings":"waAmBa,MAAAA,EAAuB,MAAOC,EAAgB,KAAU,CACnEC,EAAM,cAAgBD,CACxB,ECWME,EACJC,GAC8B,CAC9B,GAAI,CAACA,EAAM,OACX,KAAM,CAAE,KAAAC,EAAM,MAAAC,EAAO,GAAGC,CAAmB,EAAAH,EACpC,MAAA,CAAE,KAAAC,EAAM,MAAAC,EAAO,eAAAC,CAAe,CACvC,EAEMC,EACJJ,GACgC,CAChC,GAAKA,EAEE,OAAAA,EACJ,OAAQK,GAAW,CAAC,CAACA,CAAM,EAC3B,IAAKA,GAAW,CACf,KAAM,CAAE,KAAAJ,EAAM,MAAAC,EAAO,GAAGC,CACtB,EAAAE,EACK,MAAA,CAAE,KAAAJ,EAAM,MAAAC,EAAO,eAAAC,CAAe,CAAA,CACtC,CACL,EClBMG,EAAiBN,GAAsC,WAC3D,GAAI,CAACA,EAAM,O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,EAAqB,MAAOd,GAA2B,CAClE,GAAI5C,EAAM,YAAa,CACrB,MAAM4D,EAAoBhB,CAAK,EAC/B,MAAA,CAGG5C,EAAM,SACHA,EAAA,OAAS,MAAMyE,EAAe,GAGtC,MAAMC,EAAc9B,EAAQ,MAAM2B,GAAe3B,CAAK,EAAI,KAE1D5C,EAAM,YAAc,GACbwD,EAAA,KAAK,uBAAwBkB,CAAW,CACjD,ECrCaf,EAAgB,IAAM,CAC5B3D,EAAM,cACXA,EAAM,OAAS,KACfA,EAAM,QAAU,KACTwD,EAAA,KAAK,mBAAoB,IAAI,EACtC,ECEMmB,GAAsB,MAAO/B,GAAyC,CACtE,GAAA,CACE,OAAA0B,EAAY1B,CAAK,GACnB5C,EAAM,OAAS4C,EAAM,GACrB5C,EAAM,QAAU,KACR,MAAMkC,KAAc,OAE9BlC,EAAM,OAAS,KACfA,EAAM,QAAU4C,EAAM,IACd,MAAMD,KAAyB,YAChC6B,EAAO,CACN,eAAA,MAAM,mCAAoCA,CAAK,EAChD,IAAA,CAEX,EAEaZ,EAAsB,MAAO1D,GAA2B,CACnE,GAAI,CAACF,EAAM,YAAa,OAAO0D,EAAmBxD,CAAI,EAEtD,GAAIA,IAAS,KAAM,CACHyD,EAAA,EACd,MAAA,CAGI,MAAAiB,EAAS,MAAMD,GAAoBzE,CAAI,EAEtCsD,EAAA,KAAK,mBAAoBoB,CAAM,CACxC"}
|
|
1
|
+
{"version":3,"file":"synchronizeCheckout.js","sources":["/@dropins/storefront-checkout/src/api/authenticateCustomer/authenticateCustomer.ts","/@dropins/storefront-checkout/src/data/transforms/transform-payment-methods.ts","/@dropins/storefront-checkout/src/data/transforms/transform-cart.ts","/@dropins/storefront-checkout/src/data/transforms/transform-quote-address.ts","/@dropins/storefront-checkout/src/data/transforms/transform-negotiable-quote.ts","/@dropins/storefront-checkout/src/api/getCart/graphql/getCart.graphql.ts","/@dropins/storefront-checkout/src/api/getCart/getCart.ts","/@dropins/storefront-checkout/src/api/getNegotiableQuote/graphql/getNegotiableQuote.graphql.ts","/@dropins/storefront-checkout/src/api/getNegotiableQuote/getNegotiableQuote.ts","/@dropins/storefront-checkout/src/api/initialize/listeners.ts","/@dropins/storefront-checkout/src/api/initialize/initialize.ts","/@dropins/storefront-checkout/src/types/guards.ts","/@dropins/storefront-checkout/src/api/initializeCheckout/initializeCheckout.ts","/@dropins/storefront-checkout/src/api/resetCheckout/resetCheckout.ts","/@dropins/storefront-checkout/src/api/synchronizeCheckout/synchronizeCheckout.ts"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { state } from '@/checkout/lib/state';\n\nexport const authenticateCustomer = async (authenticated = false) => {\n state.authenticated = authenticated;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { PaymentMethod } from '@/checkout/data/models/payment-method';\nimport { GetCartQuery } from '@/checkout/__generated__/types';\n\ntype SelectedPaymentMethod = NonNullable<\n GetCartQuery['cart']\n>['selected_payment_method'];\n\ntype AvailablePaymentMethods = NonNullable<\n GetCartQuery['cart']\n>['available_payment_methods'];\n\ntype AvailablePaymentMethod = NonNullable<AvailablePaymentMethods>[number];\n\ntype NonNullabePaymentMethod = NonNullable<AvailablePaymentMethod>;\n\nconst transformSelectedPaymentMethod = (\n data: SelectedPaymentMethod\n): PaymentMethod | undefined => {\n if (!data) return;\n const { code, title, ...additionalData } = data;\n return { code, title, additionalData };\n};\n\nconst transformAvailablePaymentMethods = (\n data: AvailablePaymentMethods\n): PaymentMethod[] | undefined => {\n if (!data) return;\n\n return data\n .filter((method) => !!method)\n .map((method) => {\n const { code, title, ...additionalData } =\n method as NonNullabePaymentMethod;\n return { code, title, additionalData };\n });\n};\n\nexport { transformAvailablePaymentMethods, transformSelectedPaymentMethod };\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { config } from '@/checkout/api';\nimport { Cart as CartModel } from '@/checkout/data/models';\nimport {\n transformAvailablePaymentMethods,\n transformSelectedPaymentMethod,\n} from '@/checkout/data/transforms/transform-payment-methods';\nimport { GetCartQuery } from '@/checkout/__generated__/types';\nimport { merge } from '@adobe-commerce/elsie/lib';\n\nimport {\n transformCartBillingAddress,\n transformCartShippingAddress,\n} from '@/checkout/data/transforms/transform-cart-address';\nimport { state } from '@/checkout/lib/state';\n\ntype Cart = GetCartQuery['cart'];\n\nconst transformCart = (data: Cart): CartModel | undefined => {\n if (!data) return;\n\n const model = {\n type: 'cart' as const,\n availablePaymentMethods: transformAvailablePaymentMethods(\n data.available_payment_methods\n ),\n billingAddress: transformCartBillingAddress(data.billing_address),\n email: data.email ?? undefined,\n id: data.id,\n isEmpty: data.total_quantity === 0,\n isVirtual: data.is_virtual,\n selectedPaymentMethod: transformSelectedPaymentMethod(\n data.selected_payment_method\n ),\n shippingAddresses: transformCartShippingAddress(data.shipping_addresses),\n isGuest: !state.authenticated,\n };\n\n // Extend the model merging custom transformer, if provided\n return merge(\n model, // default transformer\n config.getConfig().models?.CartModel?.transformer?.(data) // custom transformer\n );\n};\n\nexport { Cart, transformCart };\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport {\n Address as AddressModel,\n ShippingAddress as ShippingAddressModel,\n} from '@/checkout/data/models';\n\nimport {\n transformAddressCountry,\n transformAddressRegion,\n transformCustomAttributes,\n transformSelectedShippingMethod,\n transformShippingMethods,\n} from '@/checkout/data/transforms';\nimport { GetNegotiableQuoteQuery } from '@/checkout/__generated__/types';\n\ntype QuoteShippingAddresses = NonNullable<\n GetNegotiableQuoteQuery['negotiableQuote']\n>['shipping_addresses'];\ntype QuoteShippingAddress = QuoteShippingAddresses[0];\ntype NonNullableShippingAddress = NonNullable<QuoteShippingAddress>;\n\ntype QuoteBillingAddress = NonNullable<\n GetNegotiableQuoteQuery['negotiableQuote']\n>['billing_address'];\ntype NonNullableBillingAddress = NonNullable<QuoteBillingAddress>;\n\nconst transformAddress = (\n data: NonNullableShippingAddress | NonNullableBillingAddress\n): AddressModel => {\n const street = data.street.filter(Boolean) as string[];\n\n return {\n city: data.city,\n company: data.company || undefined,\n country: transformAddressCountry(data.country),\n customAttributes: transformCustomAttributes(data.custom_attributes),\n customerAddressUid: data.customer_address_uid || undefined,\n fax: data.fax || undefined,\n firstName: data.firstname,\n lastName: data.lastname,\n middleName: data.middlename || undefined,\n postCode: data.postcode || undefined,\n prefix: data.prefix || undefined,\n region: transformAddressRegion(data.region),\n street,\n suffix: data.suffix || undefined,\n telephone: data.telephone || undefined,\n uid: data.uid,\n vatId: data.vat_id || undefined,\n };\n};\n\nconst transformQuoteBillingAddress = (\n data: QuoteBillingAddress\n): AddressModel | undefined => {\n if (!data) return;\n return transformAddress(data);\n};\n\nconst transformQuoteShippingAddress = (\n data: QuoteShippingAddresses\n): ShippingAddressModel[] => {\n return data\n .filter((address) => !!address)\n .map((address) => {\n const {\n available_shipping_methods,\n selected_shipping_method,\n ...baseData\n } = address as NonNullableShippingAddress;\n\n return {\n ...transformAddress(baseData as NonNullableShippingAddress),\n availableShippingMethods: transformShippingMethods(\n available_shipping_methods\n ),\n selectedShippingMethod: transformSelectedShippingMethod(\n selected_shipping_method\n ),\n };\n });\n};\n\nexport {\n QuoteBillingAddress,\n QuoteShippingAddress,\n transformQuoteBillingAddress,\n transformQuoteShippingAddress,\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { NegotiableQuote as NegotiableQuoteModel } from '@/checkout/data/models/';\nimport { GetNegotiableQuoteQuery } from '@/checkout/__generated__/types';\n\nimport {\n transformAvailablePaymentMethods,\n transformQuoteBillingAddress,\n transformQuoteShippingAddress,\n transformSelectedPaymentMethod,\n} from '@/checkout/data/transforms';\n\ntype NegotiableQuote = GetNegotiableQuoteQuery['negotiableQuote'];\n\nexport const transformNegotiableQuote = (\n data: NegotiableQuote | undefined\n): NegotiableQuoteModel | null => {\n if (!data) return null;\n\n return {\n type: 'quote' as const,\n availablePaymentMethods: transformAvailablePaymentMethods(\n data.available_payment_methods\n ),\n billingAddress: transformQuoteBillingAddress(data.billing_address),\n email: data.email ?? '',\n isEmpty: data.total_quantity === 0,\n isVirtual: data.is_virtual,\n name: data.name,\n selectedPaymentMethod: transformSelectedPaymentMethod(\n data.selected_payment_method\n ),\n shippingAddresses: transformQuoteShippingAddress(data.shipping_addresses),\n status: data.status,\n uid: data.uid,\n };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { CHECKOUT_DATA_FRAGMENT } from '@/checkout/api/graphql/CheckoutDataFragment.graphql';\n\nexport const getCartQuery = /* GraphQL */ `\n query getCart($cartId: String!) {\n cart(cart_id: $cartId) {\n ...CHECKOUT_DATA_FRAGMENT\n }\n }\n\n ${CHECKOUT_DATA_FRAGMENT}\n`;\n\nexport const getCustomerCartQuery = /* GraphQL */ `\n query getCustomerCart {\n cart: customerCart {\n ...CHECKOUT_DATA_FRAGMENT\n }\n }\n\n ${CHECKOUT_DATA_FRAGMENT}\n`;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport {\n getCartQuery,\n getCustomerCartQuery,\n} from '@/checkout/api/getCart/graphql';\nimport { transformCart } from '@/checkout/data/transforms';\nimport { dispatchApiCall } from '@/checkout/lib/dispatchApiCall';\nimport { state } from '@/checkout/lib';\nimport { MissingCart } from '@/checkout/lib/errors';\n\nexport const getCart = async () => {\n const cartId = state.cartId;\n const isGuest = state.authenticated === false;\n const query = isGuest ? getCartQuery : getCustomerCartQuery;\n const variables = isGuest ? { cartId } : {};\n\n if (isGuest && !cartId) throw new MissingCart();\n\n return await dispatchApiCall({\n type: 'query',\n query,\n options: { method: 'POST', cache: 'no-cache', variables },\n path: 'cart',\n transformer: transformCart,\n });\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { NEGOTIABLE_QUOTE_FRAGMENT } from '@/checkout/api/graphql/NegotiableQuoteFragment.graphql';\n\nexport const getNegotiableQuoteQuery = /* GraphQL */ `\n query getNegotiableQuote($quoteId: ID!) {\n negotiableQuote(uid: $quoteId) {\n ...NEGOTIABLE_QUOTE_FRAGMENT\n }\n }\n\n ${NEGOTIABLE_QUOTE_FRAGMENT}\n`;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { getNegotiableQuoteQuery } from '@/checkout/api/getNegotiableQuote/graphql';\nimport { transformNegotiableQuote as transformer } from '@/checkout/data/transforms';\nimport { state } from '@/checkout/lib';\nimport { dispatchApiCall } from '@/checkout/lib/dispatchApiCall';\nimport {\n MissingNegotiableQuoteId,\n Unauthenticated,\n} from '@/checkout/lib/errors';\n\ntype GetNegotiableQuoteInput = {\n uid?: string;\n};\n\nexport const getNegotiableQuote = async (\n input: GetNegotiableQuoteInput = {}\n) => {\n const quoteId = input.uid ?? state.quoteId;\n const isGuest = state.authenticated === false;\n\n if (isGuest) throw new Unauthenticated();\n if (!quoteId) throw new MissingNegotiableQuoteId();\n\n const variables = { quoteId };\n\n return await dispatchApiCall({\n type: 'query',\n query: getNegotiableQuoteQuery,\n options: { method: 'GET', cache: 'no-cache', variables },\n path: 'negotiableQuote',\n transformer,\n });\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport {\n authenticateCustomer,\n ConfigProps,\n initializeCheckout,\n resetCheckout,\n synchronizeCheckout,\n} from '@/checkout/api';\nimport { ErrorCodes } from '@/checkout/lib/errors';\nimport { PermissionsModel } from '@/checkout/types';\nimport { events, Events } from '@adobe-commerce/event-bus';\n\ntype Listener = [keyof Events, (...args: any[]) => void, { eager: boolean }?];\n\nconst asEager = { eager: true };\n\nexport const addCheckoutEventListeners = (config: ConfigProps | undefined) => {\n const useB2bQuotes = config?.features?.b2b?.quotes ?? false;\n\n const handleAuthenticated = (isAuthenticated = false) => {\n authenticateCustomer(isAuthenticated);\n\n if (!useB2bQuotes) return;\n if (isAuthenticated) return;\n\n const destination = config?.features?.b2b?.routeLogin?.();\n if (destination) {\n window.location.assign(destination);\n }\n };\n\n const cartListeners: Listener[] = [\n ['cart/initialized', initializeCheckout, asEager],\n ['cart/reset', resetCheckout],\n ['cart/updated', synchronizeCheckout],\n [\n 'auth/permissions',\n (permissions: PermissionsModel) => {\n if (permissions['admin'] === true) return;\n\n if (!permissions['Magento_Sales::place_order']) {\n const message =\n config?.langDefinitions?.default?.Checkout?.ServerError\n ?.permissionDenied ||\n 'You do not have permission to complete checkout. Please contact your administrator for assistance.';\n events.emit('checkout/error', {\n message,\n code: ErrorCodes.PERMISSION_DENIED,\n });\n }\n },\n asEager,\n ],\n ];\n\n const quoteListeners: Listener[] = [\n [\n 'quote-management/quote-data/initialized',\n (data) => {\n if (!data.quote.canCheckout) {\n const message =\n config?.langDefinitions?.default?.Checkout?.Quote\n ?.permissionDenied ||\n 'You do not have permission to checkout with this quote.';\n events.emit('checkout/error', {\n message,\n code: ErrorCodes.QUOTE_PERMISSION_DENIED,\n });\n return;\n }\n\n initializeCheckout(data.quote);\n },\n asEager,\n ],\n [\n 'quote-management/quote-data/error',\n () => {\n const message =\n config?.langDefinitions?.default?.Checkout?.Quote?.dataError ||\n 'We were unable to retrieve the quote data. Please try again later.';\n events.emit('checkout/error', {\n message,\n code: ErrorCodes.QUOTE_DATA_ERROR,\n });\n },\n ],\n ];\n\n const listeners: Listener[] = [\n ['authenticated', handleAuthenticated, asEager],\n ...(useB2bQuotes ? quoteListeners : cartListeners),\n ];\n\n return listeners.map(([eventName, handler, options]) => {\n return events.on(eventName, handler, options);\n });\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { addCheckoutEventListeners } from '@/checkout/api/initialize/listeners';\nimport {\n Cart as CartModel,\n Customer as CustomerModel,\n ShippingMethod,\n} from '@/checkout/data/models';\nimport { state } from '@/checkout/lib';\nimport { Filter, Selector } from '@/checkout/types/utils';\nimport { definition } from '@adobe-commerce/elsie/i18n';\nimport { deepmerge, Initializer, Model } from '@adobe-commerce/elsie/lib';\n\nconst url = new URL(window.location.href);\nconst quoteId = url.searchParams.get('quoteId');\nstate.quoteId = quoteId;\n\nexport type ConfigProps = {\n defaults?: {\n isBillToShipping?: boolean;\n selectedShippingMethod?: Selector<ShippingMethod>;\n };\n shipping?: {\n filterOptions?: Filter<ShippingMethod>;\n };\n features?: {\n b2b?: {\n quotes?: boolean;\n routeLogin?: () => string | void;\n };\n };\n langDefinitions?: typeof definition & { default: { Checkout: any } };\n models?: {\n CartModel?: Model<CartModel>;\n CustomerModel?: Model<CustomerModel>;\n };\n};\n\nexport const initialize = new Initializer<ConfigProps>({\n init: async (_config = {}) => {\n initialize.config.setConfig(\n deepmerge(\n {\n defaults: {\n isBillToShipping: true,\n selectedShippingMethod: (options) => {\n return options.length > 0 ? options[0] : null;\n },\n },\n features: {\n b2b: { quotes: false },\n },\n },\n _config\n )\n );\n },\n listeners: addCheckoutEventListeners,\n});\n\nexport const config = initialize.config;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport {\n CartModel,\n InitializeInput,\n NegotiableQuoteModel,\n SynchronizeInput,\n} from '@/checkout/types';\n\nexport const isCartInput = (\n input: NonNullable<InitializeInput | SynchronizeInput>\n): input is CartModel => {\n return 'id' in input;\n};\n\nexport const isNegotiableQuoteInput = (\n input: NonNullable<InitializeInput | SynchronizeInput>\n): input is NegotiableQuoteModel => {\n return 'uid' in input;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport {\n getCart,\n getNegotiableQuote,\n getStoreConfig,\n synchronizeCheckout,\n} from '@/checkout/api';\nimport { state } from '@/checkout/lib';\nimport { InitializeInput, isCartInput } from '@/checkout/types';\nimport { events } from '@adobe-commerce/event-bus';\n\nconst getInitialData = async (input: NonNullable<InitializeInput>) => {\n try {\n if (isCartInput(input)) {\n state.cartId = input.id;\n state.quoteId = null;\n return (await getCart()) ?? null;\n }\n state.cartId = null;\n state.quoteId = input.uid;\n return (await getNegotiableQuote()) ?? null;\n } catch (error) {\n console.error('Checkout initialization failed:', error);\n return null;\n }\n};\n\nexport const initializeCheckout = async (input: InitializeInput) => {\n if (state.initialized) {\n await synchronizeCheckout(input);\n return;\n }\n\n if (!state.config) {\n state.config = await getStoreConfig();\n }\n\n const initialData = input ? await getInitialData(input) : null;\n\n state.initialized = true;\n events.emit('checkout/initialized', initialData);\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { state } from '@/checkout/lib/state';\nimport { events } from '@adobe-commerce/event-bus';\n\nexport const resetCheckout = () => {\n if (!state.initialized) return;\n state.cartId = null;\n state.quoteId = null;\n events.emit('checkout/updated', null);\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport {\n getCart,\n getNegotiableQuote,\n initializeCheckout,\n resetCheckout,\n} from '@/checkout/api';\nimport { state } from '@/checkout/lib/state';\nimport { isCartInput, SynchronizeInput } from '@/checkout/types';\nimport { events } from '@adobe-commerce/event-bus';\n\nconst getSynchronizedData = async (input: NonNullable<SynchronizeInput>) => {\n try {\n if (isCartInput(input)) {\n state.cartId = input.id;\n state.quoteId = null;\n return (await getCart()) ?? null;\n }\n state.cartId = null;\n state.quoteId = input.uid;\n return (await getNegotiableQuote()) ?? null;\n } catch (error) {\n console.error('Checkout synchronization failed:', error);\n return null;\n }\n};\n\nexport const synchronizeCheckout = async (data: SynchronizeInput) => {\n if (!state.initialized) return initializeCheckout(data);\n\n if (data === null) {\n resetCheckout();\n return;\n }\n\n const update = await getSynchronizedData(data);\n\n events.emit('checkout/updated', update);\n};\n"],"names":["authenticateCustomer","authenticated","state","transformSelectedPaymentMethod","data","code","title","additionalData","transformAvailablePaymentMethods","method","transformCart","model","transformCartBillingAddress","transformCartShippingAddress","merge","_c","_b","_a","config","transformAddress","street","transformAddressCountry","transformCustomAttributes","transformAddressRegion","transformQuoteBillingAddress","transformQuoteShippingAddress","address","available_shipping_methods","selected_shipping_method","baseData","transformShippingMethods","transformSelectedShippingMethod","transformNegotiableQuote","getCartQuery","CHECKOUT_DATA_FRAGMENT","getCustomerCartQuery","getCart","cartId","isGuest","query","variables","MissingCart","dispatchApiCall","getNegotiableQuoteQuery","NEGOTIABLE_QUOTE_FRAGMENT","getNegotiableQuote","input","quoteId","Unauthenticated","MissingNegotiableQuoteId","transformer","asEager","addCheckoutEventListeners","useB2bQuotes","isAuthenticated","destination","message","_d","events","ErrorCodes","initializeCheckout","resetCheckout","synchronizeCheckout","permissions","eventName","handler","options","url","initialize","Initializer","_config","deepmerge","isCartInput","getInitialData","error","getStoreConfig","initialData","getSynchronizedData","update"],"mappings":"waAmBa,MAAAA,EAAuB,MAAOC,EAAgB,KAAU,CACnEC,EAAM,cAAgBD,CACxB,ECWME,EACJC,GAC8B,CAC9B,GAAI,CAACA,EAAM,OACX,KAAM,CAAE,KAAAC,EAAM,MAAAC,EAAO,GAAGC,CAAmB,EAAAH,EACpC,MAAA,CAAE,KAAAC,EAAM,MAAAC,EAAO,eAAAC,CAAe,CACvC,EAEMC,EACJJ,GACgC,CAChC,GAAKA,EAEE,OAAAA,EACJ,OAAQK,GAAW,CAAC,CAACA,CAAM,EAC3B,IAAKA,GAAW,CACf,KAAM,CAAE,KAAAJ,EAAM,MAAAC,EAAO,GAAGC,CACtB,EAAAE,EACK,MAAA,CAAE,KAAAJ,EAAM,MAAAC,EAAO,eAAAC,CAAe,CAAA,CACtC,CACL,EClBMG,EAAiBN,GAAsC,WAC3D,GAAI,CAACA,EAAM,OAEX,MAAMO,EAAQ,CACZ,KAAM,OACN,wBAAyBH,EACvBJ,EAAK,yBACP,EACA,eAAgBQ,EAA4BR,EAAK,eAAe,EAChE,MAAOA,EAAK,OAAS,OACrB,GAAIA,EAAK,GACT,QAASA,EAAK,iBAAmB,EACjC,UAAWA,EAAK,WAChB,sBAAuBD,EACrBC,EAAK,uBACP,EACA,kBAAmBS,EAA6BT,EAAK,kBAAkB,EACvE,QAAS,CAACF,EAAM,aAClB,EAGO,OAAAY,EACLH,GACAI,GAAAC,GAAAC,EAAAC,GAAO,UAAU,EAAE,SAAnB,YAAAD,EAA2B,YAA3B,YAAAD,EAAsC,cAAtC,YAAAD,EAAA,KAAAC,EAAoDZ,EACtD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,GAAyC,CACtE,GAAA,CACE,OAAA0B,EAAY1B,CAAK,GACnB5C,EAAM,OAAS4C,EAAM,GACrB5C,EAAM,QAAU,KACR,MAAMkC,KAAc,OAE9BlC,EAAM,OAAS,KACfA,EAAM,QAAU4C,EAAM,IACd,MAAMD,KAAyB,YAChC6B,EAAO,CACN,eAAA,MAAM,mCAAoCA,CAAK,EAChD,IAAA,CAEX,EAEaZ,EAAsB,MAAO1D,GAA2B,CACnE,GAAI,CAACF,EAAM,YAAa,OAAO0D,EAAmBxD,CAAI,EAEtD,GAAIA,IAAS,KAAM,CACHyD,EAAA,EACd,MAAA,CAGI,MAAAiB,EAAS,MAAMD,GAAoBzE,CAAI,EAEtCsD,EAAA,KAAK,mBAAoBoB,CAAM,CACxC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
/*! Copyright 2025 Adobe
|
|
2
2
|
All Rights Reserved. */
|
|
3
|
-
import{jsx as n,jsxs as
|
|
3
|
+
import{jsx as n,jsxs as j}from"@dropins/tools/preact-jsx-runtime.js";import{h as w}from"../chunks/fetch-graphql.js";import"@dropins/tools/lib.js";import{h as C,a as L}from"../chunks/events2.js";import{n as R,g as U}from"../chunks/values.js";import{events as D}from"@dropins/tools/event-bus.js";import{c as W}from"../chunks/synchronizeCheckout.js";import{s as V}from"../chunks/setBillingAddress.js";/* empty css */import{Skeleton as P,SkeletonRow as $,Checkbox as q,InLineAlert as y}from"@dropins/tools/components.js";import{W as F}from"../chunks/ConditionalWrapper.js";import{c as G}from"../chunks/classes.js";import{useText as E}from"@dropins/tools/i18n.js";import{useState as b,useRef as H,useCallback as A,useEffect as B}from"@dropins/tools/preact-hooks.js";import"@dropins/tools/signals.js";import"@dropins/tools/fetch-graphql.js";import"../fragments.js";import"../chunks/transform-shipping-methods.js";import"../chunks/classifiers.js";import"../chunks/guards.js";const J=()=>n(P,{className:"bill-to-shipping-address__skeleton","data-testid":"bill-to-shipping-skeleton",children:n($,{size:"small",variant:"row"})}),K=({className:i,checked:c,disabled:e,error:t=null,onChange:p=()=>{},onDismissError:a=()=>{}})=>{const f=E({title:"Checkout.BillToShippingAddress.title"}),g=t!==null,r=l=>{const d=l.target;p==null||p(d.checked)};return j("div",{className:"checkout-bill-to-shipping-address",children:[n(q,{checked:c,className:G(["checkout-bill-to-shipping-address__checkbox",i]),"data-testid":"bill-to-shipping-checkbox",disabled:e,label:f.title,name:"checkout-bill-to-shipping-address__checkbox",onChange:r}),g&&n("div",{className:"checkout-bill-to-shipping-address__error","data-testid":"checkout-bill-to-shipping-address-alert",children:n(y,{heading:t,type:"error",variant:"primary",onDismiss:a})})]})},M=F(K,J),fs=({active:i=!0,autoSync:c=!0,onCartSyncError:e,onChange:t})=>{const[p,a]=b(null),[f,g]=b(!1),[r,l]=b(),d=H(!1),I=w.value,{cartSyncError:S}=E({cartSyncError:"Checkout.BillToShippingAddress.cartSyncError"}),N=A(()=>{a(null)},[]),v=A(s=>{a(null),l(s),t==null||t(s),!(!c||!s||!C())&&V({sameAsShipping:!0}).catch(o=>{l(!1),e==null||e({error:o}),e||a(S)})},[c,S,e,t]),h=A(s=>{var _;const o=!s||s.isEmpty,u=!!(s!=null&&s.isVirtual);if(o||u){g(u),l(!1),d.current=!1;return}if(d.current)return;const x=s,k=(_=x.shippingAddresses)==null?void 0:_[0],T=!!x.billingAddress;let m;if(k)m=k.sameAsBilling??!T;else{const{defaults:z}=W.getConfig();m=z.isBillToShipping}l(m),d.current=!0,c&&m&&k&&!T&&V({sameAsShipping:!0}).catch(()=>{})},[]);return B(()=>{!i||r===void 0||R({isBillToShipping:r})},[i,r]),B(()=>{if(!i)return;const s=L();if(s){const u=U("isBillToShipping");u!=null&&l(u),h(s);return}const o=D.on("checkout/initialized",h,{eager:!0});return()=>{o==null||o.off()}},[i,h]),B(()=>{if(!i)return;const s=D.on("checkout/updated",h,{eager:!1});return()=>{s==null||s.off()}},[i,h]),n(M,{checked:r,disabled:I,error:p,initialized:r!==void 0,visible:i&&!f,onChange:v,onDismissError:N})};export{fs as BillToShippingAddress,fs as default};
|
|
4
4
|
//# sourceMappingURL=BillToShippingAddress.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BillToShippingAddress.js","sources":["/@dropins/storefront-checkout/src/components/BillToShippingAddress/BillToShippingAddressSkeleton.tsx","/@dropins/storefront-checkout/src/components/BillToShippingAddress/BillToShippingAddress.tsx","/@dropins/storefront-checkout/src/containers/BillToShippingAddress/BillToShippingAddress.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { Skeleton, SkeletonRow } from '@adobe-commerce/elsie/components';\nimport { FunctionComponent } from 'preact';\n\nexport const BillToShippingAddressSkeleton: FunctionComponent = () => {\n return (\n <Skeleton\n className=\"bill-to-shipping-address__skeleton\"\n data-testid=\"bill-to-shipping-skeleton\"\n >\n <SkeletonRow size=\"small\" variant=\"row\" />\n </Skeleton>\n );\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport '@/checkout/components/BillToShippingAddress/BillToShippingAddress.css';\nimport { BillToShippingAddressSkeleton } from '@/checkout/components/BillToShippingAddress/BillToShippingAddressSkeleton';\nimport { WithConditionals } from '@/checkout/components/ConditionalWrapper/ConditionalWrapper';\nimport { Checkbox, InLineAlert } from '@adobe-commerce/elsie/components';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { classes } from '@adobe-commerce/elsie/lib/classes';\nimport { FunctionComponent } from 'preact';\nimport { ChangeEvent, HTMLAttributes } from 'preact/compat';\n\nexport interface BillToShippingAddressProps\n extends Omit<\n HTMLAttributes<HTMLInputElement>,\n 'loading' | 'disabled' | 'onChange'\n > {\n disabled?: boolean;\n error?: string | null;\n onChange?: (checked: boolean) => void;\n onDismissError?: () => void;\n}\n\nconst BillToShippingAddressComponent: FunctionComponent<\n BillToShippingAddressProps\n> = ({\n className,\n checked,\n disabled,\n error = null,\n onChange = () => {},\n onDismissError = () => {},\n}) => {\n const translations = useText({\n title: 'Checkout.BillToShippingAddress.title',\n });\n\n const hasError = error !== null;\n\n const handleChange = (event: Event | ChangeEvent<HTMLInputElement>) => {\n const checkbox = event.target as HTMLInputElement;\n onChange?.(checkbox.checked);\n };\n\n return (\n <div className=\"checkout-bill-to-shipping-address\">\n <Checkbox\n checked={checked}\n className={classes([\n 'checkout-bill-to-shipping-address__checkbox',\n className,\n ])}\n data-testid=\"bill-to-shipping-checkbox\"\n disabled={disabled}\n label={translations.title}\n name=\"checkout-bill-to-shipping-address__checkbox\"\n onChange={handleChange}\n />\n\n {hasError && (\n <div\n className=\"checkout-bill-to-shipping-address__error\"\n data-testid=\"checkout-bill-to-shipping-address-alert\"\n >\n <InLineAlert\n heading={error}\n type=\"error\"\n variant=\"primary\"\n onDismiss={onDismissError}\n />\n </div>\n )}\n </div>\n );\n};\n\nexport const BillToShippingAddress = WithConditionals(\n BillToShippingAddressComponent,\n BillToShippingAddressSkeleton\n);\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { config, setBillingAddress } from '@/checkout/api';\nimport { BillToShippingAddress as BillToShippingAddressComponent } from '@/checkout/components/BillToShippingAddress';\nimport { Cart, NegotiableQuote } from '@/checkout/data/models';\nimport {\n getLatestCheckoutUpdate,\n getValue,\n hasPendingUpdates,\n hasShippingAddress,\n notifyValues,\n} from '@/checkout/lib';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { Container } from '@adobe-commerce/elsie/lib';\nimport { events } from '@adobe-commerce/event-bus';\nimport { HTMLAttributes } from 'preact/compat';\nimport { useCallback, useEffect, useRef, useState } from 'preact/hooks';\n\ninterface CartSyncError {\n error: Error;\n}\n\nexport interface BillToShippingAddressProps\n extends Omit<HTMLAttributes<HTMLDivElement>, 'onChange'> {\n active?: boolean;\n autoSync?: boolean;\n onCartSyncError?: (error: CartSyncError) => void;\n onChange?: (checked: boolean) => void;\n}\n\nexport const BillToShippingAddress: Container<BillToShippingAddressProps> = ({\n active = true,\n autoSync = true,\n onCartSyncError,\n onChange,\n}) => {\n const [error, setError] = useState<string | null>(null);\n const [isVirtual, setIsVirtual] = useState(false);\n const [isChecked, setIsChecked] = useState<boolean | undefined>();\n\n const hasInitialCartData = useRef(false);\n\n const isDisabled = hasPendingUpdates.value;\n\n const { cartSyncError } = useText({\n cartSyncError: 'Checkout.BillToShippingAddress.cartSyncError',\n });\n\n const handleDismissError = useCallback(() => {\n setError(null);\n }, []);\n\n const handleChange = useCallback(\n (isBillToShipping: boolean) => {\n setError(null);\n setIsChecked(isBillToShipping);\n\n onChange?.(isBillToShipping);\n\n if (!autoSync || !isBillToShipping || !hasShippingAddress()) {\n return;\n }\n\n setBillingAddress({ sameAsShipping: true }).catch((error: any) => {\n setIsChecked(false);\n onCartSyncError?.({ error });\n\n if (!onCartSyncError) {\n setError(cartSyncError);\n }\n });\n },\n [autoSync, cartSyncError, onCartSyncError, onChange]\n );\n\n const handleCheckoutData = useCallback(\n (data: Cart | NegotiableQuote | null) => {\n const isCartEmpty = !data || data.isEmpty;\n const isCartVirtual = !!data?.isVirtual;\n\n if (isCartEmpty || isCartVirtual) {\n setIsVirtual(isCartVirtual);\n setIsChecked(false);\n hasInitialCartData.current = false;\n return;\n }\n\n // If we've already set the initial state from cart data, don't override it.\n // This preserves any changes the user might have made.\n if (hasInitialCartData.current) {\n return;\n }\n\n const cart = data as Cart;\n const shippingAddress = cart.shippingAddresses?.[0];\n const hasBillingAddress = !!cart.billingAddress;\n\n let initialIsChecked: boolean;\n\n if (!shippingAddress) {\n const { defaults } = config.getConfig();\n initialIsChecked = defaults!.isBillToShipping!;\n } else {\n initialIsChecked = shippingAddress.sameAsBilling ?? !hasBillingAddress;\n }\n\n setIsChecked(initialIsChecked);\n hasInitialCartData.current = true;\n },\n []\n );\n\n useEffect(() => {\n if (!active || isChecked === undefined) return;\n notifyValues({ isBillToShipping: isChecked });\n }, [active, isChecked]);\n\n useEffect(() => {\n if (!active) return;\n\n const pastUpdate = getLatestCheckoutUpdate();\n\n if (pastUpdate) {\n // When component becomes active, restore key state so handleCheckoutData can work properly\n const userBillToShipping = getValue('isBillToShipping');\n if (userBillToShipping != null) {\n setIsChecked(userBillToShipping);\n }\n handleCheckoutData(pastUpdate);\n return;\n }\n\n const onCheckoutInit = events.on(\n 'checkout/initialized',\n handleCheckoutData,\n { eager: true }\n );\n\n return () => {\n onCheckoutInit?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n if (!active) return;\n\n const onCheckoutUpdated = events.on(\n 'checkout/updated',\n handleCheckoutData,\n {\n eager: false,\n }\n );\n\n return () => {\n onCheckoutUpdated?.off();\n };\n }, [active, handleCheckoutData]);\n\n return (\n <BillToShippingAddressComponent\n checked={isChecked}\n disabled={isDisabled}\n error={error}\n initialized={isChecked !== undefined}\n visible={active && !isVirtual}\n onChange={handleChange}\n onDismissError={handleDismissError}\n />\n );\n};\n"],"names":["BillToShippingAddressSkeleton","jsx","Skeleton","SkeletonRow","BillToShippingAddressComponent","className","checked","disabled","error","onChange","onDismissError","translations","useText","hasError","handleChange","event","checkbox","jsxs","Checkbox","classes","InLineAlert","BillToShippingAddress","WithConditionals","active","autoSync","onCartSyncError","setError","useState","isVirtual","setIsVirtual","isChecked","setIsChecked","hasInitialCartData","useRef","isDisabled","hasPendingUpdates","cartSyncError","handleDismissError","useCallback","isBillToShipping","hasShippingAddress","setBillingAddress","handleCheckoutData","data","isCartEmpty","isCartVirtual","cart","shippingAddress","_a","hasBillingAddress","initialIsChecked","defaults","config","useEffect","notifyValues","pastUpdate","getLatestCheckoutUpdate","userBillToShipping","getValue","onCheckoutInit","events","onCheckoutUpdated"],"mappings":"o+BAoBO,MAAMA,EAAmD,IAE5DC,EAACC,EAAA,CACC,UAAU,qCACV,cAAY,4BAEZ,SAACD,EAAAE,EAAA,CAAY,KAAK,QAAQ,QAAQ,KAAM,CAAA,CAAA,CAC1C,ECUEC,EAEF,CAAC,CACH,UAAAC,EACA,QAAAC,EACA,SAAAC,EACA,MAAAC,EAAQ,KACR,SAAAC,EAAW,IAAM,CAAC,EAClB,eAAAC,EAAiB,IAAM,CAAA,CACzB,IAAM,CACJ,MAAMC,EAAeC,EAAQ,CAC3B,MAAO,sCAAA,CACR,EAEKC,EAAWL,IAAU,KAErBM,EAAgBC,GAAiD,CACrE,MAAMC,EAAWD,EAAM,OACvBN,GAAA,MAAAA,EAAWO,EAAS,QACtB,EAGE,OAAAC,EAAC,MAAI,CAAA,UAAU,oCACb,SAAA,CAAAhB,EAACiB,EAAA,CACC,QAAAZ,EACA,UAAWa,EAAQ,CACjB,8CACAd,CAAA,CACD,EACD,cAAY,4BACZ,SAAAE,EACA,MAAOI,EAAa,MACpB,KAAK,8CACL,SAAUG,CAAA,CACZ,EAECD,GACCZ,EAAC,MAAA,CACC,UAAU,2CACV,cAAY,0CAEZ,SAAAA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B,GAC3CC,EAAoB,CAAC,CAACH,EAAK,eAE7B,IAAAI,EAEJ,GAAKH,EAIgBG,EAAAH,EAAgB,eAAiB,CAACE,MAJjC,CACpB,KAAM,CAAE,SAAAE,CAAA,EAAaC,EAAO,UAAU,EACtCF,EAAmBC,EAAU,gBAAA,CAK/BpB,EAAamB,CAAgB,EAC7BlB,EAAmB,QAAU,EAC/B,EACA,CAAA,CACF,EAEA,OAAAqB,EAAU,IAAM,CACV,CAAC9B,GAAUO,IAAc,QAChBwB,EAAA,CAAE,iBAAkBxB,EAAW,CAAA,EAC3C,CAACP,EAAQO,CAAS,CAAC,EAEtBuB,EAAU,IAAM,CACd,GAAI,CAAC9B,EAAQ,OAEb,MAAMgC,EAAaC,EAAwB,EAE3C,GAAID,EAAY,CAER,MAAAE,EAAqBC,EAAS,kBAAkB,EAClDD,GAAsB,MACxB1B,EAAa0B,CAAkB,EAEjCf,EAAmBa,CAAU,EAC7B,MAAA,CAGF,MAAMI,EAAiBC,EAAO,GAC5B,uBACAlB,EACA,CAAE,MAAO,EAAK,CAChB,EAEA,MAAO,IAAM,CACXiB,GAAA,MAAAA,EAAgB,KAClB,CAAA,EACC,CAACpC,EAAQmB,CAAkB,CAAC,EAE/BW,EAAU,IAAM,CACd,GAAI,CAAC9B,EAAQ,OAEb,MAAMsC,EAAoBD,EAAO,GAC/B,mBACAlB,EACA,CACE,MAAO,EAAA,CAEX,EAEA,MAAO,IAAM,CACXmB,GAAA,MAAAA,EAAmB,KACrB,CAAA,EACC,CAACtC,EAAQmB,CAAkB,CAAC,EAG7BzC,EAACG,EAAA,CACC,QAAS0B,EACT,SAAUI,EACV,MAAA1B,EACA,YAAasB,IAAc,OAC3B,QAASP,GAAU,CAACK,EACpB,SAAUd,EACV,eAAgBuB,CAAA,CAClB,CAEJ"}
|
|
1
|
+
{"version":3,"file":"BillToShippingAddress.js","sources":["/@dropins/storefront-checkout/src/components/BillToShippingAddress/BillToShippingAddressSkeleton.tsx","/@dropins/storefront-checkout/src/components/BillToShippingAddress/BillToShippingAddress.tsx","/@dropins/storefront-checkout/src/containers/BillToShippingAddress/BillToShippingAddress.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { Skeleton, SkeletonRow } from '@adobe-commerce/elsie/components';\nimport { FunctionComponent } from 'preact';\n\nexport const BillToShippingAddressSkeleton: FunctionComponent = () => {\n return (\n <Skeleton\n className=\"bill-to-shipping-address__skeleton\"\n data-testid=\"bill-to-shipping-skeleton\"\n >\n <SkeletonRow size=\"small\" variant=\"row\" />\n </Skeleton>\n );\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport '@/checkout/components/BillToShippingAddress/BillToShippingAddress.css';\nimport { BillToShippingAddressSkeleton } from '@/checkout/components/BillToShippingAddress/BillToShippingAddressSkeleton';\nimport { WithConditionals } from '@/checkout/components/ConditionalWrapper/ConditionalWrapper';\nimport { Checkbox, InLineAlert } from '@adobe-commerce/elsie/components';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { classes } from '@adobe-commerce/elsie/lib/classes';\nimport { FunctionComponent } from 'preact';\nimport { ChangeEvent, HTMLAttributes } from 'preact/compat';\n\nexport interface BillToShippingAddressProps\n extends Omit<\n HTMLAttributes<HTMLInputElement>,\n 'loading' | 'disabled' | 'onChange'\n > {\n disabled?: boolean;\n error?: string | null;\n onChange?: (checked: boolean) => void;\n onDismissError?: () => void;\n}\n\nconst BillToShippingAddressComponent: FunctionComponent<\n BillToShippingAddressProps\n> = ({\n className,\n checked,\n disabled,\n error = null,\n onChange = () => {},\n onDismissError = () => {},\n}) => {\n const translations = useText({\n title: 'Checkout.BillToShippingAddress.title',\n });\n\n const hasError = error !== null;\n\n const handleChange = (event: Event | ChangeEvent<HTMLInputElement>) => {\n const checkbox = event.target as HTMLInputElement;\n onChange?.(checkbox.checked);\n };\n\n return (\n <div className=\"checkout-bill-to-shipping-address\">\n <Checkbox\n checked={checked}\n className={classes([\n 'checkout-bill-to-shipping-address__checkbox',\n className,\n ])}\n data-testid=\"bill-to-shipping-checkbox\"\n disabled={disabled}\n label={translations.title}\n name=\"checkout-bill-to-shipping-address__checkbox\"\n onChange={handleChange}\n />\n\n {hasError && (\n <div\n className=\"checkout-bill-to-shipping-address__error\"\n data-testid=\"checkout-bill-to-shipping-address-alert\"\n >\n <InLineAlert\n heading={error}\n type=\"error\"\n variant=\"primary\"\n onDismiss={onDismissError}\n />\n </div>\n )}\n </div>\n );\n};\n\nexport const BillToShippingAddress = WithConditionals(\n BillToShippingAddressComponent,\n BillToShippingAddressSkeleton\n);\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { config, setBillingAddress } from '@/checkout/api';\nimport { BillToShippingAddress as BillToShippingAddressComponent } from '@/checkout/components/BillToShippingAddress';\nimport { Cart, NegotiableQuote } from '@/checkout/data/models';\nimport {\n getLatestCheckoutUpdate,\n getValue,\n hasPendingUpdates,\n hasShippingAddress,\n notifyValues,\n} from '@/checkout/lib';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { Container } from '@adobe-commerce/elsie/lib';\nimport { events } from '@adobe-commerce/event-bus';\nimport { HTMLAttributes } from 'preact/compat';\nimport { useCallback, useEffect, useRef, useState } from 'preact/hooks';\n\ninterface CartSyncError {\n error: Error;\n}\n\nexport interface BillToShippingAddressProps\n extends Omit<HTMLAttributes<HTMLDivElement>, 'onChange'> {\n active?: boolean;\n autoSync?: boolean;\n onCartSyncError?: (error: CartSyncError) => void;\n onChange?: (checked: boolean) => void;\n}\n\nexport const BillToShippingAddress: Container<BillToShippingAddressProps> = ({\n active = true,\n autoSync = true,\n onCartSyncError,\n onChange,\n}) => {\n const [error, setError] = useState<string | null>(null);\n const [isVirtual, setIsVirtual] = useState(false);\n const [isChecked, setIsChecked] = useState<boolean | undefined>();\n\n const hasInitialCartData = useRef(false);\n\n const isDisabled = hasPendingUpdates.value;\n\n const { cartSyncError } = useText({\n cartSyncError: 'Checkout.BillToShippingAddress.cartSyncError',\n });\n\n const handleDismissError = useCallback(() => {\n setError(null);\n }, []);\n\n const handleChange = useCallback(\n (isBillToShipping: boolean) => {\n setError(null);\n setIsChecked(isBillToShipping);\n\n onChange?.(isBillToShipping);\n\n if (!autoSync || !isBillToShipping || !hasShippingAddress()) {\n return;\n }\n\n setBillingAddress({ sameAsShipping: true }).catch((error: any) => {\n setIsChecked(false);\n onCartSyncError?.({ error });\n\n if (!onCartSyncError) {\n setError(cartSyncError);\n }\n });\n },\n [autoSync, cartSyncError, onCartSyncError, onChange]\n );\n\n const handleCheckoutData = useCallback(\n (data: Cart | NegotiableQuote | null) => {\n const isCartEmpty = !data || data.isEmpty;\n const isCartVirtual = !!data?.isVirtual;\n\n if (isCartEmpty || isCartVirtual) {\n setIsVirtual(isCartVirtual);\n setIsChecked(false);\n hasInitialCartData.current = false;\n return;\n }\n\n // If we've already set the initial state from cart data, don't override it.\n // This preserves any changes the user might have made.\n if (hasInitialCartData.current) {\n return;\n }\n\n const cart = data as Cart;\n const shippingAddress = cart.shippingAddresses?.[0];\n const hasBillingAddress = !!cart.billingAddress;\n\n let initialIsChecked: boolean;\n\n if (!shippingAddress) {\n const { defaults } = config.getConfig();\n initialIsChecked = defaults!.isBillToShipping!;\n } else {\n initialIsChecked = shippingAddress.sameAsBilling ?? !hasBillingAddress;\n }\n\n setIsChecked(initialIsChecked);\n hasInitialCartData.current = true;\n\n if (autoSync && initialIsChecked && shippingAddress && !hasBillingAddress) {\n setBillingAddress({ sameAsShipping: true }).catch(() => {});\n }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n []\n );\n\n useEffect(() => {\n if (!active || isChecked === undefined) return;\n notifyValues({ isBillToShipping: isChecked });\n }, [active, isChecked]);\n\n useEffect(() => {\n if (!active) return;\n\n const pastUpdate = getLatestCheckoutUpdate();\n\n if (pastUpdate) {\n // When component becomes active, restore key state so handleCheckoutData can work properly\n const userBillToShipping = getValue('isBillToShipping');\n if (userBillToShipping != null) {\n setIsChecked(userBillToShipping);\n }\n handleCheckoutData(pastUpdate);\n return;\n }\n\n const onCheckoutInit = events.on(\n 'checkout/initialized',\n handleCheckoutData,\n { eager: true }\n );\n\n return () => {\n onCheckoutInit?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n if (!active) return;\n\n const onCheckoutUpdated = events.on(\n 'checkout/updated',\n handleCheckoutData,\n {\n eager: false,\n }\n );\n\n return () => {\n onCheckoutUpdated?.off();\n };\n }, [active, handleCheckoutData]);\n\n return (\n <BillToShippingAddressComponent\n checked={isChecked}\n disabled={isDisabled}\n error={error}\n initialized={isChecked !== undefined}\n visible={active && !isVirtual}\n onChange={handleChange}\n onDismissError={handleDismissError}\n />\n );\n};\n"],"names":["BillToShippingAddressSkeleton","jsx","Skeleton","SkeletonRow","BillToShippingAddressComponent","className","checked","disabled","error","onChange","onDismissError","translations","useText","hasError","handleChange","event","checkbox","jsxs","Checkbox","classes","InLineAlert","BillToShippingAddress","WithConditionals","active","autoSync","onCartSyncError","setError","useState","isVirtual","setIsVirtual","isChecked","setIsChecked","hasInitialCartData","useRef","isDisabled","hasPendingUpdates","cartSyncError","handleDismissError","useCallback","isBillToShipping","hasShippingAddress","setBillingAddress","handleCheckoutData","data","isCartEmpty","isCartVirtual","cart","shippingAddress","_a","hasBillingAddress","initialIsChecked","defaults","config","useEffect","notifyValues","pastUpdate","getLatestCheckoutUpdate","userBillToShipping","getValue","onCheckoutInit","events","onCheckoutUpdated"],"mappings":"o+BAoBO,MAAMA,EAAmD,IAE5DC,EAACC,EAAA,CACC,UAAU,qCACV,cAAY,4BAEZ,SAACD,EAAAE,EAAA,CAAY,KAAK,QAAQ,QAAQ,KAAM,CAAA,CAAA,CAC1C,ECUEC,EAEF,CAAC,CACH,UAAAC,EACA,QAAAC,EACA,SAAAC,EACA,MAAAC,EAAQ,KACR,SAAAC,EAAW,IAAM,CAAC,EAClB,eAAAC,EAAiB,IAAM,CAAA,CACzB,IAAM,CACJ,MAAMC,EAAeC,EAAQ,CAC3B,MAAO,sCAAA,CACR,EAEKC,EAAWL,IAAU,KAErBM,EAAgBC,GAAiD,CACrE,MAAMC,EAAWD,EAAM,OACvBN,GAAA,MAAAA,EAAWO,EAAS,QACtB,EAGE,OAAAC,EAAC,MAAI,CAAA,UAAU,oCACb,SAAA,CAAAhB,EAACiB,EAAA,CACC,QAAAZ,EACA,UAAWa,EAAQ,CACjB,8CACAd,CAAA,CACD,EACD,cAAY,4BACZ,SAAAE,EACA,MAAOI,EAAa,MACpB,KAAK,8CACL,SAAUG,CAAA,CACZ,EAECD,GACCZ,EAAC,MAAA,CACC,UAAU,2CACV,cAAY,0CAEZ,SAAAA,EAACmB,EAAA,CACC,QAASZ,EACT,KAAK,QACL,QAAQ,UACR,UAAWE,CAAA,CAAA,CACb,CAAA,CACF,EA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{h as
|
|
3
|
+
import{h as se,s as ie}from"../chunks/fetch-graphql.js";import{classes as O,VComponent as me,deepmerge as de,Slot as G}from"@dropins/tools/lib.js";import{events as q}from"@dropins/tools/event-bus.js";import{v as le}from"../chunks/validation.js";import{s as Q}from"../chunks/setPaymentMethod.js";import{jsxs as D,jsx as c}from"@dropins/tools/preact-jsx-runtime.js";import{useState as _,useMemo as L,useCallback as p,useEffect as R}from"@dropins/tools/preact-hooks.js";import"../chunks/TermsAndConditions.js";import{Skeleton as ue,SkeletonRow as N,IllustratedMessage as pe,Icon as X,InLineAlert as he,ToggleButton as fe,RadioButton as ye}from"@dropins/tools/components.js";/* empty css */import*as T from"@dropins/tools/preact-compat.js";import{useRef as ke,useEffect as ge}from"@dropins/tools/preact-compat.js";/* empty css *//* empty css *//* empty css *//* empty css */import{P as ve}from"../chunks/PurchaseOrder.js";import{P as Ce}from"../chunks/PaymentOnAccount2.js";import{r as Se}from"../chunks/render.js";import{i as Me}from"../chunks/events.js";import{h as be,a as Ee}from"../chunks/events2.js";import{g as V,n as Pe}from"../chunks/values.js";import{W as we}from"../chunks/ConditionalWrapper.js";import{s as _e}from"../chunks/dom.js";import{useText as Y}from"@dropins/tools/i18n.js";import"@dropins/tools/signals.js";import"@dropins/tools/fetch-graphql.js";import"../fragments.js";import"../chunks/guards.js";import"../chunks/synchronizeCheckout.js";import"../chunks/transform-shipping-methods.js";import"../chunks/classifiers.js";import"../chunks/getCompanyCredit.js";const Ne=e=>T.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e},T.createElement("path",{vectorEffect:"non-scaling-stroke",d:"M17.93 14.8V18.75H5.97C4.75 18.75 3.75 17.97 3.75 17V6.5M3.75 6.5C3.75 5.53 4.74 4.75 5.97 4.75H15.94V8.25H5.97C4.75 8.25 3.75 7.47 3.75 6.5Z",stroke:"currentColor",strokeWidth:1,strokeLinecap:"round",strokeLinejoin:"round"}),T.createElement("path",{vectorEffect:"non-scaling-stroke",d:"M19.35 11.64H14.04V14.81H19.35V11.64Z",stroke:"currentColor",strokeWidth:1,strokeLinecap:"round",strokeLinejoin:"round"}),T.createElement("path",{vectorEffect:"non-scaling-stroke",d:"M17.9304 11.64V8.25H15.1504",stroke:"currentColor",strokeWidth:1,strokeLinecap:"round",strokeLinejoin:"round"})),Te=()=>D(ue,{"data-testid":"payment-methods-skeleton",children:[c(N,{size:"medium",variant:"heading"}),c(N,{size:"medium",variant:"empty"}),c(N,{fullWidth:!0,size:"xlarge"}),c(N,{fullWidth:!0,size:"xlarge"})]}),Ie=({UIComponentType:e="ToggleButton",busy:r,code:a,icon:i,onSelectionChange:o,selected:s,title:m})=>{const u={busy:r,className:"checkout-payment-methods__method",label:m,name:"payment-method",onChange:()=>o({code:a,title:m}),value:a};return e==="ToggleButton"?c(fe,{...u,icon:i?c(X,{source:i}):void 0,selected:s}):c(ye,{...u,checked:s,icon:i??void 0})},He=({className:e,error:r=null,busy:a=!1,onDismissError:i,onSelectionChange:o=()=>{},options:s,paymentMethodContent:m,selection:u,title:f,UIComponentType:S})=>{const v=Y({EmptyState:"Checkout.PaymentMethods.emptyState"}),d=r!==null,C=ke(null);return ge(()=>{d&&C.current&&_e(C.current)},[d]),D("div",{className:O(["checkout-payment-methods",e]),"data-testid":"checkout-payment-methods",children:[f&&c(me,{className:"checkout-payment-methods__title",node:f}),!a&&s.length===0&&c(pe,{"data-testid":"checkout-payment-methods-empty",icon:c(X,{source:Ne}),message:c("p",{children:v.EmptyState})}),D("div",{className:O(["checkout-payment-methods__wrapper",["checkout-payment-methods__wrapper--busy",a]]),"data-testid":"checkout-payment-methods-wrapper",children:[c("div",{className:O(["checkout-payment-methods__methods",["checkout-payment-methods--full-width",s.length%2!==0]]),children:s==null?void 0:s.map(y=>c(Ie,{UIComponentType:S,busy:a,code:y.code,icon:y.icon,selected:(u==null?void 0:u.code)===y.code,title:y.displayLabel??!0?y.title:"",onSelectionChange:o},y.code))}),m&&c("div",{className:"checkout-payment-methods__content",children:m})]}),d&&c("div",{ref:C,className:"checkout-payment-methods__error","data-testid":"checkout-payment-methods-alert",children:c(he,{heading:r,type:"error",variant:"primary",onDismiss:i})})]})},Oe=we(He,Te),Le=(e,r)=>{let a;return function(...i){clearTimeout(a),a=setTimeout(()=>e.apply(this,i),r)}};var Re=(e=>(e.PaymentOnAccount="companycredit",e.PurchaseOrder="purchaseorder",e))(Re||{});const J={companycredit:{Container:Ce,autoSync:!0,formName:"payment-on-account",validateRefNumber:!1},purchaseorder:{Container:ve,autoSync:!1,formName:"purchase-order",validateRefNumber:!0}},I=new Map,Ve=(e,r)=>{const a=`${e}-${r}`;if(!I.has(a)){const i=Le(async o=>{if(!r||le(o))try{await Q({code:e,purchase_order_number:o})}catch(s){console.error(`Failed to set payment method for ${e}:`,s)}},1e3);I.set(a,i)}return I.get(a)},w={},kt=()=>{Object.keys(w).forEach(e=>{delete w[e]}),I.clear()},K=e=>{if(!(e in J))throw new Error(`Invalid handler code: ${e}`);if(w[e])return w[e];const r=J[e],{autoSync:a,Container:i,formName:o,validateRefNumber:s}=r,m={enabled:!0,autoSync:a,render:u=>{var v;const f=String(((v=u.additionalData)==null?void 0:v.purchase_order_number)??""),S=document.createElement("div");Se.render(i,{name:o,initialReferenceNumber:f,onReferenceNumberChange:Ve(e,s)})(S),u.replaceHTML(S)}};return w[e]=m,m},Ae={companycredit:K("companycredit"),purchaseorder:K("purchaseorder")};function A(e,r){return e?r.some(a=>a.code===e.code):!1}function De(e,r){return!e||!r?!1:e.code===r.code}function We(e){return e?!!e.code&&!!e.title:!1}const gt=({UIComponentType:e="ToggleButton",active:r=!0,autoSync:a=!0,displayTitle:i=!0,slots:o,onCartSyncError:s,onSelectionChange:m})=>{const[u,f]=_(null),[S,v]=_(!1),[d,C]=_(null),[y,W]=_([]),ee=se.value,{cartSyncError:x,defaultTitle:z}=Y({cartSyncError:"Checkout.PaymentMethods.cartSyncError",defaultTitle:"Checkout.PaymentMethods.title"}),k=L(()=>{const t=(o==null?void 0:o.Methods)??{};return de(Ae,t)},[o==null?void 0:o.Methods]),U=p(t=>{var n;return(n=k[t.code])==null?void 0:n.render},[k]),B=p(t=>{const n=k[t.code];return n?n.autoSync!==!1:a},[a,k]),$=p(t=>{var l;return((l=k[t.code])==null?void 0:l.enabled)!==!1},[k]),te=p(t=>t.map(n=>{const l=k[n.code];return l?{...n,icon:l.icon}:n}),[k]),j=p(t=>{C(n=>n&&{...n,additionalData:t})},[]),ne=p(()=>{f(null)},[]),h=p(t=>{f(null),C(t)},[]),E=p(async(t,n)=>{(Me()||be())&&B(t)&&Q({code:t.code}).catch(g=>{h(n??null),f(s?null:x),s==null||s({method:t,error:g})})},[x,B,s,h]),re=p(async t=>{const n=V("selectedPaymentMethod");h(t),m==null||m(t),await E(t,n)},[m,h,E]),P=p(t=>{if(!t||t.isEmpty){h(null),W([]);return}const g=(t.availablePaymentMethods??[]).filter($);if(W(g),g.length===0){h(null);return}const M=t.selectedPaymentMethod??null,F=We(M),b=V("selectedPaymentMethod"),H=A(b,g),ce=De(b,M);if(b&&H&&!ce){E(b,M);return}if((!b||!H)&&F&&A(M,g)){h(M);return}if((!b||!H)&&(!F||!A(M,g))){const Z=g[0];h(Z),E(Z)}},[$,h,E]);R(()=>{if(!r)return;const t=Ee();if(t){v(!0);const l=V("selectedPaymentMethod");l&&C(l),P(t);return}const n=q.on("checkout/initialized",l=>{v(!0),P(l)},{eager:!0});return()=>{n==null||n.off()}},[r,P]),R(()=>{if(!r)return;const t=q.on("checkout/updated",P,{eager:!1});return()=>{t==null||t.off()}},[r,P]),R(()=>{Pe({selectedPaymentMethod:d})},[d]);const oe=L(()=>{if(i)return c(G,{name:"checkout-payment-methods-title",slot:o==null?void 0:o.Title,children:c("h2",{children:z})})},[i,o==null?void 0:o.Title,z]),ae=L(()=>{if(!d)return;const t=U(d);if(t)return c(G,{context:{additionalData:d.additionalData,cartId:ie.cartId??"",replaceHTML(n){this.replaceWith(n)},setAdditionalData:j},name:"PaymentMethodContent",slot:t},d.code)},[U,d,j]);return c(Oe,{UIComponentType:e,busy:ee,error:u,initialized:S,options:te(y),paymentMethodContent:ae,selection:d,title:oe,visible:r,onDismissError:ne,onSelectionChange:re})};export{Re as HandlerCode,gt as PaymentMethods,K as createHandler,gt as default,Ae as defaultHandlers,Ve as handleRefNumberChange,kt as resetHandlersCache};
|
|
4
4
|
//# sourceMappingURL=PaymentMethods.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PaymentMethods.js","sources":["../../node_modules/@adobe-commerce/elsie/src/icons/Wallet.svg","/@dropins/storefront-checkout/src/components/PaymentMethods/PaymentMethodsSkeleton.tsx","/@dropins/storefront-checkout/src/components/PaymentMethods/PaymentMethods.tsx","../../node_modules/@adobe-commerce/elsie/src/lib/debounce.ts","/@dropins/storefront-checkout/src/containers/PaymentMethods/handlers.tsx","/@dropins/storefront-checkout/src/containers/PaymentMethods/PaymentMethods.tsx"],"sourcesContent":["import * as React from \"react\";\nconst SvgWallet = (props) => /* @__PURE__ */ React.createElement(\"svg\", { width: 24, height: 24, viewBox: \"0 0 24 24\", fill: \"none\", xmlns: \"http://www.w3.org/2000/svg\", ...props }, /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M17.93 14.8V18.75H5.97C4.75 18.75 3.75 17.97 3.75 17V6.5M3.75 6.5C3.75 5.53 4.74 4.75 5.97 4.75H15.94V8.25H5.97C4.75 8.25 3.75 7.47 3.75 6.5Z\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M19.35 11.64H14.04V14.81H19.35V11.64Z\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M17.9304 11.64V8.25H15.1504\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }));\nexport default SvgWallet;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { Skeleton, SkeletonRow } from '@adobe-commerce/elsie/components';\nimport { FunctionComponent } from 'preact';\n\nexport const PaymentMethodsSkeleton: FunctionComponent = () => {\n return (\n <Skeleton data-testid=\"payment-methods-skeleton\">\n <SkeletonRow size=\"medium\" variant=\"heading\" />\n <SkeletonRow size=\"medium\" variant=\"empty\" />\n <SkeletonRow fullWidth={true} size=\"xlarge\" />\n <SkeletonRow fullWidth={true} size=\"xlarge\" />\n </Skeleton>\n );\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { WithConditionals } from '@/checkout/components/ConditionalWrapper/ConditionalWrapper';\nimport '@/checkout/components/PaymentMethods/PaymentMethods.css';\nimport { PaymentMethodsSkeleton } from '@/checkout/components/PaymentMethods/PaymentMethodsSkeleton';\nimport { PaymentMethodConfig } from '@/checkout/containers';\nimport { PaymentMethod } from '@/checkout/data/models/payment-method';\nimport { scrollToElement } from '@/checkout/lib';\nimport { UIComponentType } from '@/checkout/types';\nimport {\n Icon,\n IllustratedMessage,\n InLineAlert,\n RadioButton,\n ToggleButton,\n} from '@adobe-commerce/elsie/components';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { Wallet } from '@adobe-commerce/elsie/icons';\nimport { classes, VComponent } from '@adobe-commerce/elsie/lib';\nimport { FunctionComponent, VNode } from 'preact';\nimport { HTMLAttributes, useEffect, useRef } from 'preact/compat';\n\ninterface ExtendedPaymentMethod extends PaymentMethodConfig, PaymentMethod {}\n\nexport interface PaymentMethodsProps\n extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {\n error?: string | null;\n busy?: boolean;\n onDismissError?: () => void;\n onSelectionChange?: (value: PaymentMethod) => void;\n options?: ExtendedPaymentMethod[];\n paymentMethodContent?: VNode;\n selection: PaymentMethod | null;\n title?: VNode;\n UIComponentType?: UIComponentType;\n}\n\ninterface PaymentOptionProps {\n UIComponentType?: UIComponentType;\n busy?: boolean;\n code: string;\n icon?: string;\n onSelectionChange: (value: PaymentMethod) => void;\n selected: boolean;\n title: string;\n}\n\nconst PaymentOption: FunctionComponent<PaymentOptionProps> = ({\n UIComponentType = 'ToggleButton',\n busy,\n code,\n icon,\n onSelectionChange,\n selected,\n title,\n}) => {\n const commonProps = {\n busy,\n className: 'checkout-payment-methods__method',\n label: title,\n name: 'payment-method',\n onChange: () => onSelectionChange({ code, title }),\n value: code,\n };\n\n return UIComponentType === 'ToggleButton' ? (\n <ToggleButton\n {...commonProps}\n // @ts-ignore\n icon={icon ? <Icon source={icon} /> : undefined}\n selected={selected}\n />\n ) : (\n <RadioButton {...commonProps} checked={selected} icon={icon ?? undefined} />\n );\n};\n\nconst PaymentMethodsComponent: FunctionComponent<PaymentMethodsProps> = ({\n className,\n error = null,\n busy = false,\n onDismissError,\n onSelectionChange = () => {},\n options,\n paymentMethodContent,\n selection,\n title,\n UIComponentType,\n}) => {\n const translations = useText({\n EmptyState: 'Checkout.PaymentMethods.emptyState',\n });\n\n const hasError = error !== null;\n const errorRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n if (hasError && errorRef.current) {\n scrollToElement(errorRef.current);\n }\n }, [hasError]);\n\n return (\n <div\n className={classes(['checkout-payment-methods', className])}\n data-testid=\"checkout-payment-methods\"\n >\n {title && (\n <VComponent className=\"checkout-payment-methods__title\" node={title} />\n )}\n\n {!busy && options!.length === 0 && (\n <IllustratedMessage\n data-testid=\"checkout-payment-methods-empty\"\n icon={<Icon source={Wallet} />}\n message={<p>{translations.EmptyState}</p>}\n />\n )}\n\n <div\n className={classes([\n 'checkout-payment-methods__wrapper',\n ['checkout-payment-methods__wrapper--busy', busy],\n ])}\n data-testid=\"checkout-payment-methods-wrapper\"\n >\n <div\n className={classes([\n 'checkout-payment-methods__methods',\n ['checkout-payment-methods--full-width', options!.length % 2 !== 0],\n ])}\n >\n {options?.map((method) => (\n <PaymentOption\n key={method.code}\n UIComponentType={UIComponentType}\n busy={busy}\n code={method.code}\n icon={method.icon}\n selected={selection?.code === method.code}\n title={method.displayLabel ?? true ? method.title : ''}\n onSelectionChange={onSelectionChange}\n />\n ))}\n </div>\n\n {paymentMethodContent && (\n <div className=\"checkout-payment-methods__content\">\n {paymentMethodContent}\n </div>\n )}\n </div>\n\n {hasError && (\n <div\n ref={errorRef}\n className=\"checkout-payment-methods__error\"\n data-testid=\"checkout-payment-methods-alert\"\n >\n <InLineAlert\n heading={error}\n type=\"error\"\n variant=\"primary\"\n onDismiss={onDismissError}\n />\n </div>\n )}\n </div>\n );\n};\n\nexport const PaymentMethods = WithConditionals(\n PaymentMethodsComponent,\n PaymentMethodsSkeleton\n);\n","/********************************************************************\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nexport const debounce = (fn: Function, ms: number) => {\n let timeoutId: ReturnType<typeof setTimeout>;\n return function (this: any, ...args: any[]) {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => fn.apply(this, args), ms);\n };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { setPaymentMethod } from '@/checkout/api';\nimport {\n PaymentMethodConfig,\n PaymentOnAccount,\n PurchaseOrder,\n} from '@/checkout/containers';\nimport { validateNotEmpty } from '@/checkout/lib/validation';\nimport { render as Checkout } from '@/checkout/render/render';\nimport { Container } from '@adobe-commerce/elsie/lib';\nimport { debounce } from '@adobe-commerce/elsie/lib/debounce';\n\ninterface HandlerConfig {\n Container: Container<any>;\n autoSync: boolean;\n formName?: string;\n validateRefNumber: boolean;\n}\n\nexport enum HandlerCode {\n PaymentOnAccount = 'companycredit',\n PurchaseOrder = 'purchaseorder',\n}\n\nconst HANDLERS_CONFIG: Record<HandlerCode, HandlerConfig> = {\n [HandlerCode.PaymentOnAccount]: {\n Container: PaymentOnAccount,\n autoSync: true,\n formName: 'payment-on-account',\n validateRefNumber: false,\n },\n [HandlerCode.PurchaseOrder]: {\n Container: PurchaseOrder,\n autoSync: false,\n formName: 'purchase-order',\n validateRefNumber: true,\n },\n} as const;\n\n// Cache for debounced handlers to prevent memory leaks\nconst debouncedHandlers = new Map<string, ReturnType<typeof debounce>>();\n\nexport const handleRefNumberChange = (code: string, isRequired: boolean) => {\n const key = `${code}-${isRequired}`;\n\n if (!debouncedHandlers.has(key)) {\n const debouncedFn = debounce(async (refNumber: string) => {\n if (!isRequired || validateNotEmpty(refNumber)) {\n try {\n await setPaymentMethod({\n code,\n purchase_order_number: refNumber,\n });\n } catch (error) {\n console.error(`Failed to set payment method for ${code}:`, error);\n }\n }\n }, 1000);\n\n debouncedHandlers.set(key, debouncedFn);\n }\n\n return debouncedHandlers.get(key)!;\n};\n\nconst handlerCache: Partial<Record<HandlerCode, PaymentMethodConfig>> = {};\n\nexport const resetHandlersCache = () => {\n Object.keys(handlerCache).forEach((key) => {\n delete handlerCache[key as HandlerCode];\n });\n\n debouncedHandlers.clear();\n};\n\nexport const createHandler = (code: HandlerCode): PaymentMethodConfig => {\n if (!(code in HANDLERS_CONFIG)) {\n throw new Error(`Invalid handler code: ${code}`);\n }\n\n if (handlerCache[code]) {\n return handlerCache[code] as PaymentMethodConfig;\n }\n\n const config = HANDLERS_CONFIG[code];\n\n const { autoSync, Container, formName, validateRefNumber } = config;\n\n const handler: PaymentMethodConfig = {\n enabled: true,\n autoSync,\n render: (ctx) => {\n const initialReferenceNumber = String(\n ctx.additionalData?.purchase_order_number ?? ''\n );\n\n const $wrapper = document.createElement('div');\n\n Checkout.render(Container, {\n name: formName,\n initialReferenceNumber,\n onReferenceNumberChange: handleRefNumberChange(code, validateRefNumber),\n })($wrapper);\n\n ctx.replaceHTML($wrapper);\n },\n };\n\n handlerCache[code] = handler;\n\n return handler;\n};\n\nexport const defaultHandlers = {\n [HandlerCode.PaymentOnAccount]: createHandler(HandlerCode.PaymentOnAccount),\n [HandlerCode.PurchaseOrder]: createHandler(HandlerCode.PurchaseOrder),\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { setPaymentMethod } from '@/checkout/api';\nimport { PaymentMethods as PaymentMethodsComponent } from '@/checkout/components/PaymentMethods/PaymentMethods';\nimport { Cart } from '@/checkout/data/models/cart';\nimport {\n AdditionalData,\n PaymentMethod\n} from '@/checkout/data/models/payment-method';\nimport { NegotiableQuote } from '@/checkout/data/models/quote';\nimport {\n getLatestCheckoutUpdate,\n getValue,\n hasPendingUpdates,\n hasShippingAddress,\n isVirtualCart,\n notifyValues,\n state\n} from '@/checkout/lib';\nimport { TitleProps, UIComponentType } from '@/checkout/types';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport {\n Container,\n deepmerge,\n Slot,\n SlotProps\n} from '@adobe-commerce/elsie/lib';\nimport { events } from '@adobe-commerce/event-bus';\nimport { HTMLAttributes } from 'preact/compat';\nimport { useCallback, useEffect, useMemo, useState } from 'preact/hooks';\nimport { defaultHandlers } from './handlers';\n\ninterface RenderContext {\n additionalData?: AdditionalData;\n cartId: string;\n replaceHTML: (domElement: HTMLElement) => void;\n setAdditionalData: (data: AdditionalData) => void;\n}\n\nexport interface PaymentMethodConfig {\n autoSync?: boolean;\n displayLabel?: boolean;\n enabled?: boolean;\n icon?: string;\n render?: SlotProps<RenderContext>;\n}\n\nexport interface PaymentMethodHandlers {\n [code: string]: PaymentMethodConfig;\n}\n\ninterface CartSyncError {\n method: PaymentMethod;\n error: Error;\n}\n\ntype EnabledOption = PaymentMethod & PaymentMethodConfig;\n\nexport interface PaymentMethodsProps\n extends HTMLAttributes<HTMLDivElement>,\n TitleProps {\n slots?: {\n Methods?: PaymentMethodHandlers;\n } & TitleProps['slots'];\n UIComponentType?: UIComponentType;\n active?: boolean;\n autoSync?: boolean;\n onCartSyncError?: (error: CartSyncError) => void;\n onSelectionChange?: (method: PaymentMethod) => void;\n}\n\nfunction isAvailable(\n selection: PaymentMethod | null,\n options: PaymentMethod[]\n) {\n if (!selection) return false;\n return options.some((option) => option.code === selection.code);\n}\n\nfunction isEqual(a: PaymentMethod | null, b: PaymentMethod | null) {\n if (!a || !b) return false;\n return a.code === b.code;\n}\n\nfunction isValid(method: PaymentMethod | null) {\n if (!method) return false;\n return !!method.code && !!method.title;\n}\n\nexport const PaymentMethods: Container<PaymentMethodsProps> = ({\n UIComponentType = 'ToggleButton',\n active = true,\n autoSync = true,\n displayTitle = true,\n slots,\n onCartSyncError,\n onSelectionChange,\n}) => {\n const [error, setError] = useState<string | null>(null);\n const [isInitialized, setIsInitialized] = useState(false);\n const [selection, setSelection] = useState<PaymentMethod | null>(null);\n const [options, setOptions] = useState<PaymentMethod[]>([]);\n const isBusy = hasPendingUpdates.value;\n\n const { cartSyncError, defaultTitle } = useText({\n cartSyncError: 'Checkout.PaymentMethods.cartSyncError',\n defaultTitle: 'Checkout.PaymentMethods.title',\n });\n\n const availableHandlers = useMemo(() => {\n const customHandlers = slots?.Methods ?? {};\n return deepmerge(defaultHandlers, customHandlers);\n }, [slots?.Methods]);\n\n const enabledOptions: EnabledOption[] = useMemo(\n () =>\n options\n .filter((method) => availableHandlers?.[method.code]?.enabled !== false)\n .map((method) => {\n const slotMethod = availableHandlers?.[method.code] || {};\n\n return {\n ...method,\n ...slotMethod,\n };\n }),\n [options, availableHandlers]\n );\n\n const setAdditionalData = useCallback((additionalData: AdditionalData) => {\n setSelection((prev) => {\n if (!prev) return prev;\n return { ...prev, additionalData };\n });\n\n const currentSelection = getValue('selectedPaymentMethod');\n\n if (!currentSelection) return;\n\n notifyValues({\n selectedPaymentMethod: {\n ...currentSelection,\n additionalData,\n },\n });\n }, []);\n\n const handleDismissError = useCallback(() => {\n setError(null);\n }, []);\n\n const setUserSelection = useCallback((selection: PaymentMethod | null) => {\n setError(null);\n setSelection(selection);\n notifyValues({ selectedPaymentMethod: selection });\n }, []);\n\n const setUserSelectionOnCart = useCallback(\n async (selection: PaymentMethod, fallback?: PaymentMethod | null) => {\n const canSetUserSelectionOnCart = isVirtualCart() || hasShippingAddress();\n if (!canSetUserSelectionOnCart) return;\n\n const methodConfig = availableHandlers?.[selection.code];\n const shouldAutoSync = methodConfig?.autoSync ?? autoSync;\n\n if (!shouldAutoSync) return;\n\n setPaymentMethod({ code: selection.code }).catch((error) => {\n setUserSelection(fallback ?? null);\n onCartSyncError?.({ method: selection, error });\n\n if (!onCartSyncError) {\n setError(cartSyncError);\n }\n });\n },\n [\n availableHandlers,\n autoSync,\n setUserSelection,\n onCartSyncError,\n cartSyncError,\n ]\n );\n\n const handleSelectionChange = useCallback(\n async (selection: PaymentMethod) => {\n const prevSelection = getValue('selectedPaymentMethod');\n\n setUserSelection(selection);\n onSelectionChange?.(selection);\n\n await setUserSelectionOnCart(selection, prevSelection);\n },\n [onSelectionChange, setUserSelection, setUserSelectionOnCart]\n );\n\n const handleCheckoutData = useCallback(\n (data: Cart | NegotiableQuote | null) => {\n const isEmptyCart = !data || data.isEmpty;\n\n if (isEmptyCart) {\n setUserSelection(null);\n setOptions([]);\n return;\n }\n\n const availableOptions = data.availablePaymentMethods ?? [];\n setOptions(availableOptions);\n\n if (availableOptions.length === 0) {\n setUserSelection(null);\n return;\n }\n\n const cartSelection = data.selectedPaymentMethod ?? null;\n const hasCartSelection = isValid(cartSelection);\n const userSelection = getValue('selectedPaymentMethod');\n const isUserSelectionAvailable = isAvailable(userSelection, availableOptions);\n const haveSameSelection = isEqual(userSelection, cartSelection);\n\n // User has valid selection that differs from cart\n if (userSelection && isUserSelectionAvailable && !haveSameSelection) {\n setUserSelectionOnCart(userSelection, cartSelection);\n return;\n }\n\n // User has invalid selection but cart has valid selection\n if (\n (!userSelection || !isUserSelectionAvailable) &&\n hasCartSelection &&\n isAvailable(cartSelection, availableOptions)\n ) {\n setUserSelection(cartSelection);\n return;\n }\n\n // Neither user nor cart has valid selection (or both selections are unavailable)\n if (\n (!userSelection || !isUserSelectionAvailable) &&\n (!hasCartSelection ||\n !isAvailable(cartSelection, availableOptions))\n ) {\n const newSelection = availableOptions[0];\n setUserSelection(newSelection);\n setUserSelectionOnCart(newSelection);\n }\n },\n [setUserSelection, setUserSelectionOnCart]\n );\n\n useEffect(() => {\n if (!active) return;\n\n const pastUpdate = getLatestCheckoutUpdate();\n\n if (pastUpdate) {\n setIsInitialized(true);\n // When component becomes active, restore key state so handleCheckoutData can work properly\n const userSelection = getValue('selectedPaymentMethod');\n if (userSelection) {\n setSelection(userSelection);\n }\n handleCheckoutData(pastUpdate);\n return;\n }\n\n const onCheckoutInit = events.on(\n 'checkout/initialized',\n (data: Cart | NegotiableQuote | null) => {\n setIsInitialized(true);\n handleCheckoutData(data);\n },\n { eager: true }\n );\n\n return () => {\n onCheckoutInit?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n if (!active) return;\n\n const onCheckoutUpdated = events.on(\n 'checkout/updated',\n handleCheckoutData,\n { eager: false }\n );\n\n return () => {\n onCheckoutUpdated?.off();\n };\n }, [active, handleCheckoutData]);\n\n // When the current selection is disabled, this effect automatically selects the first available method\n useEffect(() => {\n if (enabledOptions.length === 0) return;\n\n const isEnabled = isAvailable(selection, enabledOptions);\n if (isEnabled) return;\n\n const firstAvailableOption = enabledOptions[0];\n const { code, title, additionalData } = firstAvailableOption;\n const selectedMethod = { code, title, additionalData };\n setUserSelection(selectedMethod);\n setUserSelectionOnCart(selectedMethod);\n }, [enabledOptions, selection, setUserSelection, setUserSelectionOnCart]);\n\n const titleContent = useMemo(() => {\n if (!displayTitle) return undefined;\n\n return (\n <Slot name=\"checkout-payment-methods-title\" slot={slots?.Title}>\n <h2>{defaultTitle}</h2>\n </Slot>\n );\n }, [displayTitle, slots?.Title, defaultTitle]);\n\n const paymentMethodContent = useMemo(() => {\n const slot = enabledOptions.find((method) => isEqual(method, selection))?.render;\n if (!slot) return undefined;\n\n return (\n <Slot\n key={selection!.code}\n context={{\n additionalData: selection!.additionalData,\n cartId: state.cartId ?? '',\n replaceHTML(domElement: HTMLElement) {\n this.replaceWith(domElement);\n },\n setAdditionalData,\n }}\n name=\"PaymentMethodContent\"\n slot={slot}\n />\n );\n\n }, [enabledOptions, selection, setAdditionalData])\n\n return (\n <PaymentMethodsComponent\n UIComponentType={UIComponentType}\n busy={isBusy}\n error={error}\n initialized={isInitialized}\n options={enabledOptions}\n paymentMethodContent={paymentMethodContent}\n selection={selection}\n title={titleContent}\n visible={active}\n onDismissError={handleDismissError}\n onSelectionChange={handleSelectionChange}\n />\n );\n};\n"],"names":["SvgWallet","props","React","PaymentMethodsSkeleton","jsxs","Skeleton","jsx","SkeletonRow","PaymentOption","UIComponentType","busy","code","icon","onSelectionChange","selected","title","commonProps","ToggleButton","Icon","RadioButton","PaymentMethodsComponent","className","error","onDismissError","options","paymentMethodContent","selection","translations","useText","hasError","errorRef","useRef","useEffect","scrollToElement","classes","VComponent","IllustratedMessage","Wallet","method","InLineAlert","PaymentMethods","WithConditionals","debounce","fn","ms","timeoutId","args","HandlerCode","HANDLERS_CONFIG","PaymentOnAccount","PurchaseOrder","debouncedHandlers","handleRefNumberChange","isRequired","key","debouncedFn","refNumber","validateNotEmpty","setPaymentMethod","handlerCache","resetHandlersCache","createHandler","config","autoSync","Container","formName","validateRefNumber","handler","ctx","initialReferenceNumber","_a","$wrapper","Checkout","defaultHandlers","isAvailable","option","isEqual","a","b","isValid","active","displayTitle","slots","onCartSyncError","setError","useState","isInitialized","setIsInitialized","setSelection","setOptions","isBusy","hasPendingUpdates","cartSyncError","defaultTitle","availableHandlers","useMemo","customHandlers","deepmerge","enabledOptions","slotMethod","setAdditionalData","useCallback","additionalData","prev","currentSelection","getValue","notifyValues","handleDismissError","setUserSelection","setUserSelectionOnCart","fallback","isVirtualCart","hasShippingAddress","methodConfig","handleSelectionChange","prevSelection","handleCheckoutData","data","availableOptions","cartSelection","hasCartSelection","userSelection","isUserSelectionAvailable","haveSameSelection","newSelection","pastUpdate","getLatestCheckoutUpdate","onCheckoutInit","events","onCheckoutUpdated","firstAvailableOption","selectedMethod","titleContent","Slot","slot","state","domElement"],"mappings":"wpDACA,MAAMA,GAAaC,GAA0BC,EAAM,cAAc,MAAO,CAAE,MAAO,GAAI,OAAQ,GAAI,QAAS,YAAa,KAAM,OAAQ,MAAO,6BAA8B,GAAGD,CAAO,EAAkBC,EAAM,cAAc,OAAQ,CAAE,aAAc,qBAAsB,EAAG,gJAA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AC7B,GAACd,EAGH,OAAA3E,EAAC+H,EAAK,CAAA,KAAK,iCAAiC,KAAMnD,GAAA,YAAAA,EAAO,MACvD,SAAA5E,EAAC,KAAI,CAAA,SAAAuF,CAAa,CAAA,EACpB,GAED,CAACZ,EAAcC,GAAA,YAAAA,EAAO,MAAOW,CAAY,CAAC,EAEvCpE,GAAuBsE,EAAQ,IAAM,OACnC,MAAAuC,GAAOhE,EAAA4B,EAAe,KAAM5D,GAAWsC,EAAQtC,EAAQZ,CAAS,CAAC,IAA1D,YAAA4C,EAA6D,OACtE,GAACgE,EAGH,OAAAhI,EAAC+H,EAAA,CAEC,QAAS,CACP,eAAgB3G,EAAW,eAC3B,OAAQ6G,GAAM,QAAU,GACxB,YAAYC,EAAyB,CACnC,KAAK,YAAYA,CAAU,CAC7B,EACA,kBAAApC,CACF,EACA,KAAK,uBACL,KAAAkC,CAAA,EAVK5G,EAAW,IAWlB,CAGD,EAAA,CAACwE,EAAgBxE,EAAW0E,CAAiB,CAAC,EAG/C,OAAA9F,EAACc,GAAA,CACC,gBAAiBX,EACjB,KAAMiF,EACN,MAAApE,EACA,YAAagE,EACb,QAASY,EACT,qBAAAzE,GACA,UAAAC,EACA,MAAO0G,GACP,QAASpD,EACT,eAAgB2B,GAChB,kBAAmBO,EAAA,CACrB,CAEJ","x_google_ignoreList":[0,3]}
|
|
1
|
+
{"version":3,"file":"PaymentMethods.js","sources":["../../node_modules/@adobe-commerce/elsie/src/icons/Wallet.svg","/@dropins/storefront-checkout/src/components/PaymentMethods/PaymentMethodsSkeleton.tsx","/@dropins/storefront-checkout/src/components/PaymentMethods/PaymentMethods.tsx","../../node_modules/@adobe-commerce/elsie/src/lib/debounce.ts","/@dropins/storefront-checkout/src/containers/PaymentMethods/handlers.tsx","/@dropins/storefront-checkout/src/containers/PaymentMethods/PaymentMethods.tsx"],"sourcesContent":["import * as React from \"react\";\nconst SvgWallet = (props) => /* @__PURE__ */ React.createElement(\"svg\", { width: 24, height: 24, viewBox: \"0 0 24 24\", fill: \"none\", xmlns: \"http://www.w3.org/2000/svg\", ...props }, /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M17.93 14.8V18.75H5.97C4.75 18.75 3.75 17.97 3.75 17V6.5M3.75 6.5C3.75 5.53 4.74 4.75 5.97 4.75H15.94V8.25H5.97C4.75 8.25 3.75 7.47 3.75 6.5Z\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M19.35 11.64H14.04V14.81H19.35V11.64Z\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M17.9304 11.64V8.25H15.1504\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }));\nexport default SvgWallet;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { Skeleton, SkeletonRow } from '@adobe-commerce/elsie/components';\nimport { FunctionComponent } from 'preact';\n\nexport const PaymentMethodsSkeleton: FunctionComponent = () => {\n return (\n <Skeleton data-testid=\"payment-methods-skeleton\">\n <SkeletonRow size=\"medium\" variant=\"heading\" />\n <SkeletonRow size=\"medium\" variant=\"empty\" />\n <SkeletonRow fullWidth={true} size=\"xlarge\" />\n <SkeletonRow fullWidth={true} size=\"xlarge\" />\n </Skeleton>\n );\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { WithConditionals } from '@/checkout/components/ConditionalWrapper/ConditionalWrapper';\nimport '@/checkout/components/PaymentMethods/PaymentMethods.css';\nimport { PaymentMethodsSkeleton } from '@/checkout/components/PaymentMethods/PaymentMethodsSkeleton';\nimport { PaymentMethodConfig } from '@/checkout/containers';\nimport { PaymentMethod } from '@/checkout/data/models/payment-method';\nimport { scrollToElement } from '@/checkout/lib';\nimport { UIComponentType } from '@/checkout/types';\nimport {\n Icon,\n IllustratedMessage,\n InLineAlert,\n RadioButton,\n ToggleButton,\n} from '@adobe-commerce/elsie/components';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { Wallet } from '@adobe-commerce/elsie/icons';\nimport { classes, VComponent } from '@adobe-commerce/elsie/lib';\nimport { FunctionComponent, VNode } from 'preact';\nimport { HTMLAttributes, useEffect, useRef } from 'preact/compat';\n\ninterface ExtendedPaymentMethod extends PaymentMethodConfig, PaymentMethod {}\n\nexport interface PaymentMethodsProps\n extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {\n error?: string | null;\n busy?: boolean;\n onDismissError?: () => void;\n onSelectionChange?: (value: PaymentMethod) => void;\n options?: ExtendedPaymentMethod[];\n paymentMethodContent?: VNode;\n selection: PaymentMethod | null;\n title?: VNode;\n UIComponentType?: UIComponentType;\n}\n\ninterface PaymentOptionProps {\n UIComponentType?: UIComponentType;\n busy?: boolean;\n code: string;\n icon?: string;\n onSelectionChange: (value: PaymentMethod) => void;\n selected: boolean;\n title: string;\n}\n\nconst PaymentOption: FunctionComponent<PaymentOptionProps> = ({\n UIComponentType = 'ToggleButton',\n busy,\n code,\n icon,\n onSelectionChange,\n selected,\n title,\n}) => {\n const commonProps = {\n busy,\n className: 'checkout-payment-methods__method',\n label: title,\n name: 'payment-method',\n onChange: () => onSelectionChange({ code, title }),\n value: code,\n };\n\n return UIComponentType === 'ToggleButton' ? (\n <ToggleButton\n {...commonProps}\n // @ts-ignore\n icon={icon ? <Icon source={icon} /> : undefined}\n selected={selected}\n />\n ) : (\n <RadioButton {...commonProps} checked={selected} icon={icon ?? undefined} />\n );\n};\n\nconst PaymentMethodsComponent: FunctionComponent<PaymentMethodsProps> = ({\n className,\n error = null,\n busy = false,\n onDismissError,\n onSelectionChange = () => {},\n options,\n paymentMethodContent,\n selection,\n title,\n UIComponentType,\n}) => {\n const translations = useText({\n EmptyState: 'Checkout.PaymentMethods.emptyState',\n });\n\n const hasError = error !== null;\n const errorRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n if (hasError && errorRef.current) {\n scrollToElement(errorRef.current);\n }\n }, [hasError]);\n\n return (\n <div\n className={classes(['checkout-payment-methods', className])}\n data-testid=\"checkout-payment-methods\"\n >\n {title && (\n <VComponent className=\"checkout-payment-methods__title\" node={title} />\n )}\n\n {!busy && options!.length === 0 && (\n <IllustratedMessage\n data-testid=\"checkout-payment-methods-empty\"\n icon={<Icon source={Wallet} />}\n message={<p>{translations.EmptyState}</p>}\n />\n )}\n\n <div\n className={classes([\n 'checkout-payment-methods__wrapper',\n ['checkout-payment-methods__wrapper--busy', busy],\n ])}\n data-testid=\"checkout-payment-methods-wrapper\"\n >\n <div\n className={classes([\n 'checkout-payment-methods__methods',\n ['checkout-payment-methods--full-width', options!.length % 2 !== 0],\n ])}\n >\n {options?.map((method) => (\n <PaymentOption\n key={method.code}\n UIComponentType={UIComponentType}\n busy={busy}\n code={method.code}\n icon={method.icon}\n selected={selection?.code === method.code}\n title={method.displayLabel ?? true ? method.title : ''}\n onSelectionChange={onSelectionChange}\n />\n ))}\n </div>\n\n {paymentMethodContent && (\n <div className=\"checkout-payment-methods__content\">\n {paymentMethodContent}\n </div>\n )}\n </div>\n\n {hasError && (\n <div\n ref={errorRef}\n className=\"checkout-payment-methods__error\"\n data-testid=\"checkout-payment-methods-alert\"\n >\n <InLineAlert\n heading={error}\n type=\"error\"\n variant=\"primary\"\n onDismiss={onDismissError}\n />\n </div>\n )}\n </div>\n );\n};\n\nexport const PaymentMethods = WithConditionals(\n PaymentMethodsComponent,\n PaymentMethodsSkeleton\n);\n","/********************************************************************\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nexport const debounce = (fn: Function, ms: number) => {\n let timeoutId: ReturnType<typeof setTimeout>;\n return function (this: any, ...args: any[]) {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => fn.apply(this, args), ms);\n };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { setPaymentMethod } from '@/checkout/api';\nimport {\n PaymentMethodConfig,\n PaymentOnAccount,\n PurchaseOrder,\n} from '@/checkout/containers';\nimport { validateNotEmpty } from '@/checkout/lib/validation';\nimport { render as Checkout } from '@/checkout/render/render';\nimport { Container } from '@adobe-commerce/elsie/lib';\nimport { debounce } from '@adobe-commerce/elsie/lib/debounce';\n\ninterface HandlerConfig {\n Container: Container<any>;\n autoSync: boolean;\n formName?: string;\n validateRefNumber: boolean;\n}\n\nexport enum HandlerCode {\n PaymentOnAccount = 'companycredit',\n PurchaseOrder = 'purchaseorder',\n}\n\nconst HANDLERS_CONFIG: Record<HandlerCode, HandlerConfig> = {\n [HandlerCode.PaymentOnAccount]: {\n Container: PaymentOnAccount,\n autoSync: true,\n formName: 'payment-on-account',\n validateRefNumber: false,\n },\n [HandlerCode.PurchaseOrder]: {\n Container: PurchaseOrder,\n autoSync: false,\n formName: 'purchase-order',\n validateRefNumber: true,\n },\n} as const;\n\n// Cache for debounced handlers to prevent memory leaks\nconst debouncedHandlers = new Map<string, ReturnType<typeof debounce>>();\n\nexport const handleRefNumberChange = (code: string, isRequired: boolean) => {\n const key = `${code}-${isRequired}`;\n\n if (!debouncedHandlers.has(key)) {\n const debouncedFn = debounce(async (refNumber: string) => {\n if (!isRequired || validateNotEmpty(refNumber)) {\n try {\n await setPaymentMethod({\n code,\n purchase_order_number: refNumber,\n });\n } catch (error) {\n console.error(`Failed to set payment method for ${code}:`, error);\n }\n }\n }, 1000);\n\n debouncedHandlers.set(key, debouncedFn);\n }\n\n return debouncedHandlers.get(key)!;\n};\n\nconst handlerCache: Partial<Record<HandlerCode, PaymentMethodConfig>> = {};\n\nexport const resetHandlersCache = () => {\n Object.keys(handlerCache).forEach((key) => {\n delete handlerCache[key as HandlerCode];\n });\n\n debouncedHandlers.clear();\n};\n\nexport const createHandler = (code: HandlerCode): PaymentMethodConfig => {\n if (!(code in HANDLERS_CONFIG)) {\n throw new Error(`Invalid handler code: ${code}`);\n }\n\n if (handlerCache[code]) {\n return handlerCache[code] as PaymentMethodConfig;\n }\n\n const config = HANDLERS_CONFIG[code];\n\n const { autoSync, Container, formName, validateRefNumber } = config;\n\n const handler: PaymentMethodConfig = {\n enabled: true,\n autoSync,\n render: (ctx) => {\n const initialReferenceNumber = String(\n ctx.additionalData?.purchase_order_number ?? ''\n );\n\n const $wrapper = document.createElement('div');\n\n Checkout.render(Container, {\n name: formName,\n initialReferenceNumber,\n onReferenceNumberChange: handleRefNumberChange(code, validateRefNumber),\n })($wrapper);\n\n ctx.replaceHTML($wrapper);\n },\n };\n\n handlerCache[code] = handler;\n\n return handler;\n};\n\nexport const defaultHandlers = {\n [HandlerCode.PaymentOnAccount]: createHandler(HandlerCode.PaymentOnAccount),\n [HandlerCode.PurchaseOrder]: createHandler(HandlerCode.PurchaseOrder),\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { setPaymentMethod } from '@/checkout/api';\nimport { PaymentMethods as PaymentMethodsComponent } from '@/checkout/components/PaymentMethods/PaymentMethods';\nimport { Cart } from '@/checkout/data/models/cart';\nimport {\n AdditionalData,\n PaymentMethod\n} from '@/checkout/data/models/payment-method';\nimport { NegotiableQuote } from '@/checkout/data/models/quote';\nimport {\n getLatestCheckoutUpdate,\n getValue,\n hasPendingUpdates,\n hasShippingAddress,\n isVirtualCart,\n notifyValues,\n state\n} from '@/checkout/lib';\nimport { TitleProps, UIComponentType } from '@/checkout/types';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport {\n Container,\n deepmerge,\n Slot,\n SlotProps\n} from '@adobe-commerce/elsie/lib';\nimport { events } from '@adobe-commerce/event-bus';\nimport { HTMLAttributes } from 'preact/compat';\nimport { useCallback, useEffect, useMemo, useState } from 'preact/hooks';\nimport { defaultHandlers } from './handlers';\n\ninterface RenderContext {\n additionalData?: AdditionalData;\n cartId: string;\n replaceHTML: (domElement: HTMLElement) => void;\n setAdditionalData: (data: AdditionalData) => void;\n}\n\nexport interface PaymentMethodConfig {\n autoSync?: boolean;\n displayLabel?: boolean;\n enabled?: boolean;\n icon?: string;\n render?: SlotProps<RenderContext>;\n}\n\nexport interface PaymentMethodHandlers {\n [code: string]: PaymentMethodConfig;\n}\n\ninterface CartSyncError {\n method: PaymentMethod;\n error: Error;\n}\n\nexport interface PaymentMethodsProps\n extends HTMLAttributes<HTMLDivElement>,\n TitleProps {\n slots?: {\n Methods?: PaymentMethodHandlers;\n } & TitleProps['slots'];\n UIComponentType?: UIComponentType;\n active?: boolean;\n autoSync?: boolean;\n onCartSyncError?: (error: CartSyncError) => void;\n onSelectionChange?: (method: PaymentMethod) => void;\n}\n\nfunction isAvailable(\n selection: PaymentMethod | null,\n options: PaymentMethod[]\n) {\n if (!selection) return false;\n return options.some((option) => option.code === selection.code);\n}\n\nfunction isEqual(a: PaymentMethod | null, b: PaymentMethod | null) {\n if (!a || !b) return false;\n return a.code === b.code;\n}\n\nfunction isValid(method: PaymentMethod | null) {\n if (!method) return false;\n return !!method.code && !!method.title;\n}\n\nexport const PaymentMethods: Container<PaymentMethodsProps> = ({\n UIComponentType = 'ToggleButton',\n active = true,\n autoSync = true,\n displayTitle = true,\n slots,\n onCartSyncError,\n onSelectionChange,\n}) => {\n const [error, setError] = useState<string | null>(null);\n const [isInitialized, setIsInitialized] = useState(false);\n const [selection, setSelection] = useState<PaymentMethod | null>(null);\n const [options, setOptions] = useState<PaymentMethod[]>([]);\n const isBusy = hasPendingUpdates.value;\n\n const { cartSyncError, defaultTitle } = useText({\n cartSyncError: 'Checkout.PaymentMethods.cartSyncError',\n defaultTitle: 'Checkout.PaymentMethods.title',\n });\n\n const availableHandlers = useMemo(() => {\n const customHandlers = slots?.Methods ?? {};\n return deepmerge(defaultHandlers, customHandlers);\n }, [slots?.Methods]);\n\n const getSlot = useCallback((method: PaymentMethod) => {\n return availableHandlers[method.code]?.render;\n }, [availableHandlers]);\n\n const hasAutoSyncEnabled = useCallback((method: PaymentMethod) => {\n const config = availableHandlers[method.code];\n if (!config) return autoSync;\n return config.autoSync !== false;\n }, [autoSync, availableHandlers]);\n\n const isEnabled = useCallback((method: PaymentMethod) => {\n const config = availableHandlers[method.code]?.enabled;\n return config !== false;\n }, [availableHandlers]);\n\n const withIcons = useCallback((options: PaymentMethod[]) => {\n return options.map((option) => {\n const handler = availableHandlers[option.code];\n if (!handler) return option;\n return {\n ...option,\n icon: handler.icon\n };\n });\n }, [availableHandlers]);\n\n const setAdditionalData = useCallback((additionalData: AdditionalData) => {\n setSelection((prev) => {\n if (!prev) return prev;\n return { ...prev, additionalData };\n });\n }, []);\n\n const handleDismissError = useCallback(() => {\n setError(null);\n }, []);\n\n const updateSelection = useCallback((selection: PaymentMethod | null) => {\n setError(null);\n setSelection(selection);\n }, []);\n\n const updateCartSelection = useCallback(\n async (selection: PaymentMethod, fallback?: PaymentMethod | null) => {\n const canSetSelectionOnCart = isVirtualCart() || hasShippingAddress();\n\n if (!canSetSelectionOnCart) return;\n if (!hasAutoSyncEnabled(selection)) return;\n\n setPaymentMethod({ code: selection.code }).catch((error) => {\n updateSelection(fallback ?? null);\n setError(onCartSyncError ? null : cartSyncError);\n onCartSyncError?.({ method: selection, error });\n });\n },\n [\n cartSyncError,\n hasAutoSyncEnabled,\n onCartSyncError,\n updateSelection,\n ]\n );\n\n const handleSelectionChange = useCallback(\n async (selection: PaymentMethod) => {\n const prevSelection = getValue('selectedPaymentMethod');\n updateSelection(selection);\n onSelectionChange?.(selection);\n await updateCartSelection(selection, prevSelection);\n },\n [onSelectionChange, updateSelection, updateCartSelection]\n );\n\n const handleCheckoutData = useCallback(\n (data: Cart | NegotiableQuote | null) => {\n const isEmptyCart = !data || data.isEmpty;\n\n if (isEmptyCart) {\n updateSelection(null);\n setOptions([]);\n return;\n }\n\n const availableOptions = data.availablePaymentMethods ?? [];\n const enabledOptions = availableOptions.filter(isEnabled);\n\n setOptions(enabledOptions);\n\n if (enabledOptions.length === 0) {\n updateSelection(null);\n return;\n }\n\n const cartSelection = data.selectedPaymentMethod ?? null;\n const hasCartSelection = isValid(cartSelection);\n const userSelection = getValue('selectedPaymentMethod');\n const isUserSelectionAvailable = isAvailable(userSelection, enabledOptions);\n const haveSameSelection = isEqual(userSelection, cartSelection);\n\n // User has valid selection that differs from cart\n if (userSelection && isUserSelectionAvailable && !haveSameSelection) {\n updateCartSelection(userSelection, cartSelection);\n return;\n }\n\n // User has invalid selection but cart has valid selection\n if (\n (!userSelection || !isUserSelectionAvailable) &&\n hasCartSelection &&\n isAvailable(cartSelection, enabledOptions)\n ) {\n updateSelection(cartSelection);\n return;\n }\n\n // Neither user nor cart has valid selection (or both selections are unavailable)\n if (\n (!userSelection || !isUserSelectionAvailable) &&\n (!hasCartSelection ||\n !isAvailable(cartSelection, enabledOptions))\n ) {\n const newSelection = enabledOptions[0];\n updateSelection(newSelection);\n updateCartSelection(newSelection);\n }\n },\n [isEnabled, updateSelection, updateCartSelection]\n );\n\n useEffect(() => {\n if (!active) return;\n\n const pastUpdate = getLatestCheckoutUpdate();\n\n if (pastUpdate) {\n setIsInitialized(true);\n // When component becomes active, restore key state so handleCheckoutData can work properly\n const userSelection = getValue('selectedPaymentMethod');\n if (userSelection) {\n setSelection(userSelection);\n }\n handleCheckoutData(pastUpdate);\n return;\n }\n\n const onCheckoutInit = events.on(\n 'checkout/initialized',\n (data: Cart | NegotiableQuote | null) => {\n setIsInitialized(true);\n handleCheckoutData(data);\n },\n { eager: true }\n );\n\n return () => {\n onCheckoutInit?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n if (!active) return;\n\n const onCheckoutUpdated = events.on(\n 'checkout/updated',\n handleCheckoutData,\n { eager: false }\n );\n\n return () => {\n onCheckoutUpdated?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n notifyValues({ selectedPaymentMethod: selection });\n }, [selection]);\n\n const titleContent = useMemo(() => {\n if (!displayTitle) return undefined;\n\n return (\n <Slot name=\"checkout-payment-methods-title\" slot={slots?.Title}>\n <h2>{defaultTitle}</h2>\n </Slot>\n );\n }, [displayTitle, slots?.Title, defaultTitle]);\n\n const paymentMethodContent = useMemo(() => {\n if (!selection) return;\n\n const slot = getSlot(selection);\n if (!slot) return;\n\n return (\n <Slot\n key={selection!.code}\n context={{\n additionalData: selection!.additionalData,\n cartId: state.cartId ?? '',\n replaceHTML(domElement: HTMLElement) {\n this.replaceWith(domElement);\n },\n setAdditionalData,\n }}\n name=\"PaymentMethodContent\"\n slot={slot}\n />\n );\n\n }, [getSlot, selection, setAdditionalData]);\n\n return (\n <PaymentMethodsComponent\n UIComponentType={UIComponentType}\n busy={isBusy}\n error={error}\n initialized={isInitialized}\n options={withIcons(options)}\n paymentMethodContent={paymentMethodContent}\n selection={selection}\n title={titleContent}\n visible={active}\n onDismissError={handleDismissError}\n onSelectionChange={handleSelectionChange}\n />\n );\n};\n"],"names":["SvgWallet","props","React","PaymentMethodsSkeleton","jsxs","Skeleton","jsx","SkeletonRow","PaymentOption","UIComponentType","busy","code","icon","onSelectionChange","selected","title","commonProps","ToggleButton","Icon","RadioButton","PaymentMethodsComponent","className","error","onDismissError","options","paymentMethodContent","selection","translations","useText","hasError","errorRef","useRef","useEffect","scrollToElement","classes","VComponent","IllustratedMessage","Wallet","method","InLineAlert","PaymentMethods","WithConditionals","debounce","fn","ms","timeoutId","args","HandlerCode","HANDLERS_CONFIG","PaymentOnAccount","PurchaseOrder","debouncedHandlers","handleRefNumberChange","isRequired","key","debouncedFn","refNumber","validateNotEmpty","setPaymentMethod","handlerCache","resetHandlersCache","createHandler","config","autoSync","Container","formName","validateRefNumber","handler","ctx","initialReferenceNumber","_a","$wrapper","Checkout","defaultHandlers","isAvailable","option","isEqual","a","b","isValid","active","displayTitle","slots","onCartSyncError","setError","useState","isInitialized","setIsInitialized","setSelection","setOptions","isBusy","hasPendingUpdates","cartSyncError","defaultTitle","availableHandlers","useMemo","customHandlers","deepmerge","getSlot","useCallback","hasAutoSyncEnabled","isEnabled","withIcons","setAdditionalData","additionalData","prev","handleDismissError","updateSelection","updateCartSelection","fallback","isVirtualCart","hasShippingAddress","handleSelectionChange","prevSelection","getValue","handleCheckoutData","data","enabledOptions","cartSelection","hasCartSelection","userSelection","isUserSelectionAvailable","haveSameSelection","newSelection","pastUpd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BnF,EAAU,IAAM,CACDiG,GAAA,CAAE,sBAAuBvG,EAAW,CAAA,EAChD,CAACA,CAAS,CAAC,EAER,MAAAwG,GAAenC,EAAQ,IAAM,CAC7B,GAACd,EAGH,OAAA3E,EAAC6H,EAAK,CAAA,KAAK,iCAAiC,KAAMjD,GAAA,YAAAA,EAAO,MACvD,SAAA5E,EAAC,KAAI,CAAA,SAAAuF,CAAa,CAAA,EACpB,GAED,CAACZ,EAAcC,GAAA,YAAAA,EAAO,MAAOW,CAAY,CAAC,EAEvCpE,GAAuBsE,EAAQ,IAAM,CACzC,GAAI,CAACrE,EAAW,OAEV,MAAA0G,EAAOlC,EAAQxE,CAAS,EAC9B,GAAK0G,EAGH,OAAA9H,EAAC6H,EAAA,CAEC,QAAS,CACP,eAAgBzG,EAAW,eAC3B,OAAQ2G,GAAM,QAAU,GACxB,YAAYC,EAAyB,CACnC,KAAK,YAAYA,CAAU,CAC7B,EACA,kBAAA/B,CACF,EACA,KAAK,uBACL,KAAA6B,CAAA,EAVK1G,EAAW,IAWlB,CAGD,EAAA,CAACwE,EAASxE,EAAW6E,CAAiB,CAAC,EAGxC,OAAAjG,EAACc,GAAA,CACC,gBAAiBX,EACjB,KAAMiF,GACN,MAAApE,EACA,YAAagE,EACb,QAASgB,GAAU9E,CAAO,EAC1B,qBAAAC,GACA,UAAAC,EACA,MAAOwG,GACP,QAASlD,EACT,eAAgB0B,GAChB,kBAAmBM,EAAA,CACrB,CAEJ","x_google_ignoreList":[0,3]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
/*! Copyright 2025 Adobe
|
|
2
2
|
All Rights Reserved. */
|
|
3
|
-
import{jsxs as
|
|
3
|
+
import{jsxs as A,jsx as r,Fragment as K}from"@dropins/tools/preact-jsx-runtime.js";import{h as pe,m as de,n as X}from"../chunks/fetch-graphql.js";import{classes as D,VComponent as he,Slot as me}from"@dropins/tools/lib.js";import{t as fe}from"../chunks/transform-shipping-estimate.js";import{h as I,a as ge}from"../chunks/events2.js";import{n as ke,g as N}from"../chunks/values.js";import{events as B}from"@dropins/tools/event-bus.js";import{c as Y}from"../chunks/synchronizeCheckout.js";import{s as ve}from"../chunks/setShippingMethods.js";import{W as Se}from"../chunks/ConditionalWrapper.js";/* empty css */import{Skeleton as Ee,SkeletonRow as T,IllustratedMessage as Ce,Icon as Le,InLineAlert as Me,RadioButton as ye,Price as ee,ToggleButton as _e}from"@dropins/tools/components.js";import{s as We}from"../chunks/dom.js";import{useRef as ne,useEffect as R,useState as V,useCallback as p,useMemo as te}from"@dropins/tools/preact-hooks.js";import*as a from"@dropins/tools/preact-compat.js";import{useText as re}from"@dropins/tools/i18n.js";import"@dropins/tools/signals.js";import"@dropins/tools/fetch-graphql.js";import"../fragments.js";import"../chunks/transform-shipping-methods.js";import"../chunks/classifiers.js";import"../chunks/guards.js";const je=i=>a.createElement("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",...i},a.createElement("path",{vectorEffect:"non-scaling-stroke",d:"M2.47266 4.90002H15.1851V10.9645H21.2495L23 12.715V17.6124H20.073",stroke:"currentColor",strokeWidth:1,strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("path",{vectorEffect:"non-scaling-stroke",d:"M15.1758 5.87573H19.0019L21.0394 10.7636",stroke:"currentColor",strokeWidth:1,strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("path",{vectorEffect:"non-scaling-stroke",d:"M9.76151 16.7898C9.76151 18.0525 8.72845 19.076 7.46582 19.076C6.20318 19.076 5.17969 18.0429 5.17969 16.7803C5.17969 15.5176 6.20318 14.4941 7.46582 14.4941C8.72845 14.4941 9.75195 15.5176 9.76151 16.7803C9.76151 16.7803 9.76151 16.7803 9.76151 16.7898Z",stroke:"currentColor",strokeWidth:1,strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("path",{vectorEffect:"non-scaling-stroke",d:"M19.8726 16.7898C19.8726 18.062 18.8491 19.0855 17.5769 19.0855C16.3047 19.0855 15.2812 18.062 15.2812 16.7898C15.2812 15.5176 16.3047 14.4941 17.5769 14.4941C18.8491 14.4941 19.8726 15.5176 19.8726 16.7898Z",stroke:"currentColor",strokeWidth:1,strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("path",{vectorEffect:"non-scaling-stroke",d:"M8.08792 7.63574H1.69824",stroke:"currentColor",strokeWidth:1,strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("path",{vectorEffect:"non-scaling-stroke",d:"M7.11229 10.3619H1",stroke:"currentColor",strokeWidth:1,strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("path",{vectorEffect:"non-scaling-stroke",d:"M5.16084 13.0402H1.92773",stroke:"currentColor",strokeWidth:1,strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("path",{vectorEffect:"non-scaling-stroke",d:"M9.76172 16.7611H15.2809",stroke:"currentColor",strokeWidth:1,strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("path",{vectorEffect:"non-scaling-stroke",d:"M2.38672 16.7611H5.17025",stroke:"currentColor",strokeWidth:1,strokeLinecap:"round",strokeLinejoin:"round"})),Be=()=>A(Ee,{"data-testid":"shipping-methods-skeleton",children:[r(T,{size:"small",variant:"heading"}),r(T,{size:"small",variant:"empty"}),r(T,{fullWidth:!0,size:"medium"}),r(T,{fullWidth:!0,size:"medium"})]}),Oe=({className:i,busy:n=!1,onSelectionChange:g=()=>{},options:v,selection:d,title:l,UIComponentType:u="RadioButton",error:h=null,onDismissError:b=()=>{},...U})=>{const S=re({EmptyState:"Checkout.ShippingMethods.emptyState"}),E=h!==null,C=ne(null);R(()=>{E&&C.current&&We(C.current)},[E]);const L=(o,x)=>{const M={busy:n,className:"checkout-shipping-methods__method",key:o.value,name:"shipping-method",value:o.value,onChange:()=>g(o)};return x==="RadioButton"?r(ye,{...M,checked:(d==null?void 0:d.value)===o.value,"data-testid":"shipping-method-radioButton",description:o.title,disabled:n,id:o.value,label:A(K,{children:[r(ee,{amount:o.amount.value,currency:o.amount.currency})," ",r("span",{children:o.carrier.title})]})}):r(_e,{...M,"data-testid":"shipping-method-toggleButton",label:A(K,{children:[r("span",{children:o.carrier.title}),r(ee,{amount:o.amount.value,currency:o.amount.currency})]}),selected:(d==null?void 0:d.value)===o.value})};return A("div",{...U,className:D(["checkout-shipping-methods",i]),"data-testid":"checkout-shipping-methods",children:[l&&r(he,{className:"checkout-shipping-methods__title",node:l}),r("div",{className:D(["checkout-shipping-methods__content"]),children:r("div",{className:D(["checkout-shipping-methods__options",["checkout-shipping-methods__options--busy",n],["checkout-shipping-methods__options--toggleButton",u==="ToggleButton"]]),"data-testid":"checkout-shipping-methods-options",children:v.length===0?r(Ce,{"data-testid":"checkout-shipping-methods-empty",icon:r(Le,{source:je}),message:r("p",{children:S.EmptyState})}):v.map(o=>L(o,u))})}),E&&r("div",{ref:C,className:"checkout-shipping-methods__error","data-testid":"checkout-shipping-methods-alert",children:r(Me,{heading:h,type:"error",variant:"primary",onDismiss:b})})]})},we=Se(Oe,Be);function P(i,n){return i?n.some(g=>Q(g,i)):!1}function Q(i,n){return!i||!n||i.amount.value!==n.amount.value?!1:i.code===n.code&&i.carrier.code===n.carrier.code}function He(i){const n=B.lastPayload("shipping/estimate");n&&B.emit("shipping/estimate",{...n,shippingMethod:fe(i)})}const Ye=({UIComponentType:i="RadioButton",active:n=!0,autoSync:g=!0,displayTitle:v=!0,initialData:d,slots:l,onCartSyncError:u,onSelectionChange:h,...b})=>{const[U,S]=V(null),[E,C]=V(!1),[L,o]=V(),[x,M]=V(null),O=ne(null),oe=pe.value,ie=de.value,{cartSyncError:Z,defaultTitle:q}=re({cartSyncError:"Checkout.ShippingMethods.cartSyncError",defaultTitle:"Checkout.ShippingMethods.title"}),w=p(e=>{if(!e||e.length===0)return[];const{shipping:t}=Y.getConfig();return t!=null&&t.filterOptions?e.filter(t.filterOptions):e},[]),F=p(e=>{if(e.length===0)return null;const{defaults:t}=Y.getConfig();return t.selectedShippingMethod(e)},[]),se=te(()=>w(L),[L,w]),ce=p(()=>{S(null)},[]),c=p(e=>{S(null),M(t=>Q(t,e)?t:(ke({selectedShippingMethod:e}),e))},[]),y=p(async(e,t)=>{if(!g||!I())return;const s={carrierCode:e.carrier.code,methodCode:e.code};ve([s]).catch(m=>{c(t??null),u==null||u({method:e,error:m}),u||S(Z)})},[g,c,u,Z]),ae=p(async e=>{const t=N("selectedShippingMethod");c(e),h==null||h(e),I()||He(e),await y(e,t)},[h,c,y]),_=p(e=>{var J;const t=!e||e.isEmpty,s=!!(e!=null&&e.isVirtual);if(t||s){C(s),c(null),o([]);return}const m=(J=e.shippingAddresses)==null?void 0:J[0];if(!m)return;const W=m.availableShippingMethods??[];X()&&!O.current&&(O.current=W);const G=X()&&O.current?O.current:W;o(G);const j=w(G);if(j.length===0){c(null);return}const f=m.selectedShippingMethod??null,k=N("selectedShippingMethod"),z=P(k,j),ue=Q(k,f);if(k&&z&&!ue){y(k,f);return}if((!k||!z)&&f&&P(f,j)){c(f);return}if((!k||!z)&&(!f||!P(f,j))){const H=F(j);c(H),H&&y(H)}},[w,F,c,y]),$=p(e=>{if(e===void 0)return;const{shippingMethod:t,availableShippingMethods:s}=e,m=(s==null?void 0:s.find(W=>W.code===(t==null?void 0:t.methodCode)&&W.carrier.code===(t==null?void 0:t.carrierCode)))??null;o(s),c(m)},[c]);R(()=>{if(!n)return;const e=ge();if(e){const s=N("selectedShippingMethod");s&&M(s),_(e);return}const t=B.on("checkout/initialized",_,{eager:!0});return()=>{t==null||t.off()}},[n,_]),R(()=>{if(!n)return;const e=B.on("checkout/updated",_,{eager:!1});return()=>{e==null||e.off()}},[n,_]),R(()=>{if(!n||I())return;const e=B.on("shipping/estimate",$,{eager:!0});return()=>{e==null||e.off()}},[n,$]);const le=te(()=>{if(v)return r(me,{name:"checkout-shipping-methods-title",slot:l==null?void 0:l.Title,children:r("h3",{children:q})})},[v,l==null?void 0:l.Title,q]);return r(we,{...b,UIComponentType:i,busy:oe||ie,error:U,initialized:L!==void 0,options:se,selection:x,title:le,visible:n&&!E,onDismissError:ce,onSelectionChange:ae})};export{Ye as ShippingMethods,Ye as default,He as emitShippingEstimateEvent};
|
|
4
4
|
//# sourceMappingURL=ShippingMethods.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ShippingMethods.js","sources":["../../node_modules/@adobe-commerce/elsie/src/icons/Delivery.svg","/@dropins/storefront-checkout/src/components/ShippingMethods/ShippingMethodsSkeleton.tsx","/@dropins/storefront-checkout/src/components/ShippingMethods/ShippingMethods.tsx","/@dropins/storefront-checkout/src/containers/ShippingMethods/ShippingMethods.tsx"],"sourcesContent":["import * as React from \"react\";\nconst SvgDelivery = (props) => /* @__PURE__ */ React.createElement(\"svg\", { width: 24, height: 24, viewBox: \"0 0 24 24\", fill: \"none\", xmlns: \"http://www.w3.org/2000/svg\", ...props }, /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M2.47266 4.90002H15.1851V10.9645H21.2495L23 12.715V17.6124H20.073\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M15.1758 5.87573H19.0019L21.0394 10.7636\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M9.76151 16.7898C9.76151 18.0525 8.72845 19.076 7.46582 19.076C6.20318 19.076 5.17969 18.0429 5.17969 16.7803C5.17969 15.5176 6.20318 14.4941 7.46582 14.4941C8.72845 14.4941 9.75195 15.5176 9.76151 16.7803C9.76151 16.7803 9.76151 16.7803 9.76151 16.7898Z\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M19.8726 16.7898C19.8726 18.062 18.8491 19.0855 17.5769 19.0855C16.3047 19.0855 15.2812 18.062 15.2812 16.7898C15.2812 15.5176 16.3047 14.4941 17.5769 14.4941C18.8491 14.4941 19.8726 15.5176 19.8726 16.7898Z\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M8.08792 7.63574H1.69824\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M7.11229 10.3619H1\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M5.16084 13.0402H1.92773\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M9.76172 16.7611H15.2809\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M2.38672 16.7611H5.17025\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }));\nexport default SvgDelivery;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { FunctionComponent } from 'preact';\nimport { Skeleton, SkeletonRow } from '@adobe-commerce/elsie/components';\n\nexport const ShippingMethodsSkeleton: FunctionComponent = () => {\n return (\n <Skeleton data-testid=\"shipping-methods-skeleton\">\n <SkeletonRow size=\"small\" variant=\"heading\" />\n <SkeletonRow size=\"small\" variant=\"empty\" />\n <SkeletonRow fullWidth={true} size=\"medium\" />\n <SkeletonRow fullWidth={true} size=\"medium\" />\n </Skeleton>\n );\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { WithConditionals } from '@/checkout/components/ConditionalWrapper/ConditionalWrapper';\nimport '@/checkout/components/ShippingMethods/ShippingMethods.css';\nimport { ShippingMethodsSkeleton } from '@/checkout/components/ShippingMethods/ShippingMethodsSkeleton';\nimport { ShippingMethod } from '@/checkout/data/models';\nimport { scrollToElement } from '@/checkout/lib';\nimport { UIComponentType } from '@/checkout/types';\nimport {\n Icon,\n IllustratedMessage,\n InLineAlert,\n Price,\n RadioButton,\n ToggleButton,\n} from '@adobe-commerce/elsie/components';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { Delivery } from '@adobe-commerce/elsie/icons';\nimport { classes, VComponent } from '@adobe-commerce/elsie/lib';\nimport { FunctionComponent, VNode } from 'preact';\nimport { HTMLAttributes } from 'preact/compat';\nimport { useEffect, useRef } from 'preact/hooks';\n\nexport interface ShippingMethodsProps\n extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {\n UIComponentType?: UIComponentType;\n busy?: boolean;\n error?: string | null;\n onDismissError?: () => void;\n onSelectionChange?: (method: ShippingMethod) => void;\n options: ShippingMethod[];\n selection: ShippingMethod | null;\n title?: VNode;\n}\n\nconst ShippingMethodsComponent: FunctionComponent<ShippingMethodsProps> = ({\n className,\n busy = false,\n onSelectionChange = () => {},\n options,\n selection,\n title,\n UIComponentType = 'RadioButton',\n error = null,\n onDismissError = () => {},\n ...props\n}) => {\n const translations = useText({\n EmptyState: 'Checkout.ShippingMethods.emptyState',\n });\n\n const hasError = error !== null;\n const errorRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n if (hasError && errorRef.current) {\n scrollToElement(errorRef.current);\n }\n }, [hasError]);\n\n const renderShippingMethod = (\n method: ShippingMethod,\n type: UIComponentType\n ) => {\n const commonProps = {\n busy,\n className: 'checkout-shipping-methods__method',\n key: method.value,\n name: 'shipping-method',\n value: method.value,\n onChange: () => onSelectionChange(method),\n };\n\n if (type === 'RadioButton') {\n return (\n <RadioButton\n {...commonProps}\n checked={selection?.value === method.value}\n data-testid=\"shipping-method-radioButton\"\n description={method.title}\n disabled={busy}\n id={method.value}\n label={\n <>\n <Price\n amount={method.amount.value}\n currency={method.amount.currency}\n />\n \n <span>{method.carrier.title}</span>\n </>\n }\n />\n );\n }\n\n return (\n <ToggleButton\n {...commonProps}\n data-testid=\"shipping-method-toggleButton\"\n label={\n <>\n <span>{method.carrier.title}</span>\n <Price\n amount={method.amount.value}\n currency={method.amount.currency}\n />\n </>\n }\n selected={selection?.value === method.value}\n />\n );\n };\n\n return (\n <div\n {...props}\n className={classes(['checkout-shipping-methods', className])}\n data-testid=\"checkout-shipping-methods\"\n >\n {title && (\n <VComponent className=\"checkout-shipping-methods__title\" node={title} />\n )}\n\n <div className={classes(['checkout-shipping-methods__content'])}>\n <div\n className={classes([\n 'checkout-shipping-methods__options',\n ['checkout-shipping-methods__options--busy', busy],\n [\n 'checkout-shipping-methods__options--toggleButton',\n UIComponentType === 'ToggleButton',\n ],\n ])}\n data-testid=\"checkout-shipping-methods-options\"\n >\n {options.length === 0 ? (\n <IllustratedMessage\n data-testid=\"checkout-shipping-methods-empty\"\n icon={<Icon source={Delivery} />}\n message={<p>{translations.EmptyState}</p>}\n />\n ) : (\n options.map((method: ShippingMethod) =>\n renderShippingMethod(method, UIComponentType)\n )\n )}\n </div>\n </div>\n\n {hasError && (\n <div\n ref={errorRef}\n className=\"checkout-shipping-methods__error\"\n data-testid=\"checkout-shipping-methods-alert\"\n >\n <InLineAlert\n heading={error}\n type=\"error\"\n variant=\"primary\"\n onDismiss={onDismissError}\n />\n </div>\n )}\n </div>\n );\n};\n\nexport const ShippingMethods = WithConditionals(\n ShippingMethodsComponent,\n ShippingMethodsSkeleton\n);\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { config, setShippingMethods } from '@/checkout/api';\nimport { ShippingMethods as ShippingMethodsComponent } from '@/checkout/components/ShippingMethods';\nimport {\n Cart,\n NegotiableQuote,\n ShippingEstimate,\n ShippingMethod,\n ShippingMethodInput,\n} from '@/checkout/data/models';\nimport { transformShippingEstimateShippingMethod } from '@/checkout/data/transforms';\nimport {\n getLatestCheckoutUpdate,\n getValue,\n hasPendingShippingEstimate,\n hasPendingUpdates,\n hasShippingAddress,\n notifyValues,\n} from '@/checkout/lib';\nimport { Filter, TitleProps, UIComponentType } from '@/checkout/types';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { Container, Slot } from '@adobe-commerce/elsie/lib';\nimport { events } from '@adobe-commerce/event-bus';\nimport { HTMLAttributes } from 'preact/compat';\nimport { useCallback, useEffect, useMemo, useState } from 'preact/hooks';\n\ninterface CartSyncError {\n method: ShippingMethod;\n error: Error;\n}\n\nexport type ShippingOptionsFilter = Filter<ShippingMethod>;\n\nexport interface ShippingMethodsProps\n extends HTMLAttributes<HTMLDivElement>,\n TitleProps {\n UIComponentType?: UIComponentType;\n active?: boolean;\n autoSync?: boolean;\n onCartSyncError?: (error: CartSyncError) => void;\n onSelectionChange?: (method: ShippingMethod) => void;\n}\n\nfunction isMethodAvailable(\n method: ShippingMethod | null,\n options: ShippingMethod[]\n) {\n if (!method) return false;\n return options.some((option) => isEqual(option, method));\n}\n\nfunction isEqual(a: ShippingMethod | null, b: ShippingMethod | null) {\n if (!a || !b) return false;\n if (a.amount.value !== b.amount.value) return false;\n return a.code === b.code && a.carrier.code === b.carrier.code;\n}\n\nexport function emitShippingEstimateEvent(selection: ShippingMethod) {\n const shippingEstimatedEvent = events.lastPayload('shipping/estimate');\n\n if (!shippingEstimatedEvent) return;\n\n events.emit('shipping/estimate', {\n ...shippingEstimatedEvent,\n shippingMethod: transformShippingEstimateShippingMethod(selection),\n });\n}\n\nexport const ShippingMethods: Container<ShippingMethodsProps> = ({\n UIComponentType = 'RadioButton',\n active = true,\n autoSync = true,\n displayTitle = true,\n initialData,\n slots,\n onCartSyncError,\n onSelectionChange,\n ...props\n}) => {\n const [error, setError] = useState<string | null>(null);\n const [isVirtual, setIsVirtual] = useState(false);\n const [options, setOptions] = useState<ShippingMethod[] | undefined>();\n const [selection, setSelection] = useState<ShippingMethod | null>(null);\n\n const hasQueuedUpdates = hasPendingUpdates.value;\n const hasPendingEstimations = hasPendingShippingEstimate.value;\n\n const { cartSyncError, defaultTitle } = useText({\n cartSyncError: 'Checkout.ShippingMethods.cartSyncError',\n defaultTitle: 'Checkout.ShippingMethods.title',\n });\n\n const filterOptions = useCallback(\n (shippingMethods: ShippingMethod[] | undefined) => {\n if (!shippingMethods || shippingMethods.length === 0) return [];\n const { shipping } = config.getConfig();\n if (!shipping?.filterOptions) return shippingMethods;\n return shippingMethods.filter(shipping.filterOptions);\n },\n []\n );\n\n const preselectOption = useCallback((shippingMethods: ShippingMethod[]) => {\n if (shippingMethods.length === 0) return null;\n const { defaults } = config.getConfig();\n return defaults!.selectedShippingMethod!(shippingMethods);\n }, []);\n\n const filteredOptions = useMemo(() => {\n return filterOptions(options);\n }, [options, filterOptions]);\n\n const handleDismissError = useCallback(() => {\n setError(null);\n }, []);\n\n const setUserSelection = useCallback(\n (shippingMethod: ShippingMethod | null) => {\n setError(null);\n setSelection((prev) => {\n if (isEqual(prev, shippingMethod)) return prev;\n notifyValues({ selectedShippingMethod: shippingMethod });\n return shippingMethod;\n });\n },\n []\n );\n\n const setUserSelectionOnCart = useCallback(\n async (selection: ShippingMethod, fallback?: ShippingMethod | null) => {\n if (!autoSync || !hasShippingAddress()) return;\n\n const shippingMethodInput: ShippingMethodInput = {\n carrierCode: selection.carrier.code,\n methodCode: selection.code,\n };\n\n setShippingMethods([shippingMethodInput]).catch((error) => {\n setUserSelection(fallback ?? null);\n onCartSyncError?.({ method: selection, error });\n\n if (!onCartSyncError) {\n setError(cartSyncError);\n }\n });\n },\n [autoSync, setUserSelection, onCartSyncError, cartSyncError]\n );\n\n const handleSelectionChange = useCallback(\n async (selection: ShippingMethod) => {\n const prevSelection = getValue('selectedShippingMethod');\n\n setUserSelection(selection);\n onSelectionChange?.(selection);\n\n if (!hasShippingAddress()) {\n emitShippingEstimateEvent(selection);\n }\n\n await setUserSelectionOnCart(selection, prevSelection);\n },\n [onSelectionChange, setUserSelection, setUserSelectionOnCart]\n );\n\n const handleCheckoutData = useCallback(\n (data: Cart | NegotiableQuote | null) => {\n const isEmptyCart = !data || data.isEmpty;\n const isVirtualCart = Boolean(data?.isVirtual);\n\n if (isEmptyCart || isVirtualCart) {\n setIsVirtual(isVirtualCart);\n setUserSelection(null);\n setOptions([]);\n return;\n }\n\n const primaryAddress = data!.shippingAddresses?.[0];\n\n // If there is no primary address, options are handled by the shipping estimation\n if (!primaryAddress) return;\n\n const availableOptions = primaryAddress.availableShippingMethods ?? [];\n const filteredOptions = filterOptions(availableOptions);\n setOptions(availableOptions);\n\n // If there are no filtered options, reset the user selection\n if (filteredOptions.length === 0) {\n setUserSelection(null);\n return;\n }\n\n const cartSelection = primaryAddress.selectedShippingMethod ?? null;\n\n const userSelection = getValue('selectedShippingMethod');\n const isAvailable = isMethodAvailable(userSelection, filteredOptions);\n const haveSameSelection = isEqual(userSelection, cartSelection);\n\n // Handle user selection that's available but different from cart\n if (userSelection && isAvailable && !haveSameSelection) {\n setUserSelectionOnCart(userSelection, cartSelection);\n return;\n }\n\n // If no user selection or not available, decide what to do based on cart and filtered options\n if ((!userSelection || !isAvailable) && cartSelection) {\n // Check if cart selection is still available after filtering\n const isCartSelectionAvailable = isMethodAvailable(\n cartSelection,\n filteredOptions\n );\n if (isCartSelectionAvailable) {\n setUserSelection(cartSelection);\n return;\n }\n }\n\n if (\n (!userSelection || !isAvailable) &&\n (!cartSelection || !isMethodAvailable(cartSelection, filteredOptions))\n ) {\n const newSelection = preselectOption(filteredOptions);\n setUserSelection(newSelection);\n if (newSelection) setUserSelectionOnCart(newSelection);\n }\n },\n [filterOptions, preselectOption, setUserSelection, setUserSelectionOnCart]\n );\n\n const handleShippingEstimate = useCallback(\n (estimation: ShippingEstimate | undefined) => {\n if (estimation === undefined) return;\n\n const { shippingMethod, availableShippingMethods } = estimation;\n\n const selectedShippingMethod =\n availableShippingMethods?.find(\n (method) =>\n method.code === shippingMethod?.methodCode &&\n method.carrier.code === shippingMethod?.carrierCode\n ) ?? null;\n\n setOptions(availableShippingMethods);\n setUserSelection(selectedShippingMethod);\n },\n [setUserSelection]\n );\n\n useEffect(() => {\n if (!active) return;\n\n const pastUpdate = getLatestCheckoutUpdate();\n\n if (pastUpdate) {\n // When component becomes active, restore key state so handleCheckoutData can work properly\n const userSelection = getValue('selectedShippingMethod');\n if (userSelection) {\n setSelection(userSelection);\n }\n\n handleCheckoutData(pastUpdate);\n return;\n }\n\n const onCheckoutInit = events.on(\n 'checkout/initialized',\n handleCheckoutData,\n { eager: true }\n );\n\n return () => {\n onCheckoutInit?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n if (!active) return;\n\n const onCheckoutUpdated = events.on(\n 'checkout/updated',\n handleCheckoutData,\n { eager: false }\n );\n\n return () => {\n onCheckoutUpdated?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n if (!active || hasShippingAddress()) return;\n\n const onShippingEstimate = events.on(\n 'shipping/estimate',\n handleShippingEstimate,\n { eager: true }\n );\n\n return () => {\n onShippingEstimate?.off();\n };\n }, [active, handleShippingEstimate]);\n\n const titleContent = useMemo(() => {\n if (!displayTitle) return undefined;\n\n return (\n <Slot name=\"checkout-shipping-methods-title\" slot={slots?.Title}>\n <h3>{defaultTitle}</h3>\n </Slot>\n );\n }, [displayTitle, slots?.Title, defaultTitle]);\n\n return (\n <ShippingMethodsComponent\n {...props}\n UIComponentType={UIComponentType}\n busy={hasQueuedUpdates || hasPendingEstimations}\n error={error}\n initialized={options !== undefined}\n options={filteredOptions}\n selection={selection}\n title={titleContent}\n visible={active && !isVirtual}\n onDismissError={handleDismissError}\n onSelectionChange={handleSelectionChange}\n />\n );\n};\n"],"names":["SvgDelivery","props","React","ShippingMethodsSkeleton","jsxs","Skeleton","jsx","SkeletonRow","ShippingMethodsComponent","className","busy","onSelectionChange","options","selection","title","UIComponentType","error","onDismissError","translations","useText","hasError","errorRef","useRef","useEffect","scrollToElement","renderShippingMethod","method","type","commonProps","RadioButton","Fragment","Price","ToggleButton","classes","VComponent","IllustratedMessage","Icon","Delivery","InLineAlert","ShippingMethods","WithConditionals","isMethodAvailable","option","isEqual","a","b","emitShippingEstimateEvent","shippingEstimatedEvent","events","transformShippingEstimateShippingMethod","active","autoSync","displayTitle","initialData","slots","onCartSyncError","setError","useState","isVirtual","setIsVirtual","setOptions","setSelection","hasQueuedUpdates","hasPendingUpdates","hasPendingEstimations","hasPendingShippingEstimate","cartSyncError","defaultTitle","filterOptions","useCallback","shippingMethods","shipping","config","preselectOption","defaults","filteredOptions","useMemo","handleDismissError","setUserSelection","shippingMethod","prev","notifyValues","setUserSelectionOnCart","fallback","hasShippingAddress","shippingMethodInput","setShippingMethods","handleSelectionChange","prevSelection","getValue","handleCheckoutData","data","isEmptyCart","isVirtualCart","primaryAddress","_a","availableOptions","cartSelection","userSelection","isAvailable","haveSameSelection","newSelection","handleShippingEstimate","estimation","availableShippingMethods","selectedShippingMethod","pastUpdate","getLatestCheckoutUpdate","onCheckoutInit","onCheckoutUpdated","onShippingEstimate","titleContent","Slot"],"mappings":"2uCACA,MAAMA,GAAeC,GAA0BC,EAAM,cAAc,MAAO,CAAE,MAAO,GAAI,OAAQ,GAAI,QAAS,YAAa,KAAM,OAAQ,MAAO,6BAA8B,GAAGD,GAAyBC,EAAM,cAAc,OAAQ,CAAE,aAAc,qBAAsB,EAAG,oEAAqE,OAAQ,eAAgB,YAAa,EAAG,cAAe,QAAS,eAAgB,OAAS,CAAA,EAAmBA,EAAM,cAAc,OAAQ,CAAE,aAAc,qBAAsB,EAAG,2CAA4C,OAAQ,eAAgB,YAAa,EAAG,cAAe,QAAS,eAAgB,OAAO,CAAE,EAAmBA,EAAM,cAAc,OAAQ,CAAE,aAAc,qBAAsB,EAAG,iQAAkQ,OAAQ,eAAgB,YAAa,EAAG,cAAe,QAAS,eAAgB,OAAS,CAAA,EAAmBA,EAAM,cAAc,OAAQ,CAAE,aAAc,qBAAsB,EAAG,kNAAmN,OAAQ,eAAgB,YAAa,EAAG,cAAe,QAAS,eAAgB,OAAO,CAAE,EAAmBA,EAAM,cAAc,OAAQ,CAAE,aAAc,qBAAsB,EAAG,2BAA4B,OAAQ,eAAgB,YAAa,EAAG,cAAe,QAAS,eAAgB,OAAO,CAAE,EAAmBA,EAAM,cAAc,OAAQ,CAAE,aAAc,qBAAsB,EAAG,qBAAsB,OAAQ,eAAgB,YAAa,EAAG,cAAe,QAAS,eAAgB,QAAS,EAAmBA,EAAM,cAAc,OAAQ,CAAE,aAAc,qBAAsB,EAAG,2BAA4B,OAAQ,eAAgB,YAAa,EAAG,cAAe,QAAS,eAA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AAa,CAAA,EACpB,GAED,CAACf,EAAcE,GAAA,YAAAA,EAAO,MAAOa,CAAY,CAAC,EAG3C,OAAA7D,EAACE,GAAA,CACE,GAAGP,EACJ,gBAAiBc,EACjB,KAAM+C,IAAoBE,GAC1B,MAAAhD,EACA,YAAaJ,IAAY,OACzB,QAAS+D,GACT,UAAA9D,EACA,MAAOkG,GACP,QAAS7D,GAAU,CAACQ,EACpB,eAAgBmB,GAChB,kBAAmBU,EAAA,CACrB,CAEJ","x_google_ignoreList":[0]}
|
|
1
|
+
{"version":3,"file":"ShippingMethods.js","sources":["../../node_modules/@adobe-commerce/elsie/src/icons/Delivery.svg","/@dropins/storefront-checkout/src/components/ShippingMethods/ShippingMethodsSkeleton.tsx","/@dropins/storefront-checkout/src/components/ShippingMethods/ShippingMethods.tsx","/@dropins/storefront-checkout/src/containers/ShippingMethods/ShippingMethods.tsx"],"sourcesContent":["import * as React from \"react\";\nconst SvgDelivery = (props) => /* @__PURE__ */ React.createElement(\"svg\", { width: 24, height: 24, viewBox: \"0 0 24 24\", fill: \"none\", xmlns: \"http://www.w3.org/2000/svg\", ...props }, /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M2.47266 4.90002H15.1851V10.9645H21.2495L23 12.715V17.6124H20.073\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M15.1758 5.87573H19.0019L21.0394 10.7636\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M9.76151 16.7898C9.76151 18.0525 8.72845 19.076 7.46582 19.076C6.20318 19.076 5.17969 18.0429 5.17969 16.7803C5.17969 15.5176 6.20318 14.4941 7.46582 14.4941C8.72845 14.4941 9.75195 15.5176 9.76151 16.7803C9.76151 16.7803 9.76151 16.7803 9.76151 16.7898Z\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M19.8726 16.7898C19.8726 18.062 18.8491 19.0855 17.5769 19.0855C16.3047 19.0855 15.2812 18.062 15.2812 16.7898C15.2812 15.5176 16.3047 14.4941 17.5769 14.4941C18.8491 14.4941 19.8726 15.5176 19.8726 16.7898Z\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M8.08792 7.63574H1.69824\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M7.11229 10.3619H1\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M5.16084 13.0402H1.92773\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M9.76172 16.7611H15.2809\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }), /* @__PURE__ */ React.createElement(\"path\", { vectorEffect: \"non-scaling-stroke\", d: \"M2.38672 16.7611H5.17025\", stroke: \"currentColor\", strokeWidth: 1, strokeLinecap: \"round\", strokeLinejoin: \"round\" }));\nexport default SvgDelivery;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { FunctionComponent } from 'preact';\nimport { Skeleton, SkeletonRow } from '@adobe-commerce/elsie/components';\n\nexport const ShippingMethodsSkeleton: FunctionComponent = () => {\n return (\n <Skeleton data-testid=\"shipping-methods-skeleton\">\n <SkeletonRow size=\"small\" variant=\"heading\" />\n <SkeletonRow size=\"small\" variant=\"empty\" />\n <SkeletonRow fullWidth={true} size=\"medium\" />\n <SkeletonRow fullWidth={true} size=\"medium\" />\n </Skeleton>\n );\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { WithConditionals } from '@/checkout/components/ConditionalWrapper/ConditionalWrapper';\nimport '@/checkout/components/ShippingMethods/ShippingMethods.css';\nimport { ShippingMethodsSkeleton } from '@/checkout/components/ShippingMethods/ShippingMethodsSkeleton';\nimport { ShippingMethod } from '@/checkout/data/models';\nimport { scrollToElement } from '@/checkout/lib';\nimport { UIComponentType } from '@/checkout/types';\nimport {\n Icon,\n IllustratedMessage,\n InLineAlert,\n Price,\n RadioButton,\n ToggleButton,\n} from '@adobe-commerce/elsie/components';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { Delivery } from '@adobe-commerce/elsie/icons';\nimport { classes, VComponent } from '@adobe-commerce/elsie/lib';\nimport { FunctionComponent, VNode } from 'preact';\nimport { HTMLAttributes } from 'preact/compat';\nimport { useEffect, useRef } from 'preact/hooks';\n\nexport interface ShippingMethodsProps\n extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {\n UIComponentType?: UIComponentType;\n busy?: boolean;\n error?: string | null;\n onDismissError?: () => void;\n onSelectionChange?: (method: ShippingMethod) => void;\n options: ShippingMethod[];\n selection: ShippingMethod | null;\n title?: VNode;\n}\n\nconst ShippingMethodsComponent: FunctionComponent<ShippingMethodsProps> = ({\n className,\n busy = false,\n onSelectionChange = () => {},\n options,\n selection,\n title,\n UIComponentType = 'RadioButton',\n error = null,\n onDismissError = () => {},\n ...props\n}) => {\n const translations = useText({\n EmptyState: 'Checkout.ShippingMethods.emptyState',\n });\n\n const hasError = error !== null;\n const errorRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n if (hasError && errorRef.current) {\n scrollToElement(errorRef.current);\n }\n }, [hasError]);\n\n const renderShippingMethod = (\n method: ShippingMethod,\n type: UIComponentType\n ) => {\n const commonProps = {\n busy,\n className: 'checkout-shipping-methods__method',\n key: method.value,\n name: 'shipping-method',\n value: method.value,\n onChange: () => onSelectionChange(method),\n };\n\n if (type === 'RadioButton') {\n return (\n <RadioButton\n {...commonProps}\n checked={selection?.value === method.value}\n data-testid=\"shipping-method-radioButton\"\n description={method.title}\n disabled={busy}\n id={method.value}\n label={\n <>\n <Price\n amount={method.amount.value}\n currency={method.amount.currency}\n />\n \n <span>{method.carrier.title}</span>\n </>\n }\n />\n );\n }\n\n return (\n <ToggleButton\n {...commonProps}\n data-testid=\"shipping-method-toggleButton\"\n label={\n <>\n <span>{method.carrier.title}</span>\n <Price\n amount={method.amount.value}\n currency={method.amount.currency}\n />\n </>\n }\n selected={selection?.value === method.value}\n />\n );\n };\n\n return (\n <div\n {...props}\n className={classes(['checkout-shipping-methods', className])}\n data-testid=\"checkout-shipping-methods\"\n >\n {title && (\n <VComponent className=\"checkout-shipping-methods__title\" node={title} />\n )}\n\n <div className={classes(['checkout-shipping-methods__content'])}>\n <div\n className={classes([\n 'checkout-shipping-methods__options',\n ['checkout-shipping-methods__options--busy', busy],\n [\n 'checkout-shipping-methods__options--toggleButton',\n UIComponentType === 'ToggleButton',\n ],\n ])}\n data-testid=\"checkout-shipping-methods-options\"\n >\n {options.length === 0 ? (\n <IllustratedMessage\n data-testid=\"checkout-shipping-methods-empty\"\n icon={<Icon source={Delivery} />}\n message={<p>{translations.EmptyState}</p>}\n />\n ) : (\n options.map((method: ShippingMethod) =>\n renderShippingMethod(method, UIComponentType)\n )\n )}\n </div>\n </div>\n\n {hasError && (\n <div\n ref={errorRef}\n className=\"checkout-shipping-methods__error\"\n data-testid=\"checkout-shipping-methods-alert\"\n >\n <InLineAlert\n heading={error}\n type=\"error\"\n variant=\"primary\"\n onDismiss={onDismissError}\n />\n </div>\n )}\n </div>\n );\n};\n\nexport const ShippingMethods = WithConditionals(\n ShippingMethodsComponent,\n ShippingMethodsSkeleton\n);\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { config, setShippingMethods } from '@/checkout/api';\nimport { ShippingMethods as ShippingMethodsComponent } from '@/checkout/components/ShippingMethods';\nimport {\n Cart,\n NegotiableQuote,\n ShippingEstimate,\n ShippingMethod,\n ShippingMethodInput,\n} from '@/checkout/data/models';\nimport { transformShippingEstimateShippingMethod } from '@/checkout/data/transforms';\nimport {\n getLatestCheckoutUpdate,\n getValue,\n hasPendingShippingEstimate,\n hasPendingUpdates,\n hasShippingAddress,\n isQuoteCheckout,\n notifyValues,\n} from '@/checkout/lib';\nimport { Filter, TitleProps, UIComponentType } from '@/checkout/types';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { Container, Slot } from '@adobe-commerce/elsie/lib';\nimport { events } from '@adobe-commerce/event-bus';\nimport { HTMLAttributes } from 'preact/compat';\nimport {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'preact/hooks';\n\ninterface CartSyncError {\n method: ShippingMethod;\n error: Error;\n}\n\nexport type ShippingOptionsFilter = Filter<ShippingMethod>;\n\nexport interface ShippingMethodsProps\n extends HTMLAttributes<HTMLDivElement>,\n TitleProps {\n UIComponentType?: UIComponentType;\n active?: boolean;\n autoSync?: boolean;\n onCartSyncError?: (error: CartSyncError) => void;\n onSelectionChange?: (method: ShippingMethod) => void;\n}\n\nfunction isMethodAvailable(\n method: ShippingMethod | null,\n options: ShippingMethod[]\n) {\n if (!method) return false;\n return options.some((option) => isEqual(option, method));\n}\n\nfunction isEqual(a: ShippingMethod | null, b: ShippingMethod | null) {\n if (!a || !b) return false;\n if (a.amount.value !== b.amount.value) return false;\n return a.code === b.code && a.carrier.code === b.carrier.code;\n}\n\nexport function emitShippingEstimateEvent(selection: ShippingMethod) {\n const shippingEstimatedEvent = events.lastPayload('shipping/estimate');\n\n if (!shippingEstimatedEvent) return;\n\n events.emit('shipping/estimate', {\n ...shippingEstimatedEvent,\n shippingMethod: transformShippingEstimateShippingMethod(selection),\n });\n}\n\nexport const ShippingMethods: Container<ShippingMethodsProps> = ({\n UIComponentType = 'RadioButton',\n active = true,\n autoSync = true,\n displayTitle = true,\n initialData,\n slots,\n onCartSyncError,\n onSelectionChange,\n ...props\n}) => {\n const [error, setError] = useState<string | null>(null);\n const [isVirtual, setIsVirtual] = useState(false);\n const [options, setOptions] = useState<ShippingMethod[] | undefined>();\n const [selection, setSelection] = useState<ShippingMethod | null>(null);\n const initialQuoteOptions = useRef<ShippingMethod[] | null>(null);\n\n const hasQueuedUpdates = hasPendingUpdates.value;\n const hasPendingEstimations = hasPendingShippingEstimate.value;\n\n const { cartSyncError, defaultTitle } = useText({\n cartSyncError: 'Checkout.ShippingMethods.cartSyncError',\n defaultTitle: 'Checkout.ShippingMethods.title',\n });\n\n const filterOptions = useCallback(\n (shippingMethods: ShippingMethod[] | undefined) => {\n if (!shippingMethods || shippingMethods.length === 0) return [];\n const { shipping } = config.getConfig();\n if (!shipping?.filterOptions) return shippingMethods;\n return shippingMethods.filter(shipping.filterOptions);\n },\n []\n );\n\n const preselectOption = useCallback((shippingMethods: ShippingMethod[]) => {\n if (shippingMethods.length === 0) return null;\n const { defaults } = config.getConfig();\n return defaults!.selectedShippingMethod!(shippingMethods);\n }, []);\n\n const filteredOptions = useMemo(() => {\n return filterOptions(options);\n }, [options, filterOptions]);\n\n const handleDismissError = useCallback(() => {\n setError(null);\n }, []);\n\n const setUserSelection = useCallback(\n (shippingMethod: ShippingMethod | null) => {\n setError(null);\n setSelection((prev) => {\n if (isEqual(prev, shippingMethod)) return prev;\n notifyValues({ selectedShippingMethod: shippingMethod });\n return shippingMethod;\n });\n },\n []\n );\n\n const setUserSelectionOnCart = useCallback(\n async (selection: ShippingMethod, fallback?: ShippingMethod | null) => {\n if (!autoSync || !hasShippingAddress()) return;\n\n const shippingMethodInput: ShippingMethodInput = {\n carrierCode: selection.carrier.code,\n methodCode: selection.code,\n };\n\n setShippingMethods([shippingMethodInput]).catch((error) => {\n setUserSelection(fallback ?? null);\n onCartSyncError?.({ method: selection, error });\n\n if (!onCartSyncError) {\n setError(cartSyncError);\n }\n });\n },\n [autoSync, setUserSelection, onCartSyncError, cartSyncError]\n );\n\n const handleSelectionChange = useCallback(\n async (selection: ShippingMethod) => {\n const prevSelection = getValue('selectedShippingMethod');\n\n setUserSelection(selection);\n onSelectionChange?.(selection);\n\n if (!hasShippingAddress()) {\n emitShippingEstimateEvent(selection);\n }\n\n await setUserSelectionOnCart(selection, prevSelection);\n },\n [onSelectionChange, setUserSelection, setUserSelectionOnCart]\n );\n\n const handleCheckoutData = useCallback(\n (data: Cart | NegotiableQuote | null) => {\n const isEmptyCart = !data || data.isEmpty;\n const isVirtualCart = Boolean(data?.isVirtual);\n\n if (isEmptyCart || isVirtualCart) {\n setIsVirtual(isVirtualCart);\n setUserSelection(null);\n setOptions([]);\n return;\n }\n\n const primaryAddress = data!.shippingAddresses?.[0];\n\n // If there is no primary address, options are handled by the shipping estimation\n if (!primaryAddress) return;\n\n const availableOptions = primaryAddress.availableShippingMethods ?? [];\n\n // For quote checkouts, preserve initial shipping methods. After the first method is selected,\n // the backend only returns that selected method, preventing users from changing to other\n // options. We maintain all initial options to match Luma's behavior.\n if (isQuoteCheckout() && !initialQuoteOptions.current) {\n initialQuoteOptions.current = availableOptions;\n }\n\n const effectiveOptions =\n isQuoteCheckout() && initialQuoteOptions.current\n ? initialQuoteOptions.current\n : availableOptions;\n\n setOptions(effectiveOptions);\n const filteredOptions = filterOptions(effectiveOptions);\n\n // If there are no filtered options, reset the user selection\n if (filteredOptions.length === 0) {\n setUserSelection(null);\n return;\n }\n\n const cartSelection = primaryAddress.selectedShippingMethod ?? null;\n\n const userSelection = getValue('selectedShippingMethod');\n const isAvailable = isMethodAvailable(userSelection, filteredOptions);\n const haveSameSelection = isEqual(userSelection, cartSelection);\n\n // Handle user selection that's available but different from cart\n if (userSelection && isAvailable && !haveSameSelection) {\n setUserSelectionOnCart(userSelection, cartSelection);\n return;\n }\n\n // If no user selection or not available, decide what to do based on cart and filtered options\n if ((!userSelection || !isAvailable) && cartSelection) {\n // Check if cart selection is still available after filtering\n const isCartSelectionAvailable = isMethodAvailable(\n cartSelection,\n filteredOptions\n );\n if (isCartSelectionAvailable) {\n setUserSelection(cartSelection);\n return;\n }\n }\n\n if (\n (!userSelection || !isAvailable) &&\n (!cartSelection || !isMethodAvailable(cartSelection, filteredOptions))\n ) {\n const newSelection = preselectOption(filteredOptions);\n setUserSelection(newSelection);\n if (newSelection) setUserSelectionOnCart(newSelection);\n }\n },\n [filterOptions, preselectOption, setUserSelection, setUserSelectionOnCart]\n );\n\n const handleShippingEstimate = useCallback(\n (estimation: ShippingEstimate | undefined) => {\n if (estimation === undefined) return;\n\n const { shippingMethod, availableShippingMethods } = estimation;\n\n const selectedShippingMethod =\n availableShippingMethods?.find(\n (method) =>\n method.code === shippingMethod?.methodCode &&\n method.carrier.code === shippingMethod?.carrierCode\n ) ?? null;\n\n setOptions(availableShippingMethods);\n setUserSelection(selectedShippingMethod);\n },\n [setUserSelection]\n );\n\n useEffect(() => {\n if (!active) return;\n\n const pastUpdate = getLatestCheckoutUpdate();\n\n if (pastUpdate) {\n // When component becomes active, restore key state so handleCheckoutData can work properly\n const userSelection = getValue('selectedShippingMethod');\n if (userSelection) {\n setSelection(userSelection);\n }\n\n handleCheckoutData(pastUpdate);\n return;\n }\n\n const onCheckoutInit = events.on(\n 'checkout/initialized',\n handleCheckoutData,\n { eager: true }\n );\n\n return () => {\n onCheckoutInit?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n if (!active) return;\n\n const onCheckoutUpdated = events.on(\n 'checkout/updated',\n handleCheckoutData,\n { eager: false }\n );\n\n return () => {\n onCheckoutUpdated?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n if (!active || hasShippingAddress()) return;\n\n const onShippingEstimate = events.on(\n 'shipping/estimate',\n handleShippingEstimate,\n { eager: true }\n );\n\n return () => {\n onShippingEstimate?.off();\n };\n }, [active, handleShippingEstimate]);\n\n const titleContent = useMemo(() => {\n if (!displayTitle) return undefined;\n\n return (\n <Slot name=\"checkout-shipping-methods-title\" slot={slots?.Title}>\n <h3>{defaultTitle}</h3>\n </Slot>\n );\n }, [displayTitle, slots?.Title, defaultTitle]);\n\n return (\n <ShippingMethodsComponent\n {...props}\n UIComponentType={UIComponentType}\n busy={hasQueuedUpdates || hasPendingEstimations}\n error={error}\n initialized={options !== undefined}\n options={filteredOptions}\n selection={selection}\n title={titleContent}\n visible={active && !isVirtual}\n onDismissError={handleDismissError}\n onSelectionChange={handleSelectionChange}\n />\n );\n};\n"],"names":["SvgDelivery","props","React","ShippingMethodsSkeleton","jsxs","Skeleton","jsx","SkeletonRow","ShippingMethodsComponent","className","busy","onSelectionChange","options","selection","title","UIComponentType","error","onDismissError","translations","useText","hasError","errorRef","useRef","useEffect","scrollToElement","renderShippingMethod","method","type","commonProps","RadioButton","Fragment","Price","ToggleButton","classes","VComponent","IllustratedMessage","Icon","Delivery","InLineAlert","ShippingMethods","WithConditionals","isMethodAvailable","option","isEqual","a","b","emitShippingEstimateEvent","shippingEstimatedEvent","events","transformShippingEstimateShippingMethod","active","autoSync","displayTitle","initialData","slots","onCartSyncError","setError","useState","isVirtual","setIsVirtual","setOptions","setSelection","initialQuoteOptions","hasQueuedUpdates","hasPendingUpdates","hasPendingEstimations","hasPendingShippingEstimate","cartSyncError","defaultTitle","filterOptions","useCallback","shippingMethods","shipping","config","preselectOption","defaults","filteredOptions","useMemo","handleDismissError","setUserSelection","shippingMethod","prev","notifyValues","setUserSelectionOnCart","fallback","hasShippingAddress","shippingMethodInput","setShippingMethods","handleSelectionChange","prevSelection","getValue","handleCheckoutData","data","isEmptyCart","isVirtualCart","primaryAddress","_a","availableOptions","isQuoteCheckout","effectiveOptions","cartSelection","userSelection","isAvailable","haveSameSelection","newSelection","handleShippingEstimate","estimation","availableShippingMethods","selectedShippingMethod","pastUpdate","getLatestCheckoutUpdate","onCheckoutInit","onCheckoutUpdated","onShippingEstimate","titleContent","Slot"],"mappings":"qvCACA,MAAMA,GAAeC,GAA0BC,EAAM,cAAc,MAAO,CAAE,MAAO,GAAI,OAAQ,GAAI,QAAS,YAAa,KAAM,OAAQ,MAAO,6BAA8B,GAAGD,GAAyBC,EAAM,cAAc,OAAQ,CAAE,aAAc,qBAAsB,EAAG,oEAAqE,OAAQ,eAAgB,YAAa,EAAG,cAAe,QAAS,eAAgB,OAAS,CAAA,EAAmBA,EAAM,cAAc,OAAQ,CAAE,aAAc,qBAAsB,EAAG,2CAA4C,OAAQ,eAAgB,YAAa,EAAG,cAAe,QAAS,eAAgB,OAAO,CAAE,EAAmBA,EAAM,cAAc,OAAQ,CAAE,aAAc,qBAAsB,EAAG,iQAAkQ,OAAQ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MAAAA,EAAgB,KAClB,CAAA,EACC,CAAC7D,EAAQyC,CAAkB,CAAC,EAE/BpE,EAAU,IAAM,CACd,GAAI,CAAC2B,EAAQ,OAEb,MAAM8D,EAAoBhE,EAAO,GAC/B,mBACA2C,EACA,CAAE,MAAO,EAAM,CACjB,EAEA,MAAO,IAAM,CACXqB,GAAA,MAAAA,EAAmB,KACrB,CAAA,EACC,CAAC9D,EAAQyC,CAAkB,CAAC,EAE/BpE,EAAU,IAAM,CACV,GAAA,CAAC2B,GAAUmC,IAAsB,OAErC,MAAM4B,EAAqBjE,EAAO,GAChC,oBACAyD,EACA,CAAE,MAAO,EAAK,CAChB,EAEA,MAAO,IAAM,CACXQ,GAAA,MAAAA,EAAoB,KACtB,CAAA,EACC,CAAC/D,EAAQuD,CAAsB,CAAC,EAE7B,MAAAS,GAAerC,GAAQ,IAAM,CAC7B,GAACzB,EAGH,OAAA9C,EAAC6G,GAAK,CAAA,KAAK,kCAAkC,KAAM7D,GAAA,YAAAA,EAAO,MACxD,SAAAhD,EAAC,KAAI,CAAA,SAAA8D,CAAa,CAAA,EACpB,GAED,CAAChB,EAAcE,GAAA,YAAAA,EAAO,MAAOc,CAAY,CAAC,EAG3C,OAAA9D,EAACE,GAAA,CACE,GAAGP,EACJ,gBAAiBc,EACjB,KAAMgD,IAAoBE,GAC1B,MAAAjD,EACA,YAAaJ,IAAY,OACzB,QAASgE,GACT,UAAA/D,EACA,MAAOqG,GACP,QAAShE,GAAU,CAACQ,EACpB,eAAgBoB,GAChB,kBAAmBU,EAAA,CACrB,CAEJ","x_google_ignoreList":[0]}
|
package/data/models/cart.d.ts
CHANGED
package/data/models/quote.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { Address, PaymentMethod, ShippingAddress } from '.';
|
|
|
2
2
|
import { NegotiableQuoteStatus } from '../../__generated__/types';
|
|
3
3
|
|
|
4
4
|
export interface NegotiableQuote {
|
|
5
|
+
type: 'quote';
|
|
5
6
|
availablePaymentMethods?: PaymentMethod[];
|
|
6
7
|
billingAddress?: Address;
|
|
7
8
|
email?: string;
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name": "@dropins/storefront-checkout", "version": "2.2.0-
|
|
1
|
+
{"name": "@dropins/storefront-checkout", "version": "2.2.0-beta2", "@dropins/tools": "^1.6.0-beta2", "license": "SEE LICENSE IN LICENSE.md"}
|