@sentecacommerce-theme/lib 0.12.62 → 0.12.63
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/dist/cjs/contexts/CheckoutForm/index.js +1 -1
- package/dist/cjs/contexts/CheckoutForm/index.js.map +1 -1
- package/dist/cjs/hooks/useProduct/index.js +29 -1
- package/dist/cjs/hooks/useProduct/index.js.map +1 -1
- package/dist/cjs/hooks/useProduct/utils/index.js +21 -4
- package/dist/cjs/hooks/useProduct/utils/index.js.map +1 -1
- package/dist/esm/contexts/CheckoutForm/index.js +1 -1
- package/dist/esm/contexts/CheckoutForm/index.js.map +1 -1
- package/dist/esm/hooks/useProduct/index.js +26 -2
- package/dist/esm/hooks/useProduct/index.js.map +1 -1
- package/dist/esm/hooks/useProduct/utils/index.js +16 -2
- package/dist/esm/hooks/useProduct/utils/index.js.map +1 -1
- package/dist/types/hooks/useProduct/utils/index.d.ts +1 -0
- package/package.json +3 -3
@@ -72,7 +72,7 @@ function CheckoutFormContextProvider(_ref) {
|
|
72
72
|
_ref$requiredFieldsOn = _ref.requiredFieldsOnShippingStep,
|
73
73
|
requiredFieldsOnShippingStep = _ref$requiredFieldsOn === void 0 ? ['firstName', 'lastName', 'email', 'phoneNumber'] : _ref$requiredFieldsOn,
|
74
74
|
_ref$requiredFieldsOn2 = _ref.requiredFieldsOnBillingAddressStep,
|
75
|
-
requiredFieldsOnBillingAddressStep = _ref$requiredFieldsOn2 === void 0 ? ['
|
75
|
+
requiredFieldsOnBillingAddressStep = _ref$requiredFieldsOn2 === void 0 ? ['vatId', 'companyId', 'companyPerson', 'companyName'] : _ref$requiredFieldsOn2,
|
76
76
|
_ref$enableNoShipping = _ref.enableNoShippingMethodMode,
|
77
77
|
enableNoShippingMethodMode = _ref$enableNoShipping === void 0 ? false : _ref$enableNoShipping,
|
78
78
|
_ref$disablePaymentRe = _ref.disablePaymentRedirects,
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../../src/contexts/CheckoutForm/index.tsx"],"names":["CheckoutFormContext","CheckoutFormContextProvider","children","defaultStep","errorLabels","enableSavedAddressList","withPersistBeforePageLeave","shippingValidations","defaultShippingValidations","validateBillingAddress","genericBillingAddressValidation","enableSaveBillingAddress","enableSavedBillingAddressList","countryCode","enableSaveAddress","autofillShippingPersonalData","onSubmit","paymentEnabledOnStep","getPaymentMethodsWhenShippingMethodIsSelected","shippingEnabledOnStep","billingEnabledOnStep","customState","initialCustomState","redirectTimeout","onBeforeRedirect","onSuccess","onError","isBoricaInDevMode","withPixelMeta","requiredFieldsOnShippingStep","requiredFieldsOnBillingAddressStep","enableNoShippingMethodMode","disablePaymentRedirects","orderQuery","myCartApi","useGet","boricaData","setBoricaData","step","setStep","isRedirecting","setIsRedirecting","fieldsWithError","serverErrors","setServerErrors","collectFieldsWithError","error","push","handleStepChange","newStep","window","scrollTo","updateServerErrors","errors","formattedErrors","reduce","data","code","response","internalError","isAuthenticated","isShippingEnabled","userQuery","usersApi","enabled","shippingState","Boolean","validations","requiredFields","mod","getIsPaymentMethodsEnabled","moduleKey","moduleData","methodKey","paymentState","billingState","withSavedBillingAddressList","requiredFieldsOnShipping","onBeforeBoricaRedirect","setTimeout","onBeforePaypalRedirect","location","replace","redirectUrl","withMeta","handleCheckoutSubmit","scrollToFirstError","interval","setInterval","errorElement","top","clearInterval","handleSubmit","e","preventDefault","Promise","all","persistShippingAddress","persistBillingAddress","isShippingValid","isValid","setIsShippingSubmitting","updateIsSubmitting","isBillingValid","setIsBillingSubmitting","isPaymentValid","setIsPaymentSubmitting","updateStep","saveOrder","shippingAddress","state","errorRef","errorFields","CheckoutFormStepsEnum","useCheckoutFormStep","context","Error","currentStep","useCheckoutFormOrder","useCheckoutFormErrorLabels","useCheckoutFormServerErrors","useCheckoutFormBillingState","useCheckoutFormShippingState","useCheckoutErrorFields","useCheckoutFormPaymentState"],"mappings":";;;;;;;;;;;;;;;;AAAA;;AAcA;;AACA;;AAQA;;AACA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B;;AAEA,MAAI,CAACmH,OAAL,EAAc;AACZ,UAAM,IAAIC,KAAJ,CACJ,gFADI,CAAN;AAGD;;AAED,SAAOD,OAAO,CAAClD,aAAf;AACD,CAVM;;;;AAYA,IAAM0D,sBAAsB,GAAG,SAAzBA,sBAAyB,GAAM;AAC1C,MAAMR,OAAO,GAAG,uBAAWnH,mBAAX,CAAhB;;AAEA,MAAI,CAACmH,OAAL,EAAc;AACZ,UAAM,IAAIC,KAAJ,CACJ,0EADI,CAAN;AAGD;;AAED,SAAO;AACLJ,IAAAA,WAAW,EAAEG,OAAO,CAACH,WADhB;AAELD,IAAAA,QAAQ,EAAEI,OAAO,CAACJ;AAFb,GAAP;AAID,CAbM;;;;AAeA,IAAMa,2BAA2B,GAAG,SAA9BA,2BAA8B,GAAM;AAC/C,MAAMT,OAAO,GAAG,uBAAWnH,mBAAX,CAAhB;;AAEA,MAAI,CAACmH,OAAL,EAAc;AACZ,UAAM,IAAIC,KAAJ,CACJ,+EADI,CAAN;AAGD;;AAED,SAAOD,OAAO,CAACzC,YAAf;AACD,CAVM","sourcesContent":["import React, {\n createContext,\n useCallback,\n useContext,\n useMemo,\n useState,\n} from 'react'\nimport {\n BoricaGeneratePaymentDataResponse,\n OrderDTO,\n AddressDTO,\n PaypalGeneratePaymentUrlResponseDTO,\n} from '@sentecacommerce/sdk'\nimport { MutateFunction, QueryResult } from 'react-query'\nimport { myCartApi } from '../../api/myCartApi'\nimport {\n useBilling,\n UseBillingResultType,\n usePayment,\n UsePaymentResultType,\n useShipping,\n UseShippingResultType,\n} from './hooks'\nimport { useIsAuthenticated } from '../../user/hooks'\nimport { useCheckoutSubmit } from '../../hooks/useCheckoutSubmit'\n\nimport {\n ShippingValidationsType,\n defaultShippingValidations,\n genericBillingAddressValidation,\n BillingAddressValidationType,\n} from './utils'\nimport { usersApi } from '../../api/usersApi'\nimport { useCheckoutShippingModule } from '../../hooks/useCheckoutShippingModule'\nimport { CheckoutFormCustomStateProvider, BoricaRedirect } from './Components'\nimport { useScrollTo } from '../../hooks/ui-hooks'\nimport { getElementOffset } from '../../utils/getElementOffset'\n\nexport const CheckoutFormContext = createContext<CheckoutFormContextType>(\n {} as any\n)\n\nexport type CheckoutCustomState = {}\n\nexport function CheckoutFormContextProvider({\n children,\n defaultStep,\n errorLabels,\n enableSavedAddressList,\n withPersistBeforePageLeave,\n shippingValidations = defaultShippingValidations,\n validateBillingAddress = genericBillingAddressValidation,\n enableSaveBillingAddress,\n enableSavedBillingAddressList,\n countryCode,\n enableSaveAddress,\n autofillShippingPersonalData,\n onSubmit,\n\n paymentEnabledOnStep,\n getPaymentMethodsWhenShippingMethodIsSelected,\n shippingEnabledOnStep,\n billingEnabledOnStep,\n\n customState: initialCustomState = {},\n redirectTimeout = 420,\n onBeforeRedirect,\n onSuccess,\n onError,\n isBoricaInDevMode,\n withPixelMeta = false,\n requiredFieldsOnShippingStep = [\n 'firstName',\n 'lastName',\n 'email',\n 'phoneNumber',\n ],\n requiredFieldsOnBillingAddressStep = ['city', 'postalCode', 'streetName'],\n enableNoShippingMethodMode = false,\n disablePaymentRedirects = false,\n}: Props) {\n const orderQuery = myCartApi.useGet()\n const [\n boricaData,\n setBoricaData,\n ] = useState<BoricaGeneratePaymentDataResponse | null>(null)\n const [step, setStep] = useState<CheckoutFormStepsEnum>(defaultStep)\n const [isRedirecting, setIsRedirecting] = useState(false)\n\n const fieldsWithError: HTMLElement[] = []\n\n const [serverErrors, setServerErrors] = useState<ServerErrors>(null)\n\n const collectFieldsWithError = (error: HTMLElement) => {\n fieldsWithError.push(error)\n }\n\n const handleStepChange = useCallback((newStep: CheckoutFormStepsEnum) => {\n window.scrollTo(0, 0)\n\n setStep(newStep)\n }, [])\n\n const updateServerErrors = useCallback((errors: any[]) => {\n // Example Error\n // [{\n // code: \"OutOfStock\"\n // message: \"Some of the ordered line items are out of stock at the time of placing the order.\"\n // responses: {\n // availableQuantity: 1\n // sku: \"200000095849\"\n // status: \"unavailable\"\n // }\n // }]\n const formattedErrors = errors?.reduce?.(\n (data: ServerErrors, error: any) => {\n return {\n ...data,\n [error?.code || 'internal']: error?.response,\n }\n },\n {}\n )\n setServerErrors(formattedErrors || { internalError: errors })\n }, [])\n\n const { isAuthenticated } = useIsAuthenticated()\n\n const isShippingEnabled = shippingEnabledOnStep === step\n\n const userQuery = usersApi.useGet(\n {},\n { enabled: isShippingEnabled && autofillShippingPersonalData }\n )\n\n const shippingState = useShipping({\n errorLabels,\n orderQuery,\n enableSavedAddressList: Boolean(isAuthenticated && enableSavedAddressList),\n enableSaveAddress: Boolean(isAuthenticated && enableSaveAddress),\n withPersistBeforePageLeave: !isRedirecting && withPersistBeforePageLeave,\n validations: shippingValidations,\n autofillShippingPersonalData: Boolean(\n isAuthenticated && autofillShippingPersonalData\n ),\n userQuery,\n enabled: isShippingEnabled,\n countryCode,\n requiredFields: requiredFieldsOnShippingStep,\n enableNoShippingMethodMode,\n })\n const mod = useCheckoutShippingModule(orderQuery, !enableNoShippingMethodMode)\n\n const getIsPaymentMethodsEnabled = () => {\n if (paymentEnabledOnStep) {\n return paymentEnabledOnStep === step\n }\n\n if (\n !enableNoShippingMethodMode &&\n getPaymentMethodsWhenShippingMethodIsSelected\n ) {\n return Boolean(mod?.moduleKey && mod?.moduleData.methodKey)\n }\n\n return false\n }\n\n const paymentState = usePayment({\n errorLabels,\n orderQuery,\n enabled: getIsPaymentMethodsEnabled(),\n })\n\n const billingState = useBilling({\n errorLabels,\n orderQuery,\n validateBillingAddress,\n enableSaveBillingAddress: Boolean(\n isAuthenticated && enableSaveBillingAddress\n ),\n withSavedBillingAddressList: Boolean(\n isAuthenticated && enableSavedBillingAddressList\n ),\n withPersistBeforePageLeave: !isRedirecting && withPersistBeforePageLeave,\n countryCode,\n enabled: billingEnabledOnStep === step,\n requiredFields: requiredFieldsOnBillingAddressStep,\n requiredFieldsOnShipping: requiredFieldsOnShippingStep,\n })\n\n const onBeforeBoricaRedirect = (data: BoricaGeneratePaymentDataResponse) => {\n if (disablePaymentRedirects) return\n\n onBeforeRedirect?.()\n setIsRedirecting(true)\n setTimeout(() => {\n setBoricaData(data)\n }, redirectTimeout)\n }\n\n const onBeforePaypalRedirect = (\n data: PaypalGeneratePaymentUrlResponseDTO\n ) => {\n if (disablePaymentRedirects) return\n\n onBeforeRedirect?.()\n setIsRedirecting(true)\n setTimeout(() => {\n window.location.replace(data.redirectUrl)\n }, redirectTimeout)\n }\n const { handleCheckoutSubmit } = useCheckoutSubmit({\n onBeforeBoricaRedirect,\n onBeforePaypalRedirect,\n onSuccess,\n onError: (errors: any) => {\n updateServerErrors(errors)\n onError(errors)\n },\n withMeta: withPixelMeta,\n disablePaymentRedirects,\n })\n\n const { scrollTo } = useScrollTo(fieldsWithError[0], 0)\n\n const scrollToFirstError = () => {\n const interval = setInterval(() => {\n const errorElement = fieldsWithError[0]\n if (!errorElement) return\n\n scrollTo(getElementOffset(errorElement).top - 100)\n clearInterval(interval)\n }, 50)\n\n setTimeout(() => {\n clearInterval(interval)\n }, 1000)\n }\n\n const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {\n e.preventDefault()\n\n await Promise.all([\n shippingState.persistShippingAddress(),\n billingState.persistBillingAddress(),\n ]).catch(() => {})\n\n onSubmit({\n isShippingValid: shippingState.isValid,\n setIsShippingSubmitting: shippingState.updateIsSubmitting,\n isBillingValid: billingState.isValid,\n setIsBillingSubmitting: billingState.updateIsSubmitting,\n isPaymentValid: paymentState.isValid,\n setIsPaymentSubmitting: paymentState.updateIsSubmitting,\n step,\n updateStep: setStep,\n saveOrder: handleCheckoutSubmit,\n updateServerErrors,\n scrollToFirstError,\n shippingState,\n shippingAddress: shippingState.data,\n })\n }\n\n const state = {\n setStep: handleStepChange,\n step,\n orderQuery,\n serverErrors,\n updateServerErrors,\n errorLabels,\n shippingState,\n paymentState,\n billingState,\n errorRef: collectFieldsWithError,\n errorFields: fieldsWithError,\n }\n\n return (\n <CheckoutFormContext.Provider value={state}>\n <CheckoutFormCustomStateProvider initialCustomState={initialCustomState}>\n <>\n <form noValidate onSubmit={handleSubmit}>\n {children}\n </form>\n {!!boricaData && (\n <BoricaRedirect\n isInDevMode={isBoricaInDevMode}\n formData={boricaData}\n />\n )}\n </>\n </CheckoutFormCustomStateProvider>\n </CheckoutFormContext.Provider>\n )\n}\n\nexport type CheckoutFormOnSubmitData = {\n isShippingValid: boolean\n setIsShippingSubmitting: (value: boolean) => void\n isBillingValid: boolean\n setIsBillingSubmitting: (value: boolean) => void\n isPaymentValid: boolean\n setIsPaymentSubmitting: (value: boolean) => void\n step: CheckoutFormStepsEnum\n updateStep: (step: CheckoutFormStepsEnum) => void\n saveOrder: MutateFunction<OrderDTO, unknown, any, unknown>\n\n updateServerErrors: (errors: any) => void\n scrollToFirstError: () => void\n shippingState: UseShippingResultType\n shippingAddress?: AddressDTO\n}\n\ntype Props = {\n children: any\n defaultStep: CheckoutFormStepsEnum\n errorLabels: CheckoutFormErrorLabelsType\n withPersistBeforePageLeave: boolean\n countryCode: string\n onSubmit: (data: CheckoutFormOnSubmitData) => void\n onError: (error: any) => void\n onSuccess: (order: OrderDTO) => void\n\n redirectTimeout?: number\n onBeforeRedirect?: () => void\n\n customState?: CheckoutCustomState\n\n enableSavedAddressList: boolean\n shippingValidations?: ShippingValidationsType\n enableSaveAddress: boolean\n autofillShippingPersonalData: boolean\n autoSelectDefaultShippingAddress: boolean\n\n enableSaveBillingAddress: boolean\n validateBillingAddress?: BillingAddressValidationType\n enableSavedBillingAddressList: boolean\n autoSelectDefaultBillingAddress: boolean\n\n paymentEnabledOnStep?: CheckoutFormStepsEnum\n getPaymentMethodsWhenShippingMethodIsSelected?: boolean\n\n shippingEnabledOnStep: CheckoutFormStepsEnum\n\n billingEnabledOnStep: CheckoutFormStepsEnum\n\n isBoricaInDevMode?: boolean\n\n withPixelMeta?: boolean\n requiredFieldsOnShippingStep?: string[]\n requiredFieldsOnBillingAddressStep?: string[]\n enableNoShippingMethodMode?: boolean\n disablePaymentRedirects?: boolean\n}\n\ntype ServerErrors = { [key: string]: any } | null\n\nexport enum CheckoutFormStepsEnum {\n Basket = 'Basket',\n Shipping = 'Shipping',\n BillingAddress = 'BillingAddress',\n Payment = 'Payment',\n Preview = 'Preview',\n All = 'All',\n}\n\nexport type CheckoutFormErrorsResultType =\n | {\n [key: string]: string\n }\n | null\n | undefined\n\nexport type ShippingFormErrorLabels = {\n fieldIsRequired: string\n fillStreetNumberBuildingEntranceOrApartment: string\n streetIsRequired: string\n invalidPhoneNumber?: string\n quarterIsRequired: string\n cantFindStreetOrQuarterMessage: string\n cityIsRequired: string\n emailIsRequired: string\n officeIsRequired: string\n selectCourier: string\n noStoreSelected: string\n}\n\nexport type CheckoutFormErrorLabelsType = ShippingFormErrorLabels & {\n selectPaymentMethod: string\n}\n\nexport type CheckoutFormContextType = {\n setStep: (step: CheckoutFormStepsEnum) => void\n step: CheckoutFormStepsEnum\n serverErrors: ServerErrors\n updateServerErrors: (errors: any) => void\n errorRef: (error: HTMLElement) => void\n errorFields: HTMLElement[]\n errorLabels: CheckoutFormErrorLabelsType\n orderQuery: QueryResult<OrderDTO, unknown>\n shippingState: UseShippingResultType\n paymentState: UsePaymentResultType\n billingState: UseBillingResultType\n}\n\nexport const useCheckoutFormStep = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormStep must be used within a CheckoutFormContextProvider'\n )\n }\n\n return useMemo(() => {\n return {\n currentStep: context.step,\n updateStep: context.setStep,\n }\n }, [context])\n}\n\nexport const useCheckoutFormOrder = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormOrder must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.orderQuery\n}\n\nexport const useCheckoutFormErrorLabels = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormErrorLabels must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.errorLabels\n}\n\nexport const useCheckoutFormServerErrors = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormServerErrors must be used within a CheckoutFormContextProvider'\n )\n }\n\n return useMemo(() => {\n return {\n serverErrors: context.serverErrors,\n updateServerErrors: context.updateServerErrors,\n }\n }, [context])\n}\n\nexport const useCheckoutFormBillingState = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormBillingState must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.billingState\n}\n\nexport const useCheckoutFormShippingState = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormShippingState must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.shippingState\n}\n\nexport const useCheckoutErrorFields = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutErrorFields must be used within a CheckoutFormContextProvider'\n )\n }\n\n return {\n errorFields: context.errorFields,\n errorRef: context.errorRef,\n }\n}\n\nexport const useCheckoutFormPaymentState = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormPaymentState must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.paymentState\n}\n"],"file":"index.js"}
|
1
|
+
{"version":3,"sources":["../../../../src/contexts/CheckoutForm/index.tsx"],"names":["CheckoutFormContext","CheckoutFormContextProvider","children","defaultStep","errorLabels","enableSavedAddressList","withPersistBeforePageLeave","shippingValidations","defaultShippingValidations","validateBillingAddress","genericBillingAddressValidation","enableSaveBillingAddress","enableSavedBillingAddressList","countryCode","enableSaveAddress","autofillShippingPersonalData","onSubmit","paymentEnabledOnStep","getPaymentMethodsWhenShippingMethodIsSelected","shippingEnabledOnStep","billingEnabledOnStep","customState","initialCustomState","redirectTimeout","onBeforeRedirect","onSuccess","onError","isBoricaInDevMode","withPixelMeta","requiredFieldsOnShippingStep","requiredFieldsOnBillingAddressStep","enableNoShippingMethodMode","disablePaymentRedirects","orderQuery","myCartApi","useGet","boricaData","setBoricaData","step","setStep","isRedirecting","setIsRedirecting","fieldsWithError","serverErrors","setServerErrors","collectFieldsWithError","error","push","handleStepChange","newStep","window","scrollTo","updateServerErrors","errors","formattedErrors","reduce","data","code","response","internalError","isAuthenticated","isShippingEnabled","userQuery","usersApi","enabled","shippingState","Boolean","validations","requiredFields","mod","getIsPaymentMethodsEnabled","moduleKey","moduleData","methodKey","paymentState","billingState","withSavedBillingAddressList","requiredFieldsOnShipping","onBeforeBoricaRedirect","setTimeout","onBeforePaypalRedirect","location","replace","redirectUrl","withMeta","handleCheckoutSubmit","scrollToFirstError","interval","setInterval","errorElement","top","clearInterval","handleSubmit","e","preventDefault","Promise","all","persistShippingAddress","persistBillingAddress","isShippingValid","isValid","setIsShippingSubmitting","updateIsSubmitting","isBillingValid","setIsBillingSubmitting","isPaymentValid","setIsPaymentSubmitting","updateStep","saveOrder","shippingAddress","state","errorRef","errorFields","CheckoutFormStepsEnum","useCheckoutFormStep","context","Error","currentStep","useCheckoutFormOrder","useCheckoutFormErrorLabels","useCheckoutFormServerErrors","useCheckoutFormBillingState","useCheckoutFormShippingState","useCheckoutErrorFields","useCheckoutFormPaymentState"],"mappings":";;;;;;;;;;;;;;;;AAAA;;AAcA;;AACA;;AAQA;;AACA;;AAEA;;AAMA;;AACA;;AACA;;AACA;;AACA;;AAEO,IAAMA,mBAAmB,gBAAG,0BACjC,EADiC,CAA5B;;;AAMA,SAASC,2BAAT,OAyCG;AAAA,MAxCRC,QAwCQ,QAxCRA,QAwCQ;AAAA,MAvCRC,WAuCQ,QAvCRA,WAuCQ;AAAA,MAtCRC,WAsCQ,QAtCRA,WAsCQ;AAAA,MArCRC,sBAqCQ,QArCRA,sBAqCQ;AAAA,MApCRC,0BAoCQ,QApCRA,0BAoCQ;AAAA,mCAnCRC,mBAmCQ;AAAA,MAnCRA,mBAmCQ,sCAnCcC,iCAmCd;AAAA,mCAlCRC,sBAkCQ;AAAA,MAlCRA,sBAkCQ,sCAlCiBC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AO,CAACJ;AAFb,GAAP;AAID,CAbM;;;;AAeA,IAAMa,2BAA2B,GAAG,SAA9BA,2BAA8B,GAAM;AAC/C,MAAMT,OAAO,GAAG,uBAAWnH,mBAAX,CAAhB;;AAEA,MAAI,CAACmH,OAAL,EAAc;AACZ,UAAM,IAAIC,KAAJ,CACJ,+EADI,CAAN;AAGD;;AAED,SAAOD,OAAO,CAACzC,YAAf;AACD,CAVM","sourcesContent":["import React, {\n createContext,\n useCallback,\n useContext,\n useMemo,\n useState,\n} from 'react'\nimport {\n BoricaGeneratePaymentDataResponse,\n OrderDTO,\n AddressDTO,\n PaypalGeneratePaymentUrlResponseDTO,\n} from '@sentecacommerce/sdk'\nimport { MutateFunction, QueryResult } from 'react-query'\nimport { myCartApi } from '../../api/myCartApi'\nimport {\n useBilling,\n UseBillingResultType,\n usePayment,\n UsePaymentResultType,\n useShipping,\n UseShippingResultType,\n} from './hooks'\nimport { useIsAuthenticated } from '../../user/hooks'\nimport { useCheckoutSubmit } from '../../hooks/useCheckoutSubmit'\n\nimport {\n ShippingValidationsType,\n defaultShippingValidations,\n genericBillingAddressValidation,\n BillingAddressValidationType,\n} from './utils'\nimport { usersApi } from '../../api/usersApi'\nimport { useCheckoutShippingModule } from '../../hooks/useCheckoutShippingModule'\nimport { CheckoutFormCustomStateProvider, BoricaRedirect } from './Components'\nimport { useScrollTo } from '../../hooks/ui-hooks'\nimport { getElementOffset } from '../../utils/getElementOffset'\n\nexport const CheckoutFormContext = createContext<CheckoutFormContextType>(\n {} as any\n)\n\nexport type CheckoutCustomState = {}\n\nexport function CheckoutFormContextProvider({\n children,\n defaultStep,\n errorLabels,\n enableSavedAddressList,\n withPersistBeforePageLeave,\n shippingValidations = defaultShippingValidations,\n validateBillingAddress = genericBillingAddressValidation,\n enableSaveBillingAddress,\n enableSavedBillingAddressList,\n countryCode,\n enableSaveAddress,\n autofillShippingPersonalData,\n onSubmit,\n\n paymentEnabledOnStep,\n getPaymentMethodsWhenShippingMethodIsSelected,\n shippingEnabledOnStep,\n billingEnabledOnStep,\n\n customState: initialCustomState = {},\n redirectTimeout = 420,\n onBeforeRedirect,\n onSuccess,\n onError,\n isBoricaInDevMode,\n withPixelMeta = false,\n requiredFieldsOnShippingStep = [\n 'firstName',\n 'lastName',\n 'email',\n 'phoneNumber',\n ],\n requiredFieldsOnBillingAddressStep = [\n 'vatId',\n 'companyId',\n 'companyPerson',\n 'companyName',\n ],\n enableNoShippingMethodMode = false,\n disablePaymentRedirects = false,\n}: Props) {\n const orderQuery = myCartApi.useGet()\n const [\n boricaData,\n setBoricaData,\n ] = useState<BoricaGeneratePaymentDataResponse | null>(null)\n const [step, setStep] = useState<CheckoutFormStepsEnum>(defaultStep)\n const [isRedirecting, setIsRedirecting] = useState(false)\n\n const fieldsWithError: HTMLElement[] = []\n\n const [serverErrors, setServerErrors] = useState<ServerErrors>(null)\n\n const collectFieldsWithError = (error: HTMLElement) => {\n fieldsWithError.push(error)\n }\n\n const handleStepChange = useCallback((newStep: CheckoutFormStepsEnum) => {\n window.scrollTo(0, 0)\n\n setStep(newStep)\n }, [])\n\n const updateServerErrors = useCallback((errors: any[]) => {\n // Example Error\n // [{\n // code: \"OutOfStock\"\n // message: \"Some of the ordered line items are out of stock at the time of placing the order.\"\n // responses: {\n // availableQuantity: 1\n // sku: \"200000095849\"\n // status: \"unavailable\"\n // }\n // }]\n const formattedErrors = errors?.reduce?.(\n (data: ServerErrors, error: any) => {\n return {\n ...data,\n [error?.code || 'internal']: error?.response,\n }\n },\n {}\n )\n setServerErrors(formattedErrors || { internalError: errors })\n }, [])\n\n const { isAuthenticated } = useIsAuthenticated()\n\n const isShippingEnabled = shippingEnabledOnStep === step\n\n const userQuery = usersApi.useGet(\n {},\n { enabled: isShippingEnabled && autofillShippingPersonalData }\n )\n\n const shippingState = useShipping({\n errorLabels,\n orderQuery,\n enableSavedAddressList: Boolean(isAuthenticated && enableSavedAddressList),\n enableSaveAddress: Boolean(isAuthenticated && enableSaveAddress),\n withPersistBeforePageLeave: !isRedirecting && withPersistBeforePageLeave,\n validations: shippingValidations,\n autofillShippingPersonalData: Boolean(\n isAuthenticated && autofillShippingPersonalData\n ),\n userQuery,\n enabled: isShippingEnabled,\n countryCode,\n requiredFields: requiredFieldsOnShippingStep,\n enableNoShippingMethodMode,\n })\n const mod = useCheckoutShippingModule(orderQuery, !enableNoShippingMethodMode)\n\n const getIsPaymentMethodsEnabled = () => {\n if (paymentEnabledOnStep) {\n return paymentEnabledOnStep === step\n }\n\n if (\n !enableNoShippingMethodMode &&\n getPaymentMethodsWhenShippingMethodIsSelected\n ) {\n return Boolean(mod?.moduleKey && mod?.moduleData.methodKey)\n }\n\n return false\n }\n\n const paymentState = usePayment({\n errorLabels,\n orderQuery,\n enabled: getIsPaymentMethodsEnabled(),\n })\n\n const billingState = useBilling({\n errorLabels,\n orderQuery,\n validateBillingAddress,\n enableSaveBillingAddress: Boolean(\n isAuthenticated && enableSaveBillingAddress\n ),\n withSavedBillingAddressList: Boolean(\n isAuthenticated && enableSavedBillingAddressList\n ),\n withPersistBeforePageLeave: !isRedirecting && withPersistBeforePageLeave,\n countryCode,\n enabled: billingEnabledOnStep === step,\n requiredFields: requiredFieldsOnBillingAddressStep,\n requiredFieldsOnShipping: requiredFieldsOnShippingStep,\n })\n\n const onBeforeBoricaRedirect = (data: BoricaGeneratePaymentDataResponse) => {\n if (disablePaymentRedirects) return\n\n onBeforeRedirect?.()\n setIsRedirecting(true)\n setTimeout(() => {\n setBoricaData(data)\n }, redirectTimeout)\n }\n\n const onBeforePaypalRedirect = (\n data: PaypalGeneratePaymentUrlResponseDTO\n ) => {\n if (disablePaymentRedirects) return\n\n onBeforeRedirect?.()\n setIsRedirecting(true)\n setTimeout(() => {\n window.location.replace(data.redirectUrl)\n }, redirectTimeout)\n }\n const { handleCheckoutSubmit } = useCheckoutSubmit({\n onBeforeBoricaRedirect,\n onBeforePaypalRedirect,\n onSuccess,\n onError: (errors: any) => {\n updateServerErrors(errors)\n onError(errors)\n },\n withMeta: withPixelMeta,\n disablePaymentRedirects,\n })\n\n const { scrollTo } = useScrollTo(fieldsWithError[0], 0)\n\n const scrollToFirstError = () => {\n const interval = setInterval(() => {\n const errorElement = fieldsWithError[0]\n if (!errorElement) return\n\n scrollTo(getElementOffset(errorElement).top - 100)\n clearInterval(interval)\n }, 50)\n\n setTimeout(() => {\n clearInterval(interval)\n }, 1000)\n }\n\n const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {\n e.preventDefault()\n\n await Promise.all([\n shippingState.persistShippingAddress(),\n billingState.persistBillingAddress(),\n ]).catch(() => {})\n\n onSubmit({\n isShippingValid: shippingState.isValid,\n setIsShippingSubmitting: shippingState.updateIsSubmitting,\n isBillingValid: billingState.isValid,\n setIsBillingSubmitting: billingState.updateIsSubmitting,\n isPaymentValid: paymentState.isValid,\n setIsPaymentSubmitting: paymentState.updateIsSubmitting,\n step,\n updateStep: setStep,\n saveOrder: handleCheckoutSubmit,\n updateServerErrors,\n scrollToFirstError,\n shippingState,\n shippingAddress: shippingState.data,\n })\n }\n\n const state = {\n setStep: handleStepChange,\n step,\n orderQuery,\n serverErrors,\n updateServerErrors,\n errorLabels,\n shippingState,\n paymentState,\n billingState,\n errorRef: collectFieldsWithError,\n errorFields: fieldsWithError,\n }\n\n return (\n <CheckoutFormContext.Provider value={state}>\n <CheckoutFormCustomStateProvider initialCustomState={initialCustomState}>\n <>\n <form noValidate onSubmit={handleSubmit}>\n {children}\n </form>\n {!!boricaData && (\n <BoricaRedirect\n isInDevMode={isBoricaInDevMode}\n formData={boricaData}\n />\n )}\n </>\n </CheckoutFormCustomStateProvider>\n </CheckoutFormContext.Provider>\n )\n}\n\nexport type CheckoutFormOnSubmitData = {\n isShippingValid: boolean\n setIsShippingSubmitting: (value: boolean) => void\n isBillingValid: boolean\n setIsBillingSubmitting: (value: boolean) => void\n isPaymentValid: boolean\n setIsPaymentSubmitting: (value: boolean) => void\n step: CheckoutFormStepsEnum\n updateStep: (step: CheckoutFormStepsEnum) => void\n saveOrder: MutateFunction<OrderDTO, unknown, any, unknown>\n\n updateServerErrors: (errors: any) => void\n scrollToFirstError: () => void\n shippingState: UseShippingResultType\n shippingAddress?: AddressDTO\n}\n\ntype Props = {\n children: any\n defaultStep: CheckoutFormStepsEnum\n errorLabels: CheckoutFormErrorLabelsType\n withPersistBeforePageLeave: boolean\n countryCode: string\n onSubmit: (data: CheckoutFormOnSubmitData) => void\n onError: (error: any) => void\n onSuccess: (order: OrderDTO) => void\n\n redirectTimeout?: number\n onBeforeRedirect?: () => void\n\n customState?: CheckoutCustomState\n\n enableSavedAddressList: boolean\n shippingValidations?: ShippingValidationsType\n enableSaveAddress: boolean\n autofillShippingPersonalData: boolean\n autoSelectDefaultShippingAddress: boolean\n\n enableSaveBillingAddress: boolean\n validateBillingAddress?: BillingAddressValidationType\n enableSavedBillingAddressList: boolean\n autoSelectDefaultBillingAddress: boolean\n\n paymentEnabledOnStep?: CheckoutFormStepsEnum\n getPaymentMethodsWhenShippingMethodIsSelected?: boolean\n\n shippingEnabledOnStep: CheckoutFormStepsEnum\n\n billingEnabledOnStep: CheckoutFormStepsEnum\n\n isBoricaInDevMode?: boolean\n\n withPixelMeta?: boolean\n requiredFieldsOnShippingStep?: string[]\n requiredFieldsOnBillingAddressStep?: string[]\n enableNoShippingMethodMode?: boolean\n disablePaymentRedirects?: boolean\n}\n\ntype ServerErrors = { [key: string]: any } | null\n\nexport enum CheckoutFormStepsEnum {\n Basket = 'Basket',\n Shipping = 'Shipping',\n BillingAddress = 'BillingAddress',\n Payment = 'Payment',\n Preview = 'Preview',\n All = 'All',\n}\n\nexport type CheckoutFormErrorsResultType =\n | {\n [key: string]: string\n }\n | null\n | undefined\n\nexport type ShippingFormErrorLabels = {\n fieldIsRequired: string\n fillStreetNumberBuildingEntranceOrApartment: string\n streetIsRequired: string\n invalidPhoneNumber?: string\n quarterIsRequired: string\n cantFindStreetOrQuarterMessage: string\n cityIsRequired: string\n emailIsRequired: string\n officeIsRequired: string\n selectCourier: string\n noStoreSelected: string\n}\n\nexport type CheckoutFormErrorLabelsType = ShippingFormErrorLabels & {\n selectPaymentMethod: string\n}\n\nexport type CheckoutFormContextType = {\n setStep: (step: CheckoutFormStepsEnum) => void\n step: CheckoutFormStepsEnum\n serverErrors: ServerErrors\n updateServerErrors: (errors: any) => void\n errorRef: (error: HTMLElement) => void\n errorFields: HTMLElement[]\n errorLabels: CheckoutFormErrorLabelsType\n orderQuery: QueryResult<OrderDTO, unknown>\n shippingState: UseShippingResultType\n paymentState: UsePaymentResultType\n billingState: UseBillingResultType\n}\n\nexport const useCheckoutFormStep = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormStep must be used within a CheckoutFormContextProvider'\n )\n }\n\n return useMemo(() => {\n return {\n currentStep: context.step,\n updateStep: context.setStep,\n }\n }, [context])\n}\n\nexport const useCheckoutFormOrder = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormOrder must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.orderQuery\n}\n\nexport const useCheckoutFormErrorLabels = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormErrorLabels must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.errorLabels\n}\n\nexport const useCheckoutFormServerErrors = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormServerErrors must be used within a CheckoutFormContextProvider'\n )\n }\n\n return useMemo(() => {\n return {\n serverErrors: context.serverErrors,\n updateServerErrors: context.updateServerErrors,\n }\n }, [context])\n}\n\nexport const useCheckoutFormBillingState = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormBillingState must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.billingState\n}\n\nexport const useCheckoutFormShippingState = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormShippingState must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.shippingState\n}\n\nexport const useCheckoutErrorFields = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutErrorFields must be used within a CheckoutFormContextProvider'\n )\n }\n\n return {\n errorFields: context.errorFields,\n errorRef: context.errorRef,\n }\n}\n\nexport const useCheckoutFormPaymentState = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormPaymentState must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.paymentState\n}\n"],"file":"index.js"}
|
@@ -188,11 +188,37 @@ function ProductProvider(_ref) {
|
|
188
188
|
function selectVariantByAttribute(key) {
|
189
189
|
var _combinations$key;
|
190
190
|
|
191
|
+
// Get by collapseKey for SD
|
192
|
+
var split = key.split(':');
|
193
|
+
|
194
|
+
if (split[0] === 'collapseKey') {
|
195
|
+
var _id = Object.keys(variants).find(function (el) {
|
196
|
+
return variants[el].collapseKey === split[1];
|
197
|
+
});
|
198
|
+
|
199
|
+
return setSelectedVariant(variants[_id]);
|
200
|
+
}
|
201
|
+
|
191
202
|
var id = (_combinations$key = combinations[key]) == null ? void 0 : _combinations$key.value;
|
192
203
|
setSelectedVariant(variants[id]);
|
193
204
|
}
|
194
205
|
|
195
206
|
function selectVariantByCombination(key, value) {
|
207
|
+
// Take collapseKey for SD
|
208
|
+
var split = value.split(':');
|
209
|
+
|
210
|
+
if (split[0] === 'collapseKey') {
|
211
|
+
var _id2 = Object.keys(variants).find(function (el) {
|
212
|
+
var _variants$el$attribut;
|
213
|
+
|
214
|
+
return variants[el].collapseKey === split[1] && ((_variants$el$attribut = variants[el].attributes.find(function (attr) {
|
215
|
+
return attr.name === 'size';
|
216
|
+
})) == null ? void 0 : _variants$el$attribut.value) === key;
|
217
|
+
});
|
218
|
+
|
219
|
+
return setSelectedVariant(variants[_id2]);
|
220
|
+
}
|
221
|
+
|
196
222
|
var id = combinations[key].params[value];
|
197
223
|
setSelectedVariant(variants[id]);
|
198
224
|
}
|
@@ -258,12 +284,14 @@ function ProductProvider(_ref) {
|
|
258
284
|
return result;
|
259
285
|
}
|
260
286
|
|
287
|
+
var collapsedImages = (0, _utils.createCollapseKeyImagesMap)(product);
|
261
288
|
var state = {
|
262
289
|
metaData: metaData,
|
263
290
|
seoData: seoData,
|
264
291
|
variants: variants,
|
265
292
|
selectedVariant: selectedVariant,
|
266
|
-
attributeRules: attributeRules
|
293
|
+
attributeRules: attributeRules,
|
294
|
+
collapsedImages: collapsedImages
|
267
295
|
};
|
268
296
|
var functions = {
|
269
297
|
getVariantById: getVariantById,
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../../src/hooks/useProduct/index.tsx"],"names":["ProductStateContext","React","createContext","undefined","CountDispatchContext","ProductProvider","product","children","defaultVariantId","useState","mounted","setMounted","getCombinationsAndAttributeRules","combinations","attributeRules","setCombinationsAndAttributeRules","getVariantsWithInventory","variants","setVariants","getDefaultVariant","selectedVariant","setSelectedVariant","metaData","useMemo","rootCategory","categories","rootCategoryId","resourceId","metaObj","_id","name","slug","description","shortDescription","metaDescription","brand","brands","resource","logo","assets","sources","url","category","length","reviewRatingStatistics","content","Boolean","map","createProductContent","seoData","seoObj","title","metaTitle","keywords","metaKeywords","customFields","mappedFields","custom","useEffect","data","variantsWithInventory","reduce","_","index","arr","currentVariant","mappedAttributes","mappedOptions","availableOptions","isAvailable","inventorySnapshot","canOrder","updatedVariant","inventory","hasAvailableQuantity","availableQuantity","quantity","attributes","options","selectedOptions","labels","getAttribute","rule","getSelectedAttribute","getAttributeByKey","key","find","a","value","getAvailabilityByStore","availabilities","mappedAttributeRules","attributesWithId","Object","keys","variantId","combinationsMap","selectVariantById","id","selectVariantByAttribute","selectVariantByCombination","params","selectVariantOptions","definitionKey","optionKey","newSelectedVariant","filter","opt","mappedSelectedOptions","option","attributeRule","values","result","forEach","currentKey","found","getVariantById","getVariantByAttribute","getVariantByCombination","getCustomFieldValue","field","getCombinationsForAttributeRule","state","functions","getProductVideos","useProductState","context","useContext","Error","useProductFunctions","useProduct","config","productsApi"],"mappings":";;;;;;;;;;;;AAAA;;AACA;;;;AASA;;AACA;;AAeA;;AACA;;AA2LA,IAAMA,mBAAmB,gBAAGC,kBAAMC,aAAN,CAE1BC,SAF0B,CAA5B;;AAGA,IAAMC,oBAAoB,gBAAGH,kBAAMC,aAAN,CAE3BC,SAF2B,CAA7B;;AAIO,SAASE,eAAT,OAIkB;AAAA,MAHvBC,OAGuB,QAHvBA,OAGuB;AAAA,MAFvBC,QAEuB,QAFvBA,QAEuB;AAAA,MADvBC,gBACuB,QADvBA,gBACuB;;AAAA,wBACOP,kBAAMQ,QAAN,CAAe,KAAf,CADP;AAAA,MAChBC,OADgB;AAAA,MACPC,UADO;;AAAA,yBAMnBV,kBAAMQ,QAAN,CAGDG,gCAHC,CANmB;AAAA;AAAA,MAInBC,YAJmB,qBAInBA,YAJmB;AAAA,MAILC,cAJK,qBAILA,cAJK;AAAA,MAKrBC,gCALqB;;AAAA,yBAWSd,kBAAMQ,QAAN,CAC9BO,wBAD8B,CAXT;AAAA,MAWhBC,QAXgB;AAAA,MAWNC,WAXM;;AAAA,yBAkBnBjB,kBAAMQ,QAAN,CAAmCU,iBAAnC,CAlBmB;AAAA,MAgBrBC,eAhBqB;AAAA,MAiBrBC,kBAjBqB;;AAoBvB,MAAMC,QAAQ,GAAGrB,kBAAMsB,OAAN,CAAc,YAAM;AAAA;;AACnC,QAAMC,YAAY,GAAGlB,OAAH,2CAAGA,OAAO,CAAEmB,UAAZ,qBAAG,oBAAsB,CAAtB,CAArB;AACA,QAAMC,cAAc,GAAGF,YAAH,oBAAGA,YAAY,CAAEG,UAArC;AAEA,QAAMC,OAA4B,GAAG;AACnCC,MAAAA,GAAG,EAAEvB,OAAF,oBAAEA,OAAO,CAAEuB,GADqB;AAEnCC,MAAAA,IAAI,EACF,6BAAqBV,eAArB,oBAAqBA,eAAe,CAAEU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,+BAA+B,EAA/BA,+BAPgB;AAQhBnB,IAAAA,oBAAoB,EAApBA,oBARgB;AAShBiB,IAAAA,mBAAmB,EAAnBA,mBATgB;AAUhBK,IAAAA,gBAAgB,EAAE;AAAA,aAAM,6BAAiBtG,QAAQ,CAACiB,MAA1B,CAAN;AAAA;AAVF,GAAlB;AAaA,sBACE,gCAAC,mBAAD,CAAqB,QAArB;AAA8B,IAAA,KAAK,EAAEmF;AAArC,kBACE,gCAAC,oBAAD,CAAsB,QAAtB;AAA+B,IAAA,KAAK,EAAEC;AAAtC,KACGpH,QADH,CADF,CADF;AAOD;;AAEM,SAASsH,eAAT,GAA2B;AAChC,MAAMC,OAAO,GAAG7H,kBAAM8H,UAAN,CAAiB/H,mBAAjB,CAAhB;;AACA,MAAI8H,OAAO,KAAK3H,SAAhB,EAA2B;AACzB,UAAM,IAAI6H,KAAJ,CAAU,uDAAV,CAAN;AACD;;AACD,SAAOF,OAAP;AACD;;AACM,SAASG,mBAAT,GAA+B;AACpC,MAAMH,OAAO,GAAG7H,kBAAM8H,UAAN,CAAiB3H,oBAAjB,CAAhB;;AACA,MAAI0H,OAAO,KAAK3H,SAAhB,EAA2B;AACzB,UAAM,IAAI6H,KAAJ,CAAU,0DAAV,CAAN;AACD;;AACD,SAAOF,OAAP;AACD;;AAEM,SAASI,UAAT,CAAoBnG,IAApB,EAAkCoG,MAAlC,EAAmE;AACxE,SAAOC,yBAAYF,UAAZ,CAAuBnG,IAAvB,EAA6BoG,MAA7B,CAAP;AACD","sourcesContent":["import React from 'react'\nimport {\n ProductDTO,\n ProductVariantDTO,\n AttributeRuleDTO,\n ProductAttributeDraftDTO,\n SelectedOptionDTO,\n ReviewRatingStatisticsDTO,\n AssetSourceDTO,\n} from '@sentecacommerce/sdk'\nimport { getTranslatableField } from '../../'\nimport {\n assignCombinationsToAttributeRules,\n createCombinationsMap,\n createCustomFieldsMap,\n createProductContent,\n createAttributeRulesMap,\n createMappedAttributes,\n processAvailabilityPerStore,\n getProductVideos,\n createMappedOptions,\n createSelectedOption2,\n SelectedOptionType,\n formatCategories,\n createLabelsMap,\n} from './utils'\nimport { productsApi, getProductBySlugConfig } from '../../api/productsApi'\nimport { assetsFieldsToMap, AssetsMap } from '../../utils/assetsToMap'\n\nexport { AssetSourceDTO }\nexport interface OptionsType {\n definitionKey: string\n label: string\n elements?: SubOptionType[]\n}\n\nexport interface SubOptionType {\n optionKey: string\n label: string\n imageIndex?: number\n}\n\nexport interface ContentType {\n key: string\n name?: string\n content?: string\n}\n\nexport interface MetaInfoCategoryType {\n name: string\n id: string\n link: string\n}\n\nexport interface MetaInformationType {\n _id?: string\n name?: string\n slug?: string\n description?: string\n shortDescription?: string\n reviewRatingStatistics?: ReviewRatingStatisticsDTO\n brand: {\n _id?: string\n name?: string\n slug?: string\n logo?: string\n }\n category: {\n _id?: string\n name?: string\n slug?: string\n }\n rootCategory: {\n _id?: string\n name?: string\n slug?: string\n }\n categories?: MetaInfoCategoryType[]\n content?: ContentType[]\n assets?: AssetsMap\n}\n\ninterface SeoInformationType {\n title?: string\n description?: string\n keywords?: string\n}\n\ninterface AttributeRulesType extends AttributeRuleDTO {\n label: string\n values: {\n [id: string]: {\n label: string\n extra: any\n combinations: {\n [id: string]: string\n }\n }\n }\n}\n\nexport interface VariantType\n extends Omit<\n ProductVariantDTO,\n 'attributes' | 'availableOptions' | 'selectedOptions' | 'labels'\n > {\n attributes: ProductAttributeDraftDTO[]\n options?: OptionsType[]\n selectedOptions: SelectedOptionDTO[]\n mappedSelectedOptions?: SelectedOptionType[]\n isAvailable: boolean\n quantity?: number\n inventory: {\n hasAvailableQuantity?: boolean\n availableQuantity?: number\n }\n labels?: string[]\n getAttribute: (\n rule: string\n ) => {\n id: string\n label: string\n name: string\n extra: any\n combinations: {\n [id: string]: string\n }\n }\n getAttributeByKey: (key: string) => undefined | any\n getAvailabilityByStore: () => InventoryAvailabilityType[] | undefined\n}\ninterface VariantMap {\n [productId: string]: VariantType\n}\n\nexport interface BooleanKVP {\n [sku: string]: boolean | undefined\n}\n\nexport interface AttributeRulesMap {\n [name: string]: AttributeRulesType\n}\n\nexport interface CombinationsMap {\n [id: string]: {\n value: string\n params: {\n [id: string]: string\n }\n }\n}\n\nexport interface InventoryAvailabilityType {\n storeName: string\n availableQuantity: number\n acceptsBackorders: boolean\n restockableInDays: number\n}\n\ntype ProductProviderProps = {\n children: React.ReactNode\n product?: ProductDTO\n defaultVariantId?: string\n query?: {\n storeKey?: string\n currencyCode?: string\n languageCode?: string\n priceListKey?: string\n time?: number\n merchantKey?: string\n expand?: string\n project?: string\n }\n}\n\ntype ProductStateContextType = {\n attributeRules: AttributeRulesMap\n metaData: MetaInformationType\n seoData: SeoInformationType\n variants?: VariantMap\n selectedVariant?: VariantType | null\n}\n\nexport type VideoType = {\n type: string\n source: string\n iframe: JSX.Element\n thumb: {\n url: string\n }\n}\n\ntype CountFunctionsContextType = {\n selectVariantById: (id: string) => void\n selectVariantByAttribute: (key: string) => void\n selectVariantByCombination: (key: string, value: string) => void\n selectVariantOptions: (optionId: string, elementId: string) => void\n getVariantById: (id: string) => VariantType\n getVariantByAttribute: (key: string) => VariantType\n getVariantByCombination: (key: string, value: string) => VariantType\n getCustomFieldValue: (field: string) => boolean | undefined\n getCombinationsForAttributeRule: (\n key: string,\n id: string\n ) => {\n label: string\n extra: any\n combinations: {\n [id: string]: string\n }\n }\n getProductVideos: () => VideoType[]\n}\n\nconst ProductStateContext = React.createContext<\n ProductStateContextType | undefined\n>(undefined)\nconst CountDispatchContext = React.createContext<\n CountFunctionsContextType | undefined\n>(undefined)\n\nexport function ProductProvider({\n product,\n children,\n defaultVariantId,\n}: ProductProviderProps) {\n const [mounted, setMounted] = React.useState(false)\n\n const [\n { combinations, attributeRules },\n setCombinationsAndAttributeRules,\n ] = React.useState<{\n combinations: CombinationsMap\n attributeRules: AttributeRulesMap\n }>(getCombinationsAndAttributeRules)\n\n const [variants, setVariants] = React.useState<VariantMap>(\n getVariantsWithInventory\n )\n\n const [\n selectedVariant,\n setSelectedVariant,\n ] = React.useState<VariantType | null>(getDefaultVariant)\n\n const metaData = React.useMemo(() => {\n const rootCategory = product?.categories?.[0]\n const rootCategoryId = rootCategory?.resourceId\n\n const metaObj: MetaInformationType = {\n _id: product?._id,\n name:\n getTranslatableField(selectedVariant?.name) ||\n getTranslatableField(product?.name),\n slug: getTranslatableField(product?.slug),\n description:\n getTranslatableField(selectedVariant?.description) ||\n getTranslatableField(product?.description),\n shortDescription:\n getTranslatableField(selectedVariant?.metaDescription) ||\n getTranslatableField(product?.metaDescription),\n brand: {\n _id: product?.brands?.[0]?.resourceId,\n name: getTranslatableField(product?.brands?.[0]?.resource?.name),\n slug: getTranslatableField(product?.brands?.[0]?.resource?.slug),\n logo: product?.brands?.[0]?.resource?.assets?.[0]?.sources?.[0]?.url,\n },\n category: {\n _id: product?.categories?.[product?.categories?.length - 1]?.resourceId,\n name: getTranslatableField(\n product?.categories?.[product?.categories?.length - 1]?.resource?.name\n ),\n slug: getTranslatableField(\n product?.categories?.[product?.categories?.length - 1]?.resource?.slug\n ),\n },\n rootCategory: {\n _id: rootCategoryId,\n name: getTranslatableField(rootCategory?.resource?.name),\n slug: getTranslatableField(rootCategory?.resource?.slug),\n },\n categories: formatCategories(product?.categories, rootCategoryId),\n reviewRatingStatistics: product?.reviewRatingStatistics,\n content: Boolean(\n selectedVariant?.content?.map(createProductContent).length\n )\n ? selectedVariant?.content?.map(createProductContent)\n : product?.content?.map(createProductContent),\n assets: assetsFieldsToMap(product?.assets),\n }\n return metaObj\n }, [\n product?._id,\n product?.brands,\n product?.content,\n product?.description,\n product?.metaDescription,\n product?.name,\n product?.slug,\n product?.assets,\n selectedVariant,\n ])\n\n const seoData = React.useMemo(() => {\n const seoObj: SeoInformationType = {\n title:\n getTranslatableField(selectedVariant?.metaTitle) ||\n getTranslatableField(product?.metaTitle),\n description:\n getTranslatableField(selectedVariant?.metaDescription) ||\n getTranslatableField(product?.metaDescription),\n keywords:\n getTranslatableField(selectedVariant?.metaKeywords) ||\n getTranslatableField(product?.metaKeywords),\n }\n return seoObj\n }, [\n product?.metaDescription,\n product?.metaKeywords,\n product?.metaTitle,\n selectedVariant,\n ])\n\n const customFields = React.useMemo(() => {\n const mappedFields = createCustomFieldsMap(product?.custom) as BooleanKVP\n return mappedFields\n }, [product?.custom])\n\n React.useEffect(() => {\n // prevent unnecessary calculations\n if (mounted) {\n setVariants(getVariantsWithInventory())\n }\n }, [product])\n\n React.useMemo(() => {\n // prevent unnecessary calculations\n if (!mounted) {\n return setMounted(true)\n }\n\n const data = getCombinationsAndAttributeRules()\n\n setCombinationsAndAttributeRules(data)\n }, [variants])\n\n function getVariantsWithInventory() {\n const variantsWithInventory = product?.variants?.reduce(\n (map: any, _, index, arr) => {\n const currentVariant = arr[index] as ProductVariantDTO\n\n const mappedAttributes = createMappedAttributes(currentVariant)\n\n const mappedOptions =\n createMappedOptions(currentVariant?.availableOptions) || []\n\n const isAvailable = currentVariant?.inventorySnapshot?.canOrder\n\n const updatedVariant: VariantType = {\n ...currentVariant,\n inventory: {\n hasAvailableQuantity: currentVariant.inventorySnapshot?.canOrder,\n availableQuantity:\n currentVariant.inventorySnapshot?.availableQuantity,\n },\n isAvailable: isAvailable ? true : false,\n quantity: isAvailable\n ? currentVariant?.inventorySnapshot?.availableQuantity\n : 0,\n attributes: mappedAttributes,\n options: mappedOptions,\n selectedOptions: [],\n labels: createLabelsMap(currentVariant.labels),\n getAttribute: (rule: string) =>\n getSelectedAttribute(rule, mappedAttributes),\n getAttributeByKey: (key: string) =>\n mappedAttributes.find((a) => a.name === key)?.value,\n getAvailabilityByStore: () =>\n processAvailabilityPerStore(\n currentVariant?.inventorySnapshot?.availabilities\n ),\n }\n\n map[currentVariant._id] = updatedVariant\n\n return map\n },\n {}\n )\n\n return variantsWithInventory || {}\n }\n\n function getCombinationsAndAttributeRules() {\n const mappedAttributeRules: AttributeRulesMap = createAttributeRulesMap(\n product\n )\n\n const attributesWithId = Object.keys(variants || {}).map((key) => {\n return {\n variantId: variants?.[key]._id,\n attributes: variants?.[key].attributes,\n }\n })\n\n const combinationsMap = createCombinationsMap(\n Object.keys(mappedAttributeRules),\n attributesWithId\n )\n\n assignCombinationsToAttributeRules(mappedAttributeRules, combinationsMap)\n\n return {\n combinations: combinationsMap,\n attributeRules: mappedAttributeRules,\n }\n }\n\n function getDefaultVariant() {\n if (!defaultVariantId) return null\n\n return variants[defaultVariantId]\n }\n\n function selectVariantById(id: string) {\n setSelectedVariant(variants[id])\n }\n\n function selectVariantByAttribute(key: string) {\n const id = combinations[key]?.value\n setSelectedVariant(variants[id])\n }\n\n function selectVariantByCombination(key: string, value: string) {\n const id = combinations[key].params[value]\n setSelectedVariant(variants[id])\n }\n\n function selectVariantOptions(definitionKey: string, optionKey: string) {\n if (selectedVariant) {\n const newSelectedVariant = { ...selectedVariant }\n\n newSelectedVariant.selectedOptions = newSelectedVariant.selectedOptions.filter(\n (opt) => opt.definitionKey !== definitionKey\n )\n\n newSelectedVariant.selectedOptions = [\n ...newSelectedVariant.selectedOptions,\n {\n definitionKey,\n optionKey,\n },\n ]\n\n newSelectedVariant.mappedSelectedOptions = newSelectedVariant.selectedOptions.map(\n (option) => createSelectedOption2(newSelectedVariant.options, option)\n )\n\n setSelectedVariant(newSelectedVariant)\n }\n }\n\n function getSelectedAttribute(rule: string, attributes: any[]) {\n const attributeRule = attributeRules[rule]?.values\n let result\n\n attributes.forEach((currentKey) => {\n const found = attributeRule?.[currentKey.value]\n if (found) result = { id: currentKey.value, name: rule, ...found }\n })\n\n return (result as unknown) as {\n id: string\n name: string\n label: string\n extra: any\n combinations: {\n [id: string]: string\n }\n }\n }\n\n function getVariantById(id: string) {\n return variants?.[id]\n }\n\n function getVariantByAttribute(key: string) {\n const id = combinations[key]?.value\n return variants?.[id]\n }\n\n function getVariantByCombination(key: string, value: string) {\n const id = combinations[key]?.params[value]\n return variants?.[id]\n }\n\n function getCustomFieldValue(field: string) {\n return customFields?.[field]\n }\n\n function getCombinationsForAttributeRule(key: string, id: string) {\n const result = attributeRules?.[key]?.values?.[id]\n return result\n }\n\n const state = {\n metaData,\n seoData,\n variants,\n selectedVariant,\n attributeRules,\n }\n\n const functions = {\n getVariantById,\n getVariantByAttribute,\n getVariantByCombination,\n selectVariantById,\n selectVariantByAttribute,\n selectVariantByCombination,\n getCombinationsForAttributeRule,\n selectVariantOptions,\n getCustomFieldValue,\n getProductVideos: () => getProductVideos(metaData.assets),\n }\n\n return (\n <ProductStateContext.Provider value={state}>\n <CountDispatchContext.Provider value={functions}>\n {children}\n </CountDispatchContext.Provider>\n </ProductStateContext.Provider>\n )\n}\n\nexport function useProductState() {\n const context = React.useContext(ProductStateContext)\n if (context === undefined) {\n throw new Error('useProductState must be used within a ProductProvider')\n }\n return context\n}\nexport function useProductFunctions() {\n const context = React.useContext(CountDispatchContext)\n if (context === undefined) {\n throw new Error('useProductDispatch must be used within a ProductProvider')\n }\n return context\n}\n\nexport function useProduct(slug: string, config?: getProductBySlugConfig) {\n return productsApi.useProduct(slug, config)\n}\n"],"file":"index.js"}
|
1
|
+
{"version":3,"sources":["../../../../src/hooks/useProduct/index.tsx"],"names":["ProductStateContext","React","createContext","undefined","CountDispatchContext","ProductProvider","product","children","defaultVariantId","useState","mounted","setMounted","getCombinationsAndAttributeRules","combinations","attributeRules","setCombinationsAndAttributeRules","getVariantsWithInventory","variants","setVariants","getDefaultVariant","selectedVariant","setSelectedVariant","metaData","useMemo","rootCategory","categories","rootCategoryId","resourceId","metaObj","_id","name","slug","description","shortDescription","metaDescription","brand","brands","resource","logo","assets","sources","url","category","length","reviewRatingStatistics","content","Boolean","map","createProductContent","seoData","seoObj","title","metaTitle","keywords","metaKeywords","customFields","mappedFields","custom","useEffect","data","variantsWithInventory","reduce","_","index","arr","currentVariant","mappedAttributes","mappedOptions","availableOptions","isAvailable","inventorySnapshot","canOrder","updatedVariant","inventory","hasAvailableQuantity","availableQuantity","quantity","attributes","options","selectedOptions","labels","getAttribute","rule","getSelectedAttribute","getAttributeByKey","key","find","a","value","getAvailabilityByStore","availabilities","mappedAttributeRules","attributesWithId","Object","keys","variantId","combinationsMap","selectVariantById","id","selectVariantByAttribute","split","el","collapseKey","selectVariantByCombination","attr","params","selectVariantOptions","definitionKey","optionKey","newSelectedVariant","filter","opt","mappedSelectedOptions","option","attributeRule","values","result","forEach","currentKey","found","getVariantById","getVariantByAttribute","getVariantByCombination","getCustomFieldValue","field","getCombinationsForAttributeRule","collapsedImages","state","functions","getProductVideos","useProductState","context","useContext","Error","useProductFunctions","useProduct","config","productsApi"],"mappings":";;;;;;;;;;;;AAAA;;AACA;;;;AASA;;AACA;;AAgBA;;AACA;;AA2LA,IAAMA,mBAAmB,gBAAGC,kBAAMC,aAAN,CAE1BC,SAF0B,CAA5B;;AAGA,IAAMC,oBAAoB,gBAAGH,kBAAMC,aAAN,CAE3BC,SAF2B,CAA7B;;AAIO,SAASE,eAAT,OAIkB;AAAA,MAHvBC,OAGuB,QAHvBA,OAGuB;AAAA,MAFvBC,QAEuB,QAFvBA,QAEuB;AAAA,MADvBC,gBACuB,QADvBA,gBACuB;;AAAA,wBACOP,kBAAMQ,QAAN,CAAe,KAAf,CADP;AAAA,MAChBC,OADgB;AAAA,MACPC,UADO;;AAAA,yBAMnBV,kBAAMQ,QAAN,CAGDG,gCAHC,CANmB;AAAA;AAAA,MAInBC,YAJmB,qBAInBA,YAJmB;AAAA,MAILC,cAJK,qBAILA,cAJK;AAAA,MAKrBC,gCALqB;;AAAA,yBAWSd,kBAAMQ,QAAN,CAC9BO,wBAD8B,CAXT;AAAA,MAWhBC,QAXgB;AAAA,MAWNC,WAXM;;AAAA,yBAkBnBjB,kBAAMQ,QAAN,CAAmCU,iBAAnC,CAlBmB;AAAA,MAgBrBC,eAhBqB;AAAA,MAiBrBC,kBAjBqB;;AAoBvB,MAAMC,QAAQ,GAAGrB,kBAAMsB,OAAN,CAAc,YAAM;AAAA;;AACnC,QAAMC,YAAY,GAAGlB,OAAH,2CAAGA,OAA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;AAKhBE,IAAAA,wBAAwB,EAAxBA,wBALgB;AAMhBI,IAAAA,0BAA0B,EAA1BA,0BANgB;AAOhBsB,IAAAA,+BAA+B,EAA/BA,+BAPgB;AAQhBnB,IAAAA,oBAAoB,EAApBA,oBARgB;AAShBiB,IAAAA,mBAAmB,EAAnBA,mBATgB;AAUhBM,IAAAA,gBAAgB,EAAE;AAAA,aAAM,6BAAiB3G,QAAQ,CAACiB,MAA1B,CAAN;AAAA;AAVF,GAAlB;AAaA,sBACE,gCAAC,mBAAD,CAAqB,QAArB;AAA8B,IAAA,KAAK,EAAEwF;AAArC,kBACE,gCAAC,oBAAD,CAAsB,QAAtB;AAA+B,IAAA,KAAK,EAAEC;AAAtC,KACGzH,QADH,CADF,CADF;AAOD;;AAEM,SAAS2H,eAAT,GAA2B;AAChC,MAAMC,OAAO,GAAGlI,kBAAMmI,UAAN,CAAiBpI,mBAAjB,CAAhB;;AACA,MAAImI,OAAO,KAAKhI,SAAhB,EAA2B;AACzB,UAAM,IAAIkI,KAAJ,CAAU,uDAAV,CAAN;AACD;;AACD,SAAOF,OAAP;AACD;;AACM,SAASG,mBAAT,GAA+B;AACpC,MAAMH,OAAO,GAAGlI,kBAAMmI,UAAN,CAAiBhI,oBAAjB,CAAhB;;AACA,MAAI+H,OAAO,KAAKhI,SAAhB,EAA2B;AACzB,UAAM,IAAIkI,KAAJ,CAAU,0DAAV,CAAN;AACD;;AACD,SAAOF,OAAP;AACD;;AAEM,SAASI,UAAT,CAAoBxG,IAApB,EAAkCyG,MAAlC,EAAmE;AACxE,SAAOC,yBAAYF,UAAZ,CAAuBxG,IAAvB,EAA6ByG,MAA7B,CAAP;AACD","sourcesContent":["import React from 'react'\nimport {\n ProductDTO,\n ProductVariantDTO,\n AttributeRuleDTO,\n ProductAttributeDraftDTO,\n SelectedOptionDTO,\n ReviewRatingStatisticsDTO,\n AssetSourceDTO,\n} from '@sentecacommerce/sdk'\nimport { getTranslatableField } from '../../'\nimport {\n assignCombinationsToAttributeRules,\n createCombinationsMap,\n createCustomFieldsMap,\n createProductContent,\n createAttributeRulesMap,\n createMappedAttributes,\n processAvailabilityPerStore,\n getProductVideos,\n createMappedOptions,\n createSelectedOption2,\n SelectedOptionType,\n formatCategories,\n createLabelsMap,\n createCollapseKeyImagesMap,\n} from './utils'\nimport { productsApi, getProductBySlugConfig } from '../../api/productsApi'\nimport { assetsFieldsToMap, AssetsMap } from '../../utils/assetsToMap'\n\nexport { AssetSourceDTO }\nexport interface OptionsType {\n definitionKey: string\n label: string\n elements?: SubOptionType[]\n}\n\nexport interface SubOptionType {\n optionKey: string\n label: string\n imageIndex?: number\n}\n\nexport interface ContentType {\n key: string\n name?: string\n content?: string\n}\n\nexport interface MetaInfoCategoryType {\n name: string\n id: string\n link: string\n}\n\nexport interface MetaInformationType {\n _id?: string\n name?: string\n slug?: string\n description?: string\n shortDescription?: string\n reviewRatingStatistics?: ReviewRatingStatisticsDTO\n brand: {\n _id?: string\n name?: string\n slug?: string\n logo?: string\n }\n category: {\n _id?: string\n name?: string\n slug?: string\n }\n rootCategory: {\n _id?: string\n name?: string\n slug?: string\n }\n categories?: MetaInfoCategoryType[]\n content?: ContentType[]\n assets?: AssetsMap\n}\n\ninterface SeoInformationType {\n title?: string\n description?: string\n keywords?: string\n}\n\ninterface AttributeRulesType extends AttributeRuleDTO {\n label: string\n values: {\n [id: string]: {\n label: string\n extra: any\n combinations: {\n [id: string]: string\n }\n }\n }\n}\n\nexport interface VariantType\n extends Omit<\n ProductVariantDTO,\n 'attributes' | 'availableOptions' | 'selectedOptions' | 'labels'\n > {\n attributes: ProductAttributeDraftDTO[]\n options?: OptionsType[]\n selectedOptions: SelectedOptionDTO[]\n mappedSelectedOptions?: SelectedOptionType[]\n isAvailable: boolean\n quantity?: number\n inventory: {\n hasAvailableQuantity?: boolean\n availableQuantity?: number\n }\n labels?: string[]\n getAttribute: (\n rule: string\n ) => {\n id: string\n label: string\n name: string\n extra: any\n combinations: {\n [id: string]: string\n }\n }\n getAttributeByKey: (key: string) => undefined | any\n getAvailabilityByStore: () => InventoryAvailabilityType[] | undefined\n}\ninterface VariantMap {\n [productId: string]: VariantType\n}\n\nexport interface BooleanKVP {\n [sku: string]: boolean | undefined\n}\n\nexport interface AttributeRulesMap {\n [name: string]: AttributeRulesType\n}\n\nexport interface CombinationsMap {\n [id: string]: {\n value: string\n params: {\n [id: string]: string\n }\n }\n}\n\nexport interface InventoryAvailabilityType {\n storeName: string\n availableQuantity: number\n acceptsBackorders: boolean\n restockableInDays: number\n}\n\ntype ProductProviderProps = {\n children: React.ReactNode\n product?: ProductDTO\n defaultVariantId?: string\n query?: {\n storeKey?: string\n currencyCode?: string\n languageCode?: string\n priceListKey?: string\n time?: number\n merchantKey?: string\n expand?: string\n project?: string\n }\n}\n\ntype ProductStateContextType = {\n attributeRules: AttributeRulesMap\n metaData: MetaInformationType\n seoData: SeoInformationType\n variants?: VariantMap\n selectedVariant?: VariantType | null\n}\n\nexport type VideoType = {\n type: string\n source: string\n iframe: JSX.Element\n thumb: {\n url: string\n }\n}\n\ntype CountFunctionsContextType = {\n selectVariantById: (id: string) => void\n selectVariantByAttribute: (key: string) => void\n selectVariantByCombination: (key: string, value: string) => void\n selectVariantOptions: (optionId: string, elementId: string) => void\n getVariantById: (id: string) => VariantType\n getVariantByAttribute: (key: string) => VariantType\n getVariantByCombination: (key: string, value: string) => VariantType\n getCustomFieldValue: (field: string) => boolean | undefined\n getCombinationsForAttributeRule: (\n key: string,\n id: string\n ) => {\n label: string\n extra: any\n combinations: {\n [id: string]: string\n }\n }\n getProductVideos: () => VideoType[]\n}\n\nconst ProductStateContext = React.createContext<\n ProductStateContextType | undefined\n>(undefined)\nconst CountDispatchContext = React.createContext<\n CountFunctionsContextType | undefined\n>(undefined)\n\nexport function ProductProvider({\n product,\n children,\n defaultVariantId,\n}: ProductProviderProps) {\n const [mounted, setMounted] = React.useState(false)\n\n const [\n { combinations, attributeRules },\n setCombinationsAndAttributeRules,\n ] = React.useState<{\n combinations: CombinationsMap\n attributeRules: AttributeRulesMap\n }>(getCombinationsAndAttributeRules)\n\n const [variants, setVariants] = React.useState<VariantMap>(\n getVariantsWithInventory\n )\n\n const [\n selectedVariant,\n setSelectedVariant,\n ] = React.useState<VariantType | null>(getDefaultVariant)\n\n const metaData = React.useMemo(() => {\n const rootCategory = product?.categories?.[0]\n const rootCategoryId = rootCategory?.resourceId\n\n const metaObj: MetaInformationType = {\n _id: product?._id,\n name:\n getTranslatableField(selectedVariant?.name) ||\n getTranslatableField(product?.name),\n slug: getTranslatableField(product?.slug),\n description:\n getTranslatableField(selectedVariant?.description) ||\n getTranslatableField(product?.description),\n shortDescription:\n getTranslatableField(selectedVariant?.metaDescription) ||\n getTranslatableField(product?.metaDescription),\n brand: {\n _id: product?.brands?.[0]?.resourceId,\n name: getTranslatableField(product?.brands?.[0]?.resource?.name),\n slug: getTranslatableField(product?.brands?.[0]?.resource?.slug),\n logo: product?.brands?.[0]?.resource?.assets?.[0]?.sources?.[0]?.url,\n },\n category: {\n _id: product?.categories?.[product?.categories?.length - 1]?.resourceId,\n name: getTranslatableField(\n product?.categories?.[product?.categories?.length - 1]?.resource?.name\n ),\n slug: getTranslatableField(\n product?.categories?.[product?.categories?.length - 1]?.resource?.slug\n ),\n },\n rootCategory: {\n _id: rootCategoryId,\n name: getTranslatableField(rootCategory?.resource?.name),\n slug: getTranslatableField(rootCategory?.resource?.slug),\n },\n categories: formatCategories(product?.categories, rootCategoryId),\n reviewRatingStatistics: product?.reviewRatingStatistics,\n content: Boolean(\n selectedVariant?.content?.map(createProductContent).length\n )\n ? selectedVariant?.content?.map(createProductContent)\n : product?.content?.map(createProductContent),\n assets: assetsFieldsToMap(product?.assets),\n }\n return metaObj\n }, [\n product?._id,\n product?.brands,\n product?.content,\n product?.description,\n product?.metaDescription,\n product?.name,\n product?.slug,\n product?.assets,\n selectedVariant,\n ])\n\n const seoData = React.useMemo(() => {\n const seoObj: SeoInformationType = {\n title:\n getTranslatableField(selectedVariant?.metaTitle) ||\n getTranslatableField(product?.metaTitle),\n description:\n getTranslatableField(selectedVariant?.metaDescription) ||\n getTranslatableField(product?.metaDescription),\n keywords:\n getTranslatableField(selectedVariant?.metaKeywords) ||\n getTranslatableField(product?.metaKeywords),\n }\n return seoObj\n }, [\n product?.metaDescription,\n product?.metaKeywords,\n product?.metaTitle,\n selectedVariant,\n ])\n\n const customFields = React.useMemo(() => {\n const mappedFields = createCustomFieldsMap(product?.custom) as BooleanKVP\n return mappedFields\n }, [product?.custom])\n\n React.useEffect(() => {\n // prevent unnecessary calculations\n if (mounted) {\n setVariants(getVariantsWithInventory())\n }\n }, [product])\n\n React.useMemo(() => {\n // prevent unnecessary calculations\n if (!mounted) {\n return setMounted(true)\n }\n\n const data = getCombinationsAndAttributeRules()\n\n setCombinationsAndAttributeRules(data)\n }, [variants])\n\n function getVariantsWithInventory() {\n const variantsWithInventory = product?.variants?.reduce(\n (map: any, _, index, arr) => {\n const currentVariant = arr[index] as ProductVariantDTO\n\n const mappedAttributes = createMappedAttributes(currentVariant)\n\n const mappedOptions =\n createMappedOptions(currentVariant?.availableOptions) || []\n\n const isAvailable = currentVariant?.inventorySnapshot?.canOrder\n\n const updatedVariant: VariantType = {\n ...currentVariant,\n inventory: {\n hasAvailableQuantity: currentVariant.inventorySnapshot?.canOrder,\n availableQuantity:\n currentVariant.inventorySnapshot?.availableQuantity,\n },\n isAvailable: isAvailable ? true : false,\n quantity: isAvailable\n ? currentVariant?.inventorySnapshot?.availableQuantity\n : 0,\n attributes: mappedAttributes,\n options: mappedOptions,\n selectedOptions: [],\n labels: createLabelsMap(currentVariant.labels),\n getAttribute: (rule: string) =>\n getSelectedAttribute(rule, mappedAttributes),\n getAttributeByKey: (key: string) =>\n mappedAttributes.find((a) => a.name === key)?.value,\n getAvailabilityByStore: () =>\n processAvailabilityPerStore(\n currentVariant?.inventorySnapshot?.availabilities\n ),\n }\n\n map[currentVariant._id] = updatedVariant\n\n return map\n },\n {}\n )\n\n return variantsWithInventory || {}\n }\n\n function getCombinationsAndAttributeRules() {\n const mappedAttributeRules: AttributeRulesMap = createAttributeRulesMap(\n product\n )\n\n const attributesWithId = Object.keys(variants || {}).map((key) => {\n return {\n variantId: variants?.[key]._id,\n attributes: variants?.[key].attributes,\n }\n })\n\n const combinationsMap = createCombinationsMap(\n Object.keys(mappedAttributeRules),\n attributesWithId\n )\n\n assignCombinationsToAttributeRules(mappedAttributeRules, combinationsMap)\n\n return {\n combinations: combinationsMap,\n attributeRules: mappedAttributeRules,\n }\n }\n\n function getDefaultVariant() {\n if (!defaultVariantId) return null\n\n return variants[defaultVariantId]\n }\n\n function selectVariantById(id: string) {\n setSelectedVariant(variants[id])\n }\n\n function selectVariantByAttribute(key: string) {\n // Get by collapseKey for SD\n const split = key.split(':')\n if (split[0] === 'collapseKey') {\n const id = Object.keys(variants).find(\n (el) => variants[el].collapseKey === split[1]\n )\n return setSelectedVariant(variants[id as string])\n }\n const id = combinations[key]?.value\n setSelectedVariant(variants[id])\n }\n\n function selectVariantByCombination(key: string, value: string) {\n // Take collapseKey for SD\n const split = value.split(':')\n if (split[0] === 'collapseKey') {\n const id = Object.keys(variants).find(\n (el) =>\n variants[el].collapseKey === split[1] &&\n variants[el].attributes.find((attr) => attr.name === 'size')\n ?.value === key\n )\n return setSelectedVariant(variants[id as string])\n }\n const id = combinations[key].params[value]\n setSelectedVariant(variants[id])\n }\n\n function selectVariantOptions(definitionKey: string, optionKey: string) {\n if (selectedVariant) {\n const newSelectedVariant = { ...selectedVariant }\n\n newSelectedVariant.selectedOptions = newSelectedVariant.selectedOptions.filter(\n (opt) => opt.definitionKey !== definitionKey\n )\n\n newSelectedVariant.selectedOptions = [\n ...newSelectedVariant.selectedOptions,\n {\n definitionKey,\n optionKey,\n },\n ]\n\n newSelectedVariant.mappedSelectedOptions = newSelectedVariant.selectedOptions.map(\n (option) => createSelectedOption2(newSelectedVariant.options, option)\n )\n\n setSelectedVariant(newSelectedVariant)\n }\n }\n\n function getSelectedAttribute(rule: string, attributes: any[]) {\n const attributeRule = attributeRules[rule]?.values\n let result\n\n attributes.forEach((currentKey) => {\n const found = attributeRule?.[currentKey.value]\n if (found) result = { id: currentKey.value, name: rule, ...found }\n })\n\n return (result as unknown) as {\n id: string\n name: string\n label: string\n extra: any\n combinations: {\n [id: string]: string\n }\n }\n }\n\n function getVariantById(id: string) {\n return variants?.[id]\n }\n\n function getVariantByAttribute(key: string) {\n const id = combinations[key]?.value\n return variants?.[id]\n }\n\n function getVariantByCombination(key: string, value: string) {\n const id = combinations[key]?.params[value]\n return variants?.[id]\n }\n\n function getCustomFieldValue(field: string) {\n return customFields?.[field]\n }\n\n function getCombinationsForAttributeRule(key: string, id: string) {\n const result = attributeRules?.[key]?.values?.[id]\n return result\n }\n\n const collapsedImages = createCollapseKeyImagesMap(product)\n\n const state = {\n metaData,\n seoData,\n variants,\n selectedVariant,\n attributeRules,\n collapsedImages,\n }\n\n const functions = {\n getVariantById,\n getVariantByAttribute,\n getVariantByCombination,\n selectVariantById,\n selectVariantByAttribute,\n selectVariantByCombination,\n getCombinationsForAttributeRule,\n selectVariantOptions,\n getCustomFieldValue,\n getProductVideos: () => getProductVideos(metaData.assets),\n }\n\n return (\n <ProductStateContext.Provider value={state}>\n <CountDispatchContext.Provider value={functions}>\n {children}\n </CountDispatchContext.Provider>\n </ProductStateContext.Provider>\n )\n}\n\nexport function useProductState() {\n const context = React.useContext(ProductStateContext)\n if (context === undefined) {\n throw new Error('useProductState must be used within a ProductProvider')\n }\n return context\n}\nexport function useProductFunctions() {\n const context = React.useContext(CountDispatchContext)\n if (context === undefined) {\n throw new Error('useProductDispatch must be used within a ProductProvider')\n }\n return context\n}\n\nexport function useProduct(slug: string, config?: getProductBySlugConfig) {\n return productsApi.useProduct(slug, config)\n}\n"],"file":"index.js"}
|
@@ -3,7 +3,7 @@
|
|
3
3
|
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
4
4
|
|
5
5
|
exports.__esModule = true;
|
6
|
-
exports.createLabelsMap = exports.formatCategories = exports.getProductVideos = exports.processAvailabilityPerStore = exports.createMappedAttributes = exports.createSelectedOption = exports.createSelectedOption2 = exports.createMappedOptions = exports.createAttributeRulesMap = exports.createProductContent = exports.assignCombinationsToAttributeRules = exports.createCombinationsMap = exports.createCustomFieldsMap = void 0;
|
6
|
+
exports.createLabelsMap = exports.formatCategories = exports.getProductVideos = exports.processAvailabilityPerStore = exports.createMappedAttributes = exports.createSelectedOption = exports.createSelectedOption2 = exports.createMappedOptions = exports.createAttributeRulesMap = exports.createCollapseKeyImagesMap = exports.createProductContent = exports.assignCombinationsToAttributeRules = exports.createCombinationsMap = exports.createCustomFieldsMap = void 0;
|
7
7
|
|
8
8
|
var _extends4 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
9
9
|
|
@@ -92,12 +92,29 @@ var createProductContent = function createProductContent(data) {
|
|
92
92
|
name: (0, _utils.getTranslatableField)(data.label),
|
93
93
|
content: (0, _utils.getTranslatableField)(data.content)
|
94
94
|
};
|
95
|
-
};
|
95
|
+
}; // Add grouped images for SD color variants
|
96
|
+
|
96
97
|
|
97
98
|
exports.createProductContent = createProductContent;
|
98
99
|
|
100
|
+
var createCollapseKeyImagesMap = function createCollapseKeyImagesMap(product) {
|
101
|
+
var _product$variants;
|
102
|
+
|
103
|
+
var mappedKeys = product == null ? void 0 : (_product$variants = product.variants) == null ? void 0 : _product$variants.reduce(function (res, cur) {
|
104
|
+
if (!res[cur.collapseKey]) {
|
105
|
+
res[cur.collapseKey] = [];
|
106
|
+
}
|
107
|
+
|
108
|
+
res[cur.collapseKey].push(cur);
|
109
|
+
return res;
|
110
|
+
}, {});
|
111
|
+
return mappedKeys;
|
112
|
+
};
|
113
|
+
|
114
|
+
exports.createCollapseKeyImagesMap = createCollapseKeyImagesMap;
|
115
|
+
|
99
116
|
var createAttributeRulesMap = function createAttributeRulesMap(product) {
|
100
|
-
var _product$attributeRul, _product$
|
117
|
+
var _product$attributeRul, _product$variants2;
|
101
118
|
|
102
119
|
var uniqueRules = product == null ? void 0 : (_product$attributeRul = product.attributeRules) == null ? void 0 : _product$attributeRul.filter(function (x) {
|
103
120
|
return x.constraint === _sdk.AttributeRuleDTOConstraintEnum.CombinationUnique;
|
@@ -129,7 +146,7 @@ var createAttributeRulesMap = function createAttributeRulesMap(product) {
|
|
129
146
|
return map;
|
130
147
|
};
|
131
148
|
|
132
|
-
var mappedAttributeRules = product == null ? void 0 : (_product$
|
149
|
+
var mappedAttributeRules = product == null ? void 0 : (_product$variants2 = product.variants) == null ? void 0 : _product$variants2.map(function (v) {
|
133
150
|
return v.attributes;
|
134
151
|
}).flat().reduce(reduceVariantsToAttributeRuleValues, {});
|
135
152
|
return mappedAttributeRules;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../../../src/hooks/useProduct/utils/index.ts"],"names":["createCustomFieldsMap","customFields","reduce","map","currentObj","field","value","createCombinationsMap","mappedAttributeRulesKeys","attributesArray","combinationsMap","forEach","key","p","currentKey","attributes","find","x","name","filtered","filter","currentCombination","params","variantId","attribute","assignCombinationsToAttributeRules","mappedAttributeRules","Object","keys","current","values","combinations","createProductContent","data","label","content","createAttributeRulesMap","product","uniqueRules","attributeRules","constraint","AttributeRuleDTOConstraintEnum","CombinationUnique","reduceVariantsToAttributeRuleValues","found","attributeName","valueData","extra","variants","v","flat","createMappedOptions","options","mappedOptions","currentOption","definitionKey","elements","subOption","optionKey","imageIndex","createSelectedOption2","selectedOption","availableOption","element","createSelectedOption","optionValue","createMappedAttributes","currentVariant","mappedAttributes","attributeArray","push","processAvailabilityPerStore","availabilities","isPhysical","acceptsBackorders","stockLocationName","restockableInDays","availableQuantity","storeName","getProductVideos","assets","youtube","videos","sources","a","embeded","type","source","url","iframe","thumb","thumbnail","formatCategories","categories","rootCategoryId","results","some","cat","resource","custom","customField","cats","result","category","resourceId","hasChildCategories","paths","parents","ancestors","parent","_id","Boolean","mainPaths","path","ancestor","formattedResults","id","link","slug","createLabelsM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AWC,OAAX,EAAZ;AAEA,MAAMC,aAAa,GAAG1F,IAAH,oBAAGA,IAAI,CAAEb,MAAN,CAAa,UAACwG,EAAD,EAAQ;AACzC,QAAI,CAACA,EAAE,CAACC,SAAJ,IAAiB,CAACD,EAAE,CAACE,OAAzB,EAAkC;AAChC,aAAOF,EAAP;AACD,KAFD,MAEO;AACL,aAAOA,EAAE,CAACC,SAAH,GAAeL,GAAf,IAAsBI,EAAE,CAACE,OAAH,GAAaN,GAA1C;AACD;AACF,GANqB,CAAtB;AAQA,SAAOG,aAAP,oBAAOA,aAAa,CAAExH,GAAf,CAAmB,UAACyH,EAAD;AAAA,WAAQA,EAAE,CAAChH,GAAX;AAAA,GAAnB,CAAP;AACD,CAbM","sourcesContent":["import {\n ProductAttributeDTO,\n CustomField,\n AttributeRuleDTOConstraintEnum,\n ProductDTO,\n ProductVariantDTO,\n InventoryAvailability,\n OptionDefinitionDTO,\n SelectedOptionDTO,\n IdReferenceDTO,\n CategoryDTO,\n ProductVariantLabelDTO,\n} from '@sentecacommerce/sdk'\n\nimport {\n AttributeRulesMap,\n CombinationsMap,\n BooleanKVP,\n InventoryAvailabilityType,\n MetaInformationType,\n OptionsType,\n} from '../index'\n\nimport { createEmbededVideo } from './createEmbededVideo'\n\nimport { getTranslatableField } from '../../../utils'\n\n// export const createMappedInventory = (\n// currentVariant: ProductVariantDraftDTO,\n// inventory?: SkuReservationResponseDTO\n// ) => {\n// const currentInventory = inventory?.find(\n// (x) => x.sku === currentVariant.sku\n// )\n\n// const mappedInventory = {\n// ...currentInventory,\n// status:\n// currentInventory?.status === SkuReservationDTOStatusEnum.Available\n// ? true\n// : false,\n// inventoryId: currentInventory?.inventoryReservations?.[0].inventoryId,\n// quantity: currentInventory?.inventoryReservations?.[0].quantity,\n// }\n\n// return mappedInventory\n// }\n\nexport const createCustomFieldsMap = (customFields?: CustomField[]) => {\n return customFields?.reduce((map: BooleanKVP, currentObj) => {\n map[currentObj.field] = currentObj.value\n return map\n }, {})\n}\n\nexport const createCombinationsMap = (\n mappedAttributeRulesKeys: string[],\n attributesArray: {\n variantId: string\n attributes: ProductAttributeDTO[]\n }[]\n) => {\n const combinationsMap: CombinationsMap = {}\n mappedAttributeRulesKeys.forEach((key) => {\n attributesArray.forEach((p) => {\n const currentKey = p.attributes.find((x) => x.name === key)\n const filtered = p.attributes.filter((x) => x.name !== key)\n\n let currentCombination = combinationsMap[currentKey?.value]\n\n if (!currentCombination) {\n currentCombination = {\n params: {},\n value: '',\n }\n }\n\n currentCombination.value = p.variantId\n\n filtered.forEach((attribute) => {\n currentCombination.params = {\n ...currentCombination.params,\n [attribute.value]: p.variantId,\n }\n })\n\n combinationsMap[currentKey?.value] = currentCombination\n })\n })\n\n return combinationsMap\n}\n\nexport const assignCombinationsToAttributeRules = (\n mappedAttributeRules: AttributeRulesMap,\n combinationsMap: CombinationsMap\n) => {\n Object.keys(mappedAttributeRules).forEach((key) => {\n const current = mappedAttributeRules[key].values\n Object.keys(current).forEach((currentKey) => {\n mappedAttributeRules[key].values[currentKey].combinations =\n combinationsMap[currentKey]?.params\n })\n })\n}\n\nexport const createProductContent = (\n data: any\n): { key: string; name: string; content: string } => {\n return {\n key: data.key,\n name: getTranslatableField(data.label),\n content: getTranslatableField(data.content),\n }\n}\n\nexport const createAttributeRulesMap = (product?: ProductDTO) => {\n const uniqueRules = product?.attributeRules?.filter(\n (x) => x.constraint === AttributeRuleDTOConstraintEnum.CombinationUnique\n )\n const reduceVariantsToAttributeRuleValues = (map: any, attribute: any) => {\n const found = uniqueRules?.find((x) => x.attributeName === attribute.name)\n if (found) {\n if (!map[attribute.name]) {\n map[attribute.name] = {\n ...found,\n label: getTranslatableField(attribute.data.label),\n values: {},\n }\n }\n\n map[attribute.name] = {\n ...map[attribute.name],\n values: {\n ...map[attribute.name].values,\n [attribute.value]: {\n label: getTranslatableField(attribute.valueData.label),\n extra: attribute.valueData.extra,\n },\n },\n }\n }\n\n return map\n }\n\n const mappedAttributeRules = product?.variants\n ?.map((v) => v.attributes)\n .flat()\n .reduce(reduceVariantsToAttributeRuleValues, {})\n\n return mappedAttributeRules\n}\n\nexport const createMappedOptions = (\n options?: OptionDefinitionDTO[]\n): OptionsType[] => {\n const mappedOptions =\n options?.map((currentOption) => {\n return {\n definitionKey: currentOption.key,\n label: getTranslatableField(currentOption?.label),\n elements: currentOption.options?.map((subOption) => {\n return {\n optionKey: subOption.key,\n label: getTranslatableField(subOption?.label),\n imageIndex: subOption?.imageIndex,\n }\n }),\n }\n }) || []\n\n return mappedOptions\n}\n\nexport type SelectedOptionType = {\n label?: string\n value?: { key?: string; label?: string; imageIndex?: number }\n}\n\nexport const createSelectedOption2 = (\n options?: OptionsType[],\n selectedOption?: SelectedOptionDTO\n): SelectedOptionType => {\n const currentOption = options?.find(\n (availableOption) =>\n availableOption.definitionKey === selectedOption?.definitionKey\n )\n\n const value = currentOption?.elements?.find(\n (element) => element.optionKey === selectedOption?.optionKey\n )\n\n return {\n label: currentOption?.label,\n value: {\n key: value?.optionKey,\n imageIndex: value?.imageIndex,\n label: value?.label,\n },\n }\n}\n\nexport const createSelectedOption = (\n options?: OptionDefinitionDTO[],\n selectedOption?: SelectedOptionDTO\n): SelectedOptionType => {\n const currentOption = options?.find(\n (availableOption) => availableOption.key === selectedOption?.definitionKey\n )\n\n const value = currentOption?.options?.find(\n (optionValue) => optionValue.key === selectedOption?.optionKey\n )\n\n return {\n label: getTranslatableField(currentOption?.label),\n value: {\n key: value?.key,\n imageIndex: value?.imageIndex,\n label: getTranslatableField(value?.label),\n },\n }\n}\n\nexport const createMappedAttributes = (currentVariant: ProductVariantDTO) => {\n const mappedAttributes =\n currentVariant.attributes?.reduce(\n (attributeArray: ProductAttributeDTO[], attribute) => {\n attributeArray.push({\n name: attribute.name,\n value: attribute.value,\n valueData: attribute.valueData,\n })\n return attributeArray\n },\n []\n ) || []\n\n return mappedAttributes\n}\n\nexport const processAvailabilityPerStore = (\n availabilities?: InventoryAvailability[]\n): InventoryAvailabilityType[] | undefined => {\n return availabilities\n ?.filter((x) => !x.isPhysical)\n ?.map(\n ({\n acceptsBackorders,\n stockLocationName,\n restockableInDays,\n availableQuantity,\n }) => {\n return {\n storeName: getTranslatableField(stockLocationName),\n availableQuantity,\n acceptsBackorders,\n restockableInDays: restockableInDays,\n }\n }\n )\n}\n\nexport const getProductVideos = (assets: MetaInformationType['assets']) => {\n if (assets?.youtube) {\n const videos = assets.youtube.sources.map((a) => {\n const embeded = createEmbededVideo(a)\n return {\n type: 'video',\n source: a.url,\n iframe: embeded.iframe,\n thumb: { url: embeded.thumbnail },\n }\n })\n\n return videos\n }\n return []\n}\n\nexport const formatCategories = (\n categories?: IdReferenceDTO[],\n rootCategoryId?: string\n) => {\n let results\n\n if (\n categories?.some((cat) =>\n cat.resource?.custom?.some(\n (customField: any) => customField.field === 'isTemporary'\n )\n )\n ) {\n type PathType = {\n [key: string]: string\n }\n type CategoryType = CategoryDTO & { hasChildCategories: boolean }\n\n const cats = categories.reduce((result, category) => {\n result[category.resourceId] = {\n ...category.resource,\n hasChildCategories: false,\n }\n\n return result\n }, {} as CategoryDTO[])\n\n const paths = Object.values(cats).reduce((result, category) => {\n const parents = (category?.ancestors as IdReferenceDTO[])\n .map((parent: any) => {\n return (cats?.[parent?.resourceId] as any)?._id\n })\n .filter(Boolean)\n\n parents.forEach((parent: any) => {\n ;(cats as CategoryType[])[parent].hasChildCategories = true\n })\n\n result[category._id as string] = [...parents, category._id]\n\n return result\n }, {} as PathType[])\n\n const mainPaths = Object.values(cats as CategoryType[] & IdReferenceDTO[])\n .filter((category: CategoryType) => category.hasChildCategories === false)\n .map((category) => paths?.[category._id as string])\n .map((paths) => paths.map((path: string) => cats?.[path]))\n .filter(\n (paths) =>\n !paths.some(\n (path: { custom: any }) =>\n path?.custom?.find(\n (custom: any) => custom.field === 'isTemporary'\n )?.value ?? false\n )\n )?.[0]\n .flat()\n\n results = mainPaths\n } else {\n results = categories?.filter(\n (cat) =>\n cat?.resourceId === rootCategoryId ||\n cat?.resource?.ancestors?.some(\n (ancestor: any) => ancestor.resource === rootCategoryId\n )\n )\n }\n\n const formattedResults = (results as IdReferenceDTO[])?.map((category) => {\n if (category.resource) {\n const resource = category.resource as CategoryDTO\n\n return {\n name: getTranslatableField(resource.name),\n id: category.resourceId || '',\n link: `/${getTranslatableField(resource.slug)}/c`,\n }\n }\n\n const cat = (category as unknown) as CategoryDTO\n\n return {\n name: getTranslatableField(cat.name),\n id: cat._id || '',\n link: `/${getTranslatableField(cat.slug)}/c`,\n }\n })\n\n return formattedResults || []\n}\n\nexport const createLabelsMap = (data?: ProductVariantLabelDTO[]) => {\n // Filter only labels that are currently active\n const now = new Date().getTime()\n\n const currentLabels = data?.filter((el) => {\n if (!el.validFrom || !el.validTo) {\n return el\n } else {\n return el.validFrom < now && el.validTo > now\n }\n })\n\n return currentLabels?.map((el) => el.key)\n}\n"],"file":"index.js"}
|
1
|
+
{"version":3,"sources":["../../../../../src/hooks/useProduct/utils/index.ts"],"names":["createCustomFieldsMap","customFields","reduce","map","currentObj","field","value","createCombinationsMap","mappedAttributeRulesKeys","attributesArray","combinationsMap","forEach","key","p","currentKey","attributes","find","x","name","filtered","filter","currentCombination","params","variantId","attribute","assignCombinationsToAttributeRules","mappedAttributeRules","Object","keys","current","values","combinations","createProductContent","data","label","content","createCollapseKeyImagesMap","product","mappedKeys","variants","res","cur","collapseKey","push","createAttributeRulesMap","uniqueRules","attributeRules","constraint","AttributeRuleDTOConstraintEnum","CombinationUnique","reduceVariantsToAttributeRuleValues","found","attributeName","valueData","extra","v","flat","createMappedOptions","options","mappedOptions","currentOption","definitionKey","elements","subOption","optionKey","imageIndex","createSelectedOption2","selectedOption","availableOption","element","createSelectedOption","optionValue","createMappedAttributes","currentVariant","mappedAttributes","attributeArray","processAvailabilityPerStore","availabilities","isPhysical","acceptsBackorders","stockLocationName","restockableInDays","availableQuantity","storeName","getProductVideos","assets","youtube","videos","sources","a","embeded","type","source","url","iframe","thumb","thumbnail","formatCategories","categories","rootCategoryId","results","some","cat","resource","custom","customField","cats","result","category","resourceId","hasChildCategories","paths","parents","ancestors","parent","_id","Boolean","mainPaths","path","ancestor","formattedResults","id","link","slug","createLabelsMap","now","Date","getTime","currentLabels","el","validFrom","validTo"],"mappings":";;;;;;;;;AAAA;;AAuBA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AAEO,IAAMA,qBAAqB,GAAG,SAAxBA,qBAAwB,CAACC,YAAD,EAAkC;AACrE,SAAOA,YAAP,oBAAOA,YAAY,CAAEC,MAAd,CAAqB,UAACC,GAAD,EAAkBC,UAAlB,EAAiC;AAC3DD,IAAAA,GAAG,CAACC,UAAU,CAACC,KAAZ,CAAH,GAAwBD,UAAU,CAACE,KAAnC;AACA,WAAOH,GAAP;AACD,GAHM,EAGJ,EAHI,CAAP;AAID,CALM;;;;AAOA,IAAMI,qBAAqB,GAAG,SAAxBA,qBAAwB,CACnCC,wBADmC,EAEnCC,eAFmC,EAMhC;AACH,MAAMC,eAAgC,GAAG,EAAzC;AACAF,EAAAA,wBAAwB,CAACG,OAAzB,CAAiC,UAACC,GAAD,EAAS;AACxCH,IAAAA,eAAe,CAACE,OAAhB,CAAwB,UAACE,CAAD,EAAO;AAC7B,UAAMC,UAAU,GAAGD,CAAC,CAACE,UAAF,CAAaC,IAAb,CAAkB,UAACC,CAAD;AAAA,eAAOA,CAAC,CAACC,IAAF,KAAWN,GAAlB;AAAA,OAAlB,CAAnB;AACA,UAAMO,QAAQ,GAAGN,CAAC,CAACE,UAAF,CAAaK,MAAb,CAAoB,UAACH,CAAD;AAAA,eAAOA,CAAC,CAACC,IAAF,KAAWN,GAAlB;AAAA,OAApB,CAAjB;AAEA,UAAIS,kBAAkB,GAAGX,eAAe,CAACI,UAAD,oBAACA,UAAU,CAAER,KAAb,CAAxC;;AAEA,UAAI,CAACe,kBAAL,EAAyB;AACvBA,QAAAA,kBAA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IAAI,EAAE,iCAAqBqF,QAAQ,CAACrF,IAA9B,CADD;AAELuG,QAAAA,EAAE,EAAEb,QAAQ,CAACC,UAAT,IAAuB,EAFtB;AAGLa,QAAAA,IAAI,QAAM,iCAAqBnB,QAAQ,CAACoB,IAA9B,CAAN;AAHC,OAAP;AAKD;;AAED,QAAMrB,GAAG,GAAIM,QAAb;AAEA,WAAO;AACL1F,MAAAA,IAAI,EAAE,iCAAqBoF,GAAG,CAACpF,IAAzB,CADD;AAELuG,MAAAA,EAAE,EAAEnB,GAAG,CAACa,GAAJ,IAAW,EAFV;AAGLO,MAAAA,IAAI,QAAM,iCAAqBpB,GAAG,CAACqB,IAAzB,CAAN;AAHC,KAAP;AAKD,GAlBwB,CAAzB;AAoBA,SAAOH,gBAAgB,IAAI,EAA3B;AACD,CA1FM;;;;AA4FA,IAAMI,eAAe,GAAG,SAAlBA,eAAkB,CAAC3F,IAAD,EAAqC;AAClE;AACA,MAAM4F,GAAG,GAAG,IAAIC,IAAJ,GAAWC,OAAX,EAAZ;AAEA,MAAMC,aAAa,GAAG/F,IAAH,oBAAGA,IAAI,CAAEb,MAAN,CAAa,UAAC6G,EAAD,EAAQ;AACzC,QAAI,CAACA,EAAE,CAACC,SAAJ,IAAiB,CAACD,EAAE,CAACE,OAAzB,EAAkC;AAChC,aAAOF,EAAP;AACD,KAFD,MAEO;AACL,aAAOA,EAAE,CAACC,SAAH,GAAeL,GAAf,IAAsBI,EAAE,CAACE,OAAH,GAAaN,GAA1C;AACD;AACF,GANqB,CAAtB;AAQA,SAAOG,aAAP,oBAAOA,aAAa,CAAE7H,GAAf,CAAmB,UAAC8H,EAAD;AAAA,WAAQA,EAAE,CAACrH,GAAX;AAAA,GAAnB,CAAP;AACD,CAbM","sourcesContent":["import {\n ProductAttributeDTO,\n CustomField,\n AttributeRuleDTOConstraintEnum,\n ProductDTO,\n ProductVariantDTO,\n InventoryAvailability,\n OptionDefinitionDTO,\n SelectedOptionDTO,\n IdReferenceDTO,\n CategoryDTO,\n ProductVariantLabelDTO,\n} from '@sentecacommerce/sdk'\n\nimport {\n AttributeRulesMap,\n CombinationsMap,\n BooleanKVP,\n InventoryAvailabilityType,\n MetaInformationType,\n OptionsType,\n} from '../index'\n\nimport { createEmbededVideo } from './createEmbededVideo'\n\nimport { getTranslatableField } from '../../../utils'\n\n// export const createMappedInventory = (\n// currentVariant: ProductVariantDraftDTO,\n// inventory?: SkuReservationResponseDTO\n// ) => {\n// const currentInventory = inventory?.find(\n// (x) => x.sku === currentVariant.sku\n// )\n\n// const mappedInventory = {\n// ...currentInventory,\n// status:\n// currentInventory?.status === SkuReservationDTOStatusEnum.Available\n// ? true\n// : false,\n// inventoryId: currentInventory?.inventoryReservations?.[0].inventoryId,\n// quantity: currentInventory?.inventoryReservations?.[0].quantity,\n// }\n\n// return mappedInventory\n// }\n\nexport const createCustomFieldsMap = (customFields?: CustomField[]) => {\n return customFields?.reduce((map: BooleanKVP, currentObj) => {\n map[currentObj.field] = currentObj.value\n return map\n }, {})\n}\n\nexport const createCombinationsMap = (\n mappedAttributeRulesKeys: string[],\n attributesArray: {\n variantId: string\n attributes: ProductAttributeDTO[]\n }[]\n) => {\n const combinationsMap: CombinationsMap = {}\n mappedAttributeRulesKeys.forEach((key) => {\n attributesArray.forEach((p) => {\n const currentKey = p.attributes.find((x) => x.name === key)\n const filtered = p.attributes.filter((x) => x.name !== key)\n\n let currentCombination = combinationsMap[currentKey?.value]\n\n if (!currentCombination) {\n currentCombination = {\n params: {},\n value: '',\n }\n }\n\n currentCombination.value = p.variantId\n\n filtered.forEach((attribute) => {\n currentCombination.params = {\n ...currentCombination.params,\n [attribute.value]: p.variantId,\n }\n })\n\n combinationsMap[currentKey?.value] = currentCombination\n })\n })\n\n return combinationsMap\n}\n\nexport const assignCombinationsToAttributeRules = (\n mappedAttributeRules: AttributeRulesMap,\n combinationsMap: CombinationsMap\n) => {\n Object.keys(mappedAttributeRules).forEach((key) => {\n const current = mappedAttributeRules[key].values\n Object.keys(current).forEach((currentKey) => {\n mappedAttributeRules[key].values[currentKey].combinations =\n combinationsMap[currentKey]?.params\n })\n })\n}\n\nexport const createProductContent = (\n data: any\n): { key: string; name: string; content: string } => {\n return {\n key: data.key,\n name: getTranslatableField(data.label),\n content: getTranslatableField(data.content),\n }\n}\n\n// Add grouped images for SD color variants\nexport const createCollapseKeyImagesMap = (product?: ProductDTO) => {\n const mappedKeys = product?.variants?.reduce((res, cur) => {\n if (!res[cur.collapseKey as string]) {\n res[cur.collapseKey as string] = []\n }\n res[cur.collapseKey as string].push(cur)\n return res\n }, {})\n\n return mappedKeys\n}\n\nexport const createAttributeRulesMap = (product?: ProductDTO) => {\n const uniqueRules = product?.attributeRules?.filter(\n (x) => x.constraint === AttributeRuleDTOConstraintEnum.CombinationUnique\n )\n const reduceVariantsToAttributeRuleValues = (map: any, attribute: any) => {\n const found = uniqueRules?.find((x) => x.attributeName === attribute.name)\n if (found) {\n if (!map[attribute.name]) {\n map[attribute.name] = {\n ...found,\n label: getTranslatableField(attribute.data.label),\n values: {},\n }\n }\n\n map[attribute.name] = {\n ...map[attribute.name],\n values: {\n ...map[attribute.name].values,\n [attribute.value]: {\n label: getTranslatableField(attribute.valueData.label),\n extra: attribute.valueData.extra,\n },\n },\n }\n }\n\n return map\n }\n\n const mappedAttributeRules = product?.variants\n ?.map((v) => v.attributes)\n .flat()\n .reduce(reduceVariantsToAttributeRuleValues, {})\n\n return mappedAttributeRules\n}\n\nexport const createMappedOptions = (\n options?: OptionDefinitionDTO[]\n): OptionsType[] => {\n const mappedOptions =\n options?.map((currentOption) => {\n return {\n definitionKey: currentOption.key,\n label: getTranslatableField(currentOption?.label),\n elements: currentOption.options?.map((subOption) => {\n return {\n optionKey: subOption.key,\n label: getTranslatableField(subOption?.label),\n imageIndex: subOption?.imageIndex,\n }\n }),\n }\n }) || []\n\n return mappedOptions\n}\n\nexport type SelectedOptionType = {\n label?: string\n value?: { key?: string; label?: string; imageIndex?: number }\n}\n\nexport const createSelectedOption2 = (\n options?: OptionsType[],\n selectedOption?: SelectedOptionDTO\n): SelectedOptionType => {\n const currentOption = options?.find(\n (availableOption) =>\n availableOption.definitionKey === selectedOption?.definitionKey\n )\n\n const value = currentOption?.elements?.find(\n (element) => element.optionKey === selectedOption?.optionKey\n )\n\n return {\n label: currentOption?.label,\n value: {\n key: value?.optionKey,\n imageIndex: value?.imageIndex,\n label: value?.label,\n },\n }\n}\n\nexport const createSelectedOption = (\n options?: OptionDefinitionDTO[],\n selectedOption?: SelectedOptionDTO\n): SelectedOptionType => {\n const currentOption = options?.find(\n (availableOption) => availableOption.key === selectedOption?.definitionKey\n )\n\n const value = currentOption?.options?.find(\n (optionValue) => optionValue.key === selectedOption?.optionKey\n )\n\n return {\n label: getTranslatableField(currentOption?.label),\n value: {\n key: value?.key,\n imageIndex: value?.imageIndex,\n label: getTranslatableField(value?.label),\n },\n }\n}\n\nexport const createMappedAttributes = (currentVariant: ProductVariantDTO) => {\n const mappedAttributes =\n currentVariant.attributes?.reduce(\n (attributeArray: ProductAttributeDTO[], attribute) => {\n attributeArray.push({\n name: attribute.name,\n value: attribute.value,\n valueData: attribute.valueData,\n })\n return attributeArray\n },\n []\n ) || []\n\n return mappedAttributes\n}\n\nexport const processAvailabilityPerStore = (\n availabilities?: InventoryAvailability[]\n): InventoryAvailabilityType[] | undefined => {\n return availabilities\n ?.filter((x) => !x.isPhysical)\n ?.map(\n ({\n acceptsBackorders,\n stockLocationName,\n restockableInDays,\n availableQuantity,\n }) => {\n return {\n storeName: getTranslatableField(stockLocationName),\n availableQuantity,\n acceptsBackorders,\n restockableInDays: restockableInDays,\n }\n }\n )\n}\n\nexport const getProductVideos = (assets: MetaInformationType['assets']) => {\n if (assets?.youtube) {\n const videos = assets.youtube.sources.map((a) => {\n const embeded = createEmbededVideo(a)\n return {\n type: 'video',\n source: a.url,\n iframe: embeded.iframe,\n thumb: { url: embeded.thumbnail },\n }\n })\n\n return videos\n }\n return []\n}\n\nexport const formatCategories = (\n categories?: IdReferenceDTO[],\n rootCategoryId?: string\n) => {\n let results\n\n if (\n categories?.some((cat) =>\n cat.resource?.custom?.some(\n (customField: any) => customField.field === 'isTemporary'\n )\n )\n ) {\n type PathType = {\n [key: string]: string\n }\n type CategoryType = CategoryDTO & { hasChildCategories: boolean }\n\n const cats = categories.reduce((result, category) => {\n result[category.resourceId] = {\n ...category.resource,\n hasChildCategories: false,\n }\n\n return result\n }, {} as CategoryDTO[])\n\n const paths = Object.values(cats).reduce((result, category) => {\n const parents = (category?.ancestors as IdReferenceDTO[])\n .map((parent: any) => {\n return (cats?.[parent?.resourceId] as any)?._id\n })\n .filter(Boolean)\n\n parents.forEach((parent: any) => {\n ;(cats as CategoryType[])[parent].hasChildCategories = true\n })\n\n result[category._id as string] = [...parents, category._id]\n\n return result\n }, {} as PathType[])\n\n const mainPaths = Object.values(cats as CategoryType[] & IdReferenceDTO[])\n .filter((category: CategoryType) => category.hasChildCategories === false)\n .map((category) => paths?.[category._id as string])\n .map((paths) => paths.map((path: string) => cats?.[path]))\n .filter(\n (paths) =>\n !paths.some(\n (path: { custom: any }) =>\n path?.custom?.find(\n (custom: any) => custom.field === 'isTemporary'\n )?.value ?? false\n )\n )?.[0]\n .flat()\n\n results = mainPaths\n } else {\n results = categories?.filter(\n (cat) =>\n cat?.resourceId === rootCategoryId ||\n cat?.resource?.ancestors?.some(\n (ancestor: any) => ancestor.resource === rootCategoryId\n )\n )\n }\n\n const formattedResults = (results as IdReferenceDTO[])?.map((category) => {\n if (category.resource) {\n const resource = category.resource as CategoryDTO\n\n return {\n name: getTranslatableField(resource.name),\n id: category.resourceId || '',\n link: `/${getTranslatableField(resource.slug)}/c`,\n }\n }\n\n const cat = (category as unknown) as CategoryDTO\n\n return {\n name: getTranslatableField(cat.name),\n id: cat._id || '',\n link: `/${getTranslatableField(cat.slug)}/c`,\n }\n })\n\n return formattedResults || []\n}\n\nexport const createLabelsMap = (data?: ProductVariantLabelDTO[]) => {\n // Filter only labels that are currently active\n const now = new Date().getTime()\n\n const currentLabels = data?.filter((el) => {\n if (!el.validFrom || !el.validTo) {\n return el\n } else {\n return el.validFrom < now && el.validTo > now\n }\n })\n\n return currentLabels?.map((el) => el.key)\n}\n"],"file":"index.js"}
|
@@ -39,7 +39,7 @@ export function CheckoutFormContextProvider(_ref) {
|
|
39
39
|
isBoricaInDevMode,
|
40
40
|
withPixelMeta = false,
|
41
41
|
requiredFieldsOnShippingStep = ['firstName', 'lastName', 'email', 'phoneNumber'],
|
42
|
-
requiredFieldsOnBillingAddressStep = ['
|
42
|
+
requiredFieldsOnBillingAddressStep = ['vatId', 'companyId', 'companyPerson', 'companyName'],
|
43
43
|
enableNoShippingMethodMode = false,
|
44
44
|
disablePaymentRedirects = false
|
45
45
|
} = _ref;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../../src/contexts/CheckoutForm/index.tsx"],"names":["React","createContext","useCallback","useContext","useMemo","useState","myCartApi","useBilling","usePayment","useShipping","useIsAuthenticated","useCheckoutSubmit","defaultShippingValidations","genericBillingAddressValidation","usersApi","useCheckoutShippingModule","CheckoutFormCustomStateProvider","BoricaRedirect","useScrollTo","getElementOffset","CheckoutFormContext","CheckoutFormContextProvider","children","defaultStep","errorLabels","enableSavedAddressList","withPersistBeforePageLeave","shippingValidations","validateBillingAddress","enableSaveBillingAddress","enableSavedBillingAddressList","countryCode","enableSaveAddress","autofillShippingPersonalData","onSubmit","paymentEnabledOnStep","getPaymentMethodsWhenShippingMethodIsSelected","shippingEnabledOnStep","billingEnabledOnStep","customState","initialCustomState","redirectTimeout","onBeforeRedirect","onSuccess","onError","isBoricaInDevMode","withPixelMeta","requiredFieldsOnShippingStep","requiredFieldsOnBillingAddressStep","enableNoShippingMethodMode","disablePaymentRedirects","orderQuery","useGet","boricaData","setBoricaData","step","setStep","isRedirecting","setIsRedirecting","fieldsWithError","serverErrors","setServerErrors","collectFieldsWithError","error","push","handleStepChange","newStep","window","scrollTo","updateServerErrors","errors","formattedErrors","reduce","data","code","response","internalError","isAuthenticated","isShippingEnabled","userQuery","enabled","shippingState","Boolean","validations","requiredFields","mod","getIsPaymentMethodsEnabled","moduleKey","moduleData","methodKey","paymentState","billingState","withSavedBillingAddressList","requiredFieldsOnShipping","onBeforeBoricaRedirect","setTimeout","onBeforePaypalRedirect","location","replace","redirectUrl","handleCheckoutSubmit","withMeta","scrollToFirstError","interval","setInterval","errorElement","top","clearInterval","handleSubmit","e","preventDefault","Promise","all","persistShippingAddress","persistBillingAddress","catch","isShippingValid","isValid","setIsShippingSubmitting","updateIsSubmitting","isBillingValid","setIsBillingSubmitting","isPaymentValid","setIsPaymentSubmitting","updateStep","saveOrder","shippingAddress","state","errorRef","errorFields","CheckoutFormStepsEnum","useCheckoutFormStep","context","Error","currentStep","useCheckoutFormOrder","useCheckoutFormErrorLabels","useCheckoutFormServerErrors","useCheckoutFormBillingState","useCheckoutFormShippingState","useCheckoutErrorFields","useCheckoutFormPaymentState"],"mappings":";;AAAA,OAAOA,KAAP,IACEC,aADF,EAEEC,WAFF,EAGEC,UAHF,EAIEC,OAJF,EAKEC,QALF,QAMO,OANP;AAcA,SAASC,SAAT,QAA0B,qBAA1B;AACA,SACEC,UADF,EAGEC,UAHF,EAKEC,WALF,QAOO,SAPP;AAQA,SAASC,kBAAT,QAAmC,kBAAnC;AACA,SAASC,iBAAT,QAAkC,+BAAlC;AAEA,SAEEC,0BAFF,EAGEC,+BAHF,QAKO,SALP;AAMA,SAASC,QAAT,QAAyB,oBAAzB;AACA,SAASC,yBAAT,QAA0C,uCAA1C;AACA,SAASC,+BAAT,EAA0CC,cAA1C,QAAgE,cAAhE;AACA,SAASC,WAAT,QAA4B,sBAA5B;AACA,SAASC,gBAAT,QAAiC,8BAAjC;AAEA,OAAO,IAAMC,mBAAmB,gBAAGnB,aAAa,CAC9C,EAD8C,CAAzC;AAMP,OAAO,SAASoB,2BAAT,OAoCG;AAAA,MApCkC;AAC1CC,IAAAA,QAD0C;AAE1CC,IAAAA,WAF0C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G,MAAM;AAChD,MAAMP,OAAO,GAAGjI,UAAU,CAACiB,mBAAD,CAA1B;;AAEA,MAAI,CAACgH,OAAL,EAAc;AACZ,UAAM,IAAIC,KAAJ,CACJ,gFADI,CAAN;AAGD;;AAED,SAAOD,OAAO,CAACnD,aAAf;AACD,CAVM;AAYP,OAAO,IAAM2D,sBAAsB,GAAG,MAAM;AAC1C,MAAMR,OAAO,GAAGjI,UAAU,CAACiB,mBAAD,CAA1B;;AAEA,MAAI,CAACgH,OAAL,EAAc;AACZ,UAAM,IAAIC,KAAJ,CACJ,0EADI,CAAN;AAGD;;AAED,SAAO;AACLJ,IAAAA,WAAW,EAAEG,OAAO,CAACH,WADhB;AAELD,IAAAA,QAAQ,EAAEI,OAAO,CAACJ;AAFb,GAAP;AAID,CAbM;AAeP,OAAO,IAAMa,2BAA2B,GAAG,MAAM;AAC/C,MAAMT,OAAO,GAAGjI,UAAU,CAACiB,mBAAD,CAA1B;;AAEA,MAAI,CAACgH,OAAL,EAAc;AACZ,UAAM,IAAIC,KAAJ,CACJ,+EADI,CAAN;AAGD;;AAED,SAAOD,OAAO,CAAC1C,YAAf;AACD,CAVM","sourcesContent":["import React, {\n createContext,\n useCallback,\n useContext,\n useMemo,\n useState,\n} from 'react'\nimport {\n BoricaGeneratePaymentDataResponse,\n OrderDTO,\n AddressDTO,\n PaypalGeneratePaymentUrlResponseDTO,\n} from '@sentecacommerce/sdk'\nimport { MutateFunction, QueryResult } from 'react-query'\nimport { myCartApi } from '../../api/myCartApi'\nimport {\n useBilling,\n UseBillingResultType,\n usePayment,\n UsePaymentResultType,\n useShipping,\n UseShippingResultType,\n} from './hooks'\nimport { useIsAuthenticated } from '../../user/hooks'\nimport { useCheckoutSubmit } from '../../hooks/useCheckoutSubmit'\n\nimport {\n ShippingValidationsType,\n defaultShippingValidations,\n genericBillingAddressValidation,\n BillingAddressValidationType,\n} from './utils'\nimport { usersApi } from '../../api/usersApi'\nimport { useCheckoutShippingModule } from '../../hooks/useCheckoutShippingModule'\nimport { CheckoutFormCustomStateProvider, BoricaRedirect } from './Components'\nimport { useScrollTo } from '../../hooks/ui-hooks'\nimport { getElementOffset } from '../../utils/getElementOffset'\n\nexport const CheckoutFormContext = createContext<CheckoutFormContextType>(\n {} as any\n)\n\nexport type CheckoutCustomState = {}\n\nexport function CheckoutFormContextProvider({\n children,\n defaultStep,\n errorLabels,\n enableSavedAddressList,\n withPersistBeforePageLeave,\n shippingValidations = defaultShippingValidations,\n validateBillingAddress = genericBillingAddressValidation,\n enableSaveBillingAddress,\n enableSavedBillingAddressList,\n countryCode,\n enableSaveAddress,\n autofillShippingPersonalData,\n onSubmit,\n\n paymentEnabledOnStep,\n getPaymentMethodsWhenShippingMethodIsSelected,\n shippingEnabledOnStep,\n billingEnabledOnStep,\n\n customState: initialCustomState = {},\n redirectTimeout = 420,\n onBeforeRedirect,\n onSuccess,\n onError,\n isBoricaInDevMode,\n withPixelMeta = false,\n requiredFieldsOnShippingStep = [\n 'firstName',\n 'lastName',\n 'email',\n 'phoneNumber',\n ],\n requiredFieldsOnBillingAddressStep = ['city', 'postalCode', 'streetName'],\n enableNoShippingMethodMode = false,\n disablePaymentRedirects = false,\n}: Props) {\n const orderQuery = myCartApi.useGet()\n const [\n boricaData,\n setBoricaData,\n ] = useState<BoricaGeneratePaymentDataResponse | null>(null)\n const [step, setStep] = useState<CheckoutFormStepsEnum>(defaultStep)\n const [isRedirecting, setIsRedirecting] = useState(false)\n\n const fieldsWithError: HTMLElement[] = []\n\n const [serverErrors, setServerErrors] = useState<ServerErrors>(null)\n\n const collectFieldsWithError = (error: HTMLElement) => {\n fieldsWithError.push(error)\n }\n\n const handleStepChange = useCallback((newStep: CheckoutFormStepsEnum) => {\n window.scrollTo(0, 0)\n\n setStep(newStep)\n }, [])\n\n const updateServerErrors = useCallback((errors: any[]) => {\n // Example Error\n // [{\n // code: \"OutOfStock\"\n // message: \"Some of the ordered line items are out of stock at the time of placing the order.\"\n // responses: {\n // availableQuantity: 1\n // sku: \"200000095849\"\n // status: \"unavailable\"\n // }\n // }]\n const formattedErrors = errors?.reduce?.(\n (data: ServerErrors, error: any) => {\n return {\n ...data,\n [error?.code || 'internal']: error?.response,\n }\n },\n {}\n )\n setServerErrors(formattedErrors || { internalError: errors })\n }, [])\n\n const { isAuthenticated } = useIsAuthenticated()\n\n const isShippingEnabled = shippingEnabledOnStep === step\n\n const userQuery = usersApi.useGet(\n {},\n { enabled: isShippingEnabled && autofillShippingPersonalData }\n )\n\n const shippingState = useShipping({\n errorLabels,\n orderQuery,\n enableSavedAddressList: Boolean(isAuthenticated && enableSavedAddressList),\n enableSaveAddress: Boolean(isAuthenticated && enableSaveAddress),\n withPersistBeforePageLeave: !isRedirecting && withPersistBeforePageLeave,\n validations: shippingValidations,\n autofillShippingPersonalData: Boolean(\n isAuthenticated && autofillShippingPersonalData\n ),\n userQuery,\n enabled: isShippingEnabled,\n countryCode,\n requiredFields: requiredFieldsOnShippingStep,\n enableNoShippingMethodMode,\n })\n const mod = useCheckoutShippingModule(orderQuery, !enableNoShippingMethodMode)\n\n const getIsPaymentMethodsEnabled = () => {\n if (paymentEnabledOnStep) {\n return paymentEnabledOnStep === step\n }\n\n if (\n !enableNoShippingMethodMode &&\n getPaymentMethodsWhenShippingMethodIsSelected\n ) {\n return Boolean(mod?.moduleKey && mod?.moduleData.methodKey)\n }\n\n return false\n }\n\n const paymentState = usePayment({\n errorLabels,\n orderQuery,\n enabled: getIsPaymentMethodsEnabled(),\n })\n\n const billingState = useBilling({\n errorLabels,\n orderQuery,\n validateBillingAddress,\n enableSaveBillingAddress: Boolean(\n isAuthenticated && enableSaveBillingAddress\n ),\n withSavedBillingAddressList: Boolean(\n isAuthenticated && enableSavedBillingAddressList\n ),\n withPersistBeforePageLeave: !isRedirecting && withPersistBeforePageLeave,\n countryCode,\n enabled: billingEnabledOnStep === step,\n requiredFields: requiredFieldsOnBillingAddressStep,\n requiredFieldsOnShipping: requiredFieldsOnShippingStep,\n })\n\n const onBeforeBoricaRedirect = (data: BoricaGeneratePaymentDataResponse) => {\n if (disablePaymentRedirects) return\n\n onBeforeRedirect?.()\n setIsRedirecting(true)\n setTimeout(() => {\n setBoricaData(data)\n }, redirectTimeout)\n }\n\n const onBeforePaypalRedirect = (\n data: PaypalGeneratePaymentUrlResponseDTO\n ) => {\n if (disablePaymentRedirects) return\n\n onBeforeRedirect?.()\n setIsRedirecting(true)\n setTimeout(() => {\n window.location.replace(data.redirectUrl)\n }, redirectTimeout)\n }\n const { handleCheckoutSubmit } = useCheckoutSubmit({\n onBeforeBoricaRedirect,\n onBeforePaypalRedirect,\n onSuccess,\n onError: (errors: any) => {\n updateServerErrors(errors)\n onError(errors)\n },\n withMeta: withPixelMeta,\n disablePaymentRedirects,\n })\n\n const { scrollTo } = useScrollTo(fieldsWithError[0], 0)\n\n const scrollToFirstError = () => {\n const interval = setInterval(() => {\n const errorElement = fieldsWithError[0]\n if (!errorElement) return\n\n scrollTo(getElementOffset(errorElement).top - 100)\n clearInterval(interval)\n }, 50)\n\n setTimeout(() => {\n clearInterval(interval)\n }, 1000)\n }\n\n const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {\n e.preventDefault()\n\n await Promise.all([\n shippingState.persistShippingAddress(),\n billingState.persistBillingAddress(),\n ]).catch(() => {})\n\n onSubmit({\n isShippingValid: shippingState.isValid,\n setIsShippingSubmitting: shippingState.updateIsSubmitting,\n isBillingValid: billingState.isValid,\n setIsBillingSubmitting: billingState.updateIsSubmitting,\n isPaymentValid: paymentState.isValid,\n setIsPaymentSubmitting: paymentState.updateIsSubmitting,\n step,\n updateStep: setStep,\n saveOrder: handleCheckoutSubmit,\n updateServerErrors,\n scrollToFirstError,\n shippingState,\n shippingAddress: shippingState.data,\n })\n }\n\n const state = {\n setStep: handleStepChange,\n step,\n orderQuery,\n serverErrors,\n updateServerErrors,\n errorLabels,\n shippingState,\n paymentState,\n billingState,\n errorRef: collectFieldsWithError,\n errorFields: fieldsWithError,\n }\n\n return (\n <CheckoutFormContext.Provider value={state}>\n <CheckoutFormCustomStateProvider initialCustomState={initialCustomState}>\n <>\n <form noValidate onSubmit={handleSubmit}>\n {children}\n </form>\n {!!boricaData && (\n <BoricaRedirect\n isInDevMode={isBoricaInDevMode}\n formData={boricaData}\n />\n )}\n </>\n </CheckoutFormCustomStateProvider>\n </CheckoutFormContext.Provider>\n )\n}\n\nexport type CheckoutFormOnSubmitData = {\n isShippingValid: boolean\n setIsShippingSubmitting: (value: boolean) => void\n isBillingValid: boolean\n setIsBillingSubmitting: (value: boolean) => void\n isPaymentValid: boolean\n setIsPaymentSubmitting: (value: boolean) => void\n step: CheckoutFormStepsEnum\n updateStep: (step: CheckoutFormStepsEnum) => void\n saveOrder: MutateFunction<OrderDTO, unknown, any, unknown>\n\n updateServerErrors: (errors: any) => void\n scrollToFirstError: () => void\n shippingState: UseShippingResultType\n shippingAddress?: AddressDTO\n}\n\ntype Props = {\n children: any\n defaultStep: CheckoutFormStepsEnum\n errorLabels: CheckoutFormErrorLabelsType\n withPersistBeforePageLeave: boolean\n countryCode: string\n onSubmit: (data: CheckoutFormOnSubmitData) => void\n onError: (error: any) => void\n onSuccess: (order: OrderDTO) => void\n\n redirectTimeout?: number\n onBeforeRedirect?: () => void\n\n customState?: CheckoutCustomState\n\n enableSavedAddressList: boolean\n shippingValidations?: ShippingValidationsType\n enableSaveAddress: boolean\n autofillShippingPersonalData: boolean\n autoSelectDefaultShippingAddress: boolean\n\n enableSaveBillingAddress: boolean\n validateBillingAddress?: BillingAddressValidationType\n enableSavedBillingAddressList: boolean\n autoSelectDefaultBillingAddress: boolean\n\n paymentEnabledOnStep?: CheckoutFormStepsEnum\n getPaymentMethodsWhenShippingMethodIsSelected?: boolean\n\n shippingEnabledOnStep: CheckoutFormStepsEnum\n\n billingEnabledOnStep: CheckoutFormStepsEnum\n\n isBoricaInDevMode?: boolean\n\n withPixelMeta?: boolean\n requiredFieldsOnShippingStep?: string[]\n requiredFieldsOnBillingAddressStep?: string[]\n enableNoShippingMethodMode?: boolean\n disablePaymentRedirects?: boolean\n}\n\ntype ServerErrors = { [key: string]: any } | null\n\nexport enum CheckoutFormStepsEnum {\n Basket = 'Basket',\n Shipping = 'Shipping',\n BillingAddress = 'BillingAddress',\n Payment = 'Payment',\n Preview = 'Preview',\n All = 'All',\n}\n\nexport type CheckoutFormErrorsResultType =\n | {\n [key: string]: string\n }\n | null\n | undefined\n\nexport type ShippingFormErrorLabels = {\n fieldIsRequired: string\n fillStreetNumberBuildingEntranceOrApartment: string\n streetIsRequired: string\n invalidPhoneNumber?: string\n quarterIsRequired: string\n cantFindStreetOrQuarterMessage: string\n cityIsRequired: string\n emailIsRequired: string\n officeIsRequired: string\n selectCourier: string\n noStoreSelected: string\n}\n\nexport type CheckoutFormErrorLabelsType = ShippingFormErrorLabels & {\n selectPaymentMethod: string\n}\n\nexport type CheckoutFormContextType = {\n setStep: (step: CheckoutFormStepsEnum) => void\n step: CheckoutFormStepsEnum\n serverErrors: ServerErrors\n updateServerErrors: (errors: any) => void\n errorRef: (error: HTMLElement) => void\n errorFields: HTMLElement[]\n errorLabels: CheckoutFormErrorLabelsType\n orderQuery: QueryResult<OrderDTO, unknown>\n shippingState: UseShippingResultType\n paymentState: UsePaymentResultType\n billingState: UseBillingResultType\n}\n\nexport const useCheckoutFormStep = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormStep must be used within a CheckoutFormContextProvider'\n )\n }\n\n return useMemo(() => {\n return {\n currentStep: context.step,\n updateStep: context.setStep,\n }\n }, [context])\n}\n\nexport const useCheckoutFormOrder = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormOrder must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.orderQuery\n}\n\nexport const useCheckoutFormErrorLabels = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormErrorLabels must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.errorLabels\n}\n\nexport const useCheckoutFormServerErrors = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormServerErrors must be used within a CheckoutFormContextProvider'\n )\n }\n\n return useMemo(() => {\n return {\n serverErrors: context.serverErrors,\n updateServerErrors: context.updateServerErrors,\n }\n }, [context])\n}\n\nexport const useCheckoutFormBillingState = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormBillingState must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.billingState\n}\n\nexport const useCheckoutFormShippingState = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormShippingState must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.shippingState\n}\n\nexport const useCheckoutErrorFields = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutErrorFields must be used within a CheckoutFormContextProvider'\n )\n }\n\n return {\n errorFields: context.errorFields,\n errorRef: context.errorRef,\n }\n}\n\nexport const useCheckoutFormPaymentState = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormPaymentState must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.paymentState\n}\n"],"file":"index.js"}
|
1
|
+
{"version":3,"sources":["../../../../src/contexts/CheckoutForm/index.tsx"],"names":["React","createContext","useCallback","useContext","useMemo","useState","myCartApi","useBilling","usePayment","useShipping","useIsAuthenticated","useCheckoutSubmit","defaultShippingValidations","genericBillingAddressValidation","usersApi","useCheckoutShippingModule","CheckoutFormCustomStateProvider","BoricaRedirect","useScrollTo","getElementOffset","CheckoutFormContext","CheckoutFormContextProvider","children","defaultStep","errorLabels","enableSavedAddressList","withPersistBeforePageLeave","shippingValidations","validateBillingAddress","enableSaveBillingAddress","enableSavedBillingAddressList","countryCode","enableSaveAddress","autofillShippingPersonalData","onSubmit","paymentEnabledOnStep","getPaymentMethodsWhenShippingMethodIsSelected","shippingEnabledOnStep","billingEnabledOnStep","customState","initialCustomState","redirectTimeout","onBeforeRedirect","onSuccess","onError","isBoricaInDevMode","withPixelMeta","requiredFieldsOnShippingStep","requiredFieldsOnBillingAddressStep","enableNoShippingMethodMode","disablePaymentRedirects","orderQuery","useGet","boricaData","setBoricaData","step","setStep","isRedirecting","setIsRedirecting","fieldsWithError","serverErrors","setServerErrors","collectFieldsWithError","error","push","handleStepChange","newStep","window","scrollTo","updateServerErrors","errors","formattedErrors","reduce","data","code","response","internalError","isAuthenticated","isShippingEnabled","userQuery","enabled","shippingState","Boolean","validations","requiredFields","mod","getIsPaymentMethodsEnabled","moduleKey","moduleData","methodKey","paymentState","billingState","withSavedBillingAddressList","requiredFieldsOnShipping","onBeforeBoricaRedirect","setTimeout","onBeforePaypalRedirect","location","replace","redirectUrl","handleCheckoutSubmit","withMeta","scrollToFirstError","interval","setInterval","errorElement","top","clearInterval","handleSubmit","e","preventDefault","Promise","all","persistShippingAddress","persistBillingAddress","catch","isShippingValid","isValid","setIsShippingSubmitting","updateIsSubmitting","isBillingValid","setIsBillingSubmitting","isPaymentValid","setIsPaymentSubmitting","updateStep","saveOrder","shippingAddress","state","errorRef","errorFields","CheckoutFormStepsEnum","useCheckoutFormStep","context","Error","currentStep","useCheckoutFormOrder","useCheckoutFormErrorLabels","useCheckoutFormServerErrors","useCheckoutFormBillingState","useCheckoutFormShippingState","useCheckoutErrorFields","useCheckoutFormPaymentState"],"mappings":";;AAAA,OAAOA,KAAP,IACEC,aADF,EAEEC,WAFF,EAGEC,UAHF,EAIEC,OAJF,EAKEC,QALF,QAMO,OANP;AAcA,SAASC,SAAT,QAA0B,qBAA1B;AACA,SACEC,UADF,EAGEC,UAHF,EAKEC,WALF,QAOO,SAPP;AAQA,SAASC,kBAAT,QAAmC,kBAAnC;AACA,SAASC,iBAAT,QAAkC,+BAAlC;AAEA,SAEEC,0BAFF,EAGEC,+BAHF,QAKO,SALP;AAMA,SAASC,QAAT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,OAAO,CAAC/D;AAFvB,KAAP;AAID,GALa,EAKX,CAAC+D,OAAD,CALW,CAAd;AAMD,CAfM;AAiBP,OAAO,IAAMM,2BAA2B,GAAG,MAAM;AAC/C,MAAMN,OAAO,GAAGjI,UAAU,CAACiB,mBAAD,CAA1B;;AAEA,MAAI,CAACgH,OAAL,EAAc;AACZ,UAAM,IAAIC,KAAJ,CACJ,+EADI,CAAN;AAGD;;AAED,SAAOD,OAAO,CAACzC,YAAf;AACD,CAVM;AAYP,OAAO,IAAMgD,4BAA4B,GAAG,MAAM;AAChD,MAAMP,OAAO,GAAGjI,UAAU,CAACiB,mBAAD,CAA1B;;AAEA,MAAI,CAACgH,OAAL,EAAc;AACZ,UAAM,IAAIC,KAAJ,CACJ,gFADI,CAAN;AAGD;;AAED,SAAOD,OAAO,CAACnD,aAAf;AACD,CAVM;AAYP,OAAO,IAAM2D,sBAAsB,GAAG,MAAM;AAC1C,MAAMR,OAAO,GAAGjI,UAAU,CAACiB,mBAAD,CAA1B;;AAEA,MAAI,CAACgH,OAAL,EAAc;AACZ,UAAM,IAAIC,KAAJ,CACJ,0EADI,CAAN;AAGD;;AAED,SAAO;AACLJ,IAAAA,WAAW,EAAEG,OAAO,CAACH,WADhB;AAELD,IAAAA,QAAQ,EAAEI,OAAO,CAACJ;AAFb,GAAP;AAID,CAbM;AAeP,OAAO,IAAMa,2BAA2B,GAAG,MAAM;AAC/C,MAAMT,OAAO,GAAGjI,UAAU,CAACiB,mBAAD,CAA1B;;AAEA,MAAI,CAACgH,OAAL,EAAc;AACZ,UAAM,IAAIC,KAAJ,CACJ,+EADI,CAAN;AAGD;;AAED,SAAOD,OAAO,CAAC1C,YAAf;AACD,CAVM","sourcesContent":["import React, {\n createContext,\n useCallback,\n useContext,\n useMemo,\n useState,\n} from 'react'\nimport {\n BoricaGeneratePaymentDataResponse,\n OrderDTO,\n AddressDTO,\n PaypalGeneratePaymentUrlResponseDTO,\n} from '@sentecacommerce/sdk'\nimport { MutateFunction, QueryResult } from 'react-query'\nimport { myCartApi } from '../../api/myCartApi'\nimport {\n useBilling,\n UseBillingResultType,\n usePayment,\n UsePaymentResultType,\n useShipping,\n UseShippingResultType,\n} from './hooks'\nimport { useIsAuthenticated } from '../../user/hooks'\nimport { useCheckoutSubmit } from '../../hooks/useCheckoutSubmit'\n\nimport {\n ShippingValidationsType,\n defaultShippingValidations,\n genericBillingAddressValidation,\n BillingAddressValidationType,\n} from './utils'\nimport { usersApi } from '../../api/usersApi'\nimport { useCheckoutShippingModule } from '../../hooks/useCheckoutShippingModule'\nimport { CheckoutFormCustomStateProvider, BoricaRedirect } from './Components'\nimport { useScrollTo } from '../../hooks/ui-hooks'\nimport { getElementOffset } from '../../utils/getElementOffset'\n\nexport const CheckoutFormContext = createContext<CheckoutFormContextType>(\n {} as any\n)\n\nexport type CheckoutCustomState = {}\n\nexport function CheckoutFormContextProvider({\n children,\n defaultStep,\n errorLabels,\n enableSavedAddressList,\n withPersistBeforePageLeave,\n shippingValidations = defaultShippingValidations,\n validateBillingAddress = genericBillingAddressValidation,\n enableSaveBillingAddress,\n enableSavedBillingAddressList,\n countryCode,\n enableSaveAddress,\n autofillShippingPersonalData,\n onSubmit,\n\n paymentEnabledOnStep,\n getPaymentMethodsWhenShippingMethodIsSelected,\n shippingEnabledOnStep,\n billingEnabledOnStep,\n\n customState: initialCustomState = {},\n redirectTimeout = 420,\n onBeforeRedirect,\n onSuccess,\n onError,\n isBoricaInDevMode,\n withPixelMeta = false,\n requiredFieldsOnShippingStep = [\n 'firstName',\n 'lastName',\n 'email',\n 'phoneNumber',\n ],\n requiredFieldsOnBillingAddressStep = [\n 'vatId',\n 'companyId',\n 'companyPerson',\n 'companyName',\n ],\n enableNoShippingMethodMode = false,\n disablePaymentRedirects = false,\n}: Props) {\n const orderQuery = myCartApi.useGet()\n const [\n boricaData,\n setBoricaData,\n ] = useState<BoricaGeneratePaymentDataResponse | null>(null)\n const [step, setStep] = useState<CheckoutFormStepsEnum>(defaultStep)\n const [isRedirecting, setIsRedirecting] = useState(false)\n\n const fieldsWithError: HTMLElement[] = []\n\n const [serverErrors, setServerErrors] = useState<ServerErrors>(null)\n\n const collectFieldsWithError = (error: HTMLElement) => {\n fieldsWithError.push(error)\n }\n\n const handleStepChange = useCallback((newStep: CheckoutFormStepsEnum) => {\n window.scrollTo(0, 0)\n\n setStep(newStep)\n }, [])\n\n const updateServerErrors = useCallback((errors: any[]) => {\n // Example Error\n // [{\n // code: \"OutOfStock\"\n // message: \"Some of the ordered line items are out of stock at the time of placing the order.\"\n // responses: {\n // availableQuantity: 1\n // sku: \"200000095849\"\n // status: \"unavailable\"\n // }\n // }]\n const formattedErrors = errors?.reduce?.(\n (data: ServerErrors, error: any) => {\n return {\n ...data,\n [error?.code || 'internal']: error?.response,\n }\n },\n {}\n )\n setServerErrors(formattedErrors || { internalError: errors })\n }, [])\n\n const { isAuthenticated } = useIsAuthenticated()\n\n const isShippingEnabled = shippingEnabledOnStep === step\n\n const userQuery = usersApi.useGet(\n {},\n { enabled: isShippingEnabled && autofillShippingPersonalData }\n )\n\n const shippingState = useShipping({\n errorLabels,\n orderQuery,\n enableSavedAddressList: Boolean(isAuthenticated && enableSavedAddressList),\n enableSaveAddress: Boolean(isAuthenticated && enableSaveAddress),\n withPersistBeforePageLeave: !isRedirecting && withPersistBeforePageLeave,\n validations: shippingValidations,\n autofillShippingPersonalData: Boolean(\n isAuthenticated && autofillShippingPersonalData\n ),\n userQuery,\n enabled: isShippingEnabled,\n countryCode,\n requiredFields: requiredFieldsOnShippingStep,\n enableNoShippingMethodMode,\n })\n const mod = useCheckoutShippingModule(orderQuery, !enableNoShippingMethodMode)\n\n const getIsPaymentMethodsEnabled = () => {\n if (paymentEnabledOnStep) {\n return paymentEnabledOnStep === step\n }\n\n if (\n !enableNoShippingMethodMode &&\n getPaymentMethodsWhenShippingMethodIsSelected\n ) {\n return Boolean(mod?.moduleKey && mod?.moduleData.methodKey)\n }\n\n return false\n }\n\n const paymentState = usePayment({\n errorLabels,\n orderQuery,\n enabled: getIsPaymentMethodsEnabled(),\n })\n\n const billingState = useBilling({\n errorLabels,\n orderQuery,\n validateBillingAddress,\n enableSaveBillingAddress: Boolean(\n isAuthenticated && enableSaveBillingAddress\n ),\n withSavedBillingAddressList: Boolean(\n isAuthenticated && enableSavedBillingAddressList\n ),\n withPersistBeforePageLeave: !isRedirecting && withPersistBeforePageLeave,\n countryCode,\n enabled: billingEnabledOnStep === step,\n requiredFields: requiredFieldsOnBillingAddressStep,\n requiredFieldsOnShipping: requiredFieldsOnShippingStep,\n })\n\n const onBeforeBoricaRedirect = (data: BoricaGeneratePaymentDataResponse) => {\n if (disablePaymentRedirects) return\n\n onBeforeRedirect?.()\n setIsRedirecting(true)\n setTimeout(() => {\n setBoricaData(data)\n }, redirectTimeout)\n }\n\n const onBeforePaypalRedirect = (\n data: PaypalGeneratePaymentUrlResponseDTO\n ) => {\n if (disablePaymentRedirects) return\n\n onBeforeRedirect?.()\n setIsRedirecting(true)\n setTimeout(() => {\n window.location.replace(data.redirectUrl)\n }, redirectTimeout)\n }\n const { handleCheckoutSubmit } = useCheckoutSubmit({\n onBeforeBoricaRedirect,\n onBeforePaypalRedirect,\n onSuccess,\n onError: (errors: any) => {\n updateServerErrors(errors)\n onError(errors)\n },\n withMeta: withPixelMeta,\n disablePaymentRedirects,\n })\n\n const { scrollTo } = useScrollTo(fieldsWithError[0], 0)\n\n const scrollToFirstError = () => {\n const interval = setInterval(() => {\n const errorElement = fieldsWithError[0]\n if (!errorElement) return\n\n scrollTo(getElementOffset(errorElement).top - 100)\n clearInterval(interval)\n }, 50)\n\n setTimeout(() => {\n clearInterval(interval)\n }, 1000)\n }\n\n const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {\n e.preventDefault()\n\n await Promise.all([\n shippingState.persistShippingAddress(),\n billingState.persistBillingAddress(),\n ]).catch(() => {})\n\n onSubmit({\n isShippingValid: shippingState.isValid,\n setIsShippingSubmitting: shippingState.updateIsSubmitting,\n isBillingValid: billingState.isValid,\n setIsBillingSubmitting: billingState.updateIsSubmitting,\n isPaymentValid: paymentState.isValid,\n setIsPaymentSubmitting: paymentState.updateIsSubmitting,\n step,\n updateStep: setStep,\n saveOrder: handleCheckoutSubmit,\n updateServerErrors,\n scrollToFirstError,\n shippingState,\n shippingAddress: shippingState.data,\n })\n }\n\n const state = {\n setStep: handleStepChange,\n step,\n orderQuery,\n serverErrors,\n updateServerErrors,\n errorLabels,\n shippingState,\n paymentState,\n billingState,\n errorRef: collectFieldsWithError,\n errorFields: fieldsWithError,\n }\n\n return (\n <CheckoutFormContext.Provider value={state}>\n <CheckoutFormCustomStateProvider initialCustomState={initialCustomState}>\n <>\n <form noValidate onSubmit={handleSubmit}>\n {children}\n </form>\n {!!boricaData && (\n <BoricaRedirect\n isInDevMode={isBoricaInDevMode}\n formData={boricaData}\n />\n )}\n </>\n </CheckoutFormCustomStateProvider>\n </CheckoutFormContext.Provider>\n )\n}\n\nexport type CheckoutFormOnSubmitData = {\n isShippingValid: boolean\n setIsShippingSubmitting: (value: boolean) => void\n isBillingValid: boolean\n setIsBillingSubmitting: (value: boolean) => void\n isPaymentValid: boolean\n setIsPaymentSubmitting: (value: boolean) => void\n step: CheckoutFormStepsEnum\n updateStep: (step: CheckoutFormStepsEnum) => void\n saveOrder: MutateFunction<OrderDTO, unknown, any, unknown>\n\n updateServerErrors: (errors: any) => void\n scrollToFirstError: () => void\n shippingState: UseShippingResultType\n shippingAddress?: AddressDTO\n}\n\ntype Props = {\n children: any\n defaultStep: CheckoutFormStepsEnum\n errorLabels: CheckoutFormErrorLabelsType\n withPersistBeforePageLeave: boolean\n countryCode: string\n onSubmit: (data: CheckoutFormOnSubmitData) => void\n onError: (error: any) => void\n onSuccess: (order: OrderDTO) => void\n\n redirectTimeout?: number\n onBeforeRedirect?: () => void\n\n customState?: CheckoutCustomState\n\n enableSavedAddressList: boolean\n shippingValidations?: ShippingValidationsType\n enableSaveAddress: boolean\n autofillShippingPersonalData: boolean\n autoSelectDefaultShippingAddress: boolean\n\n enableSaveBillingAddress: boolean\n validateBillingAddress?: BillingAddressValidationType\n enableSavedBillingAddressList: boolean\n autoSelectDefaultBillingAddress: boolean\n\n paymentEnabledOnStep?: CheckoutFormStepsEnum\n getPaymentMethodsWhenShippingMethodIsSelected?: boolean\n\n shippingEnabledOnStep: CheckoutFormStepsEnum\n\n billingEnabledOnStep: CheckoutFormStepsEnum\n\n isBoricaInDevMode?: boolean\n\n withPixelMeta?: boolean\n requiredFieldsOnShippingStep?: string[]\n requiredFieldsOnBillingAddressStep?: string[]\n enableNoShippingMethodMode?: boolean\n disablePaymentRedirects?: boolean\n}\n\ntype ServerErrors = { [key: string]: any } | null\n\nexport enum CheckoutFormStepsEnum {\n Basket = 'Basket',\n Shipping = 'Shipping',\n BillingAddress = 'BillingAddress',\n Payment = 'Payment',\n Preview = 'Preview',\n All = 'All',\n}\n\nexport type CheckoutFormErrorsResultType =\n | {\n [key: string]: string\n }\n | null\n | undefined\n\nexport type ShippingFormErrorLabels = {\n fieldIsRequired: string\n fillStreetNumberBuildingEntranceOrApartment: string\n streetIsRequired: string\n invalidPhoneNumber?: string\n quarterIsRequired: string\n cantFindStreetOrQuarterMessage: string\n cityIsRequired: string\n emailIsRequired: string\n officeIsRequired: string\n selectCourier: string\n noStoreSelected: string\n}\n\nexport type CheckoutFormErrorLabelsType = ShippingFormErrorLabels & {\n selectPaymentMethod: string\n}\n\nexport type CheckoutFormContextType = {\n setStep: (step: CheckoutFormStepsEnum) => void\n step: CheckoutFormStepsEnum\n serverErrors: ServerErrors\n updateServerErrors: (errors: any) => void\n errorRef: (error: HTMLElement) => void\n errorFields: HTMLElement[]\n errorLabels: CheckoutFormErrorLabelsType\n orderQuery: QueryResult<OrderDTO, unknown>\n shippingState: UseShippingResultType\n paymentState: UsePaymentResultType\n billingState: UseBillingResultType\n}\n\nexport const useCheckoutFormStep = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormStep must be used within a CheckoutFormContextProvider'\n )\n }\n\n return useMemo(() => {\n return {\n currentStep: context.step,\n updateStep: context.setStep,\n }\n }, [context])\n}\n\nexport const useCheckoutFormOrder = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormOrder must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.orderQuery\n}\n\nexport const useCheckoutFormErrorLabels = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormErrorLabels must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.errorLabels\n}\n\nexport const useCheckoutFormServerErrors = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormServerErrors must be used within a CheckoutFormContextProvider'\n )\n }\n\n return useMemo(() => {\n return {\n serverErrors: context.serverErrors,\n updateServerErrors: context.updateServerErrors,\n }\n }, [context])\n}\n\nexport const useCheckoutFormBillingState = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormBillingState must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.billingState\n}\n\nexport const useCheckoutFormShippingState = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormShippingState must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.shippingState\n}\n\nexport const useCheckoutErrorFields = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutErrorFields must be used within a CheckoutFormContextProvider'\n )\n }\n\n return {\n errorFields: context.errorFields,\n errorRef: context.errorRef,\n }\n}\n\nexport const useCheckoutFormPaymentState = () => {\n const context = useContext(CheckoutFormContext)\n\n if (!context) {\n throw new Error(\n 'useCheckoutFormPaymentState must be used within a CheckoutFormContextProvider'\n )\n }\n\n return context.paymentState\n}\n"],"file":"index.js"}
|
@@ -2,7 +2,7 @@ import _extends from "@babel/runtime/helpers/extends";
|
|
2
2
|
import React from 'react';
|
3
3
|
import { AssetSourceDTO } from '@sentecacommerce/sdk';
|
4
4
|
import { getTranslatableField } from '../../';
|
5
|
-
import { assignCombinationsToAttributeRules, createCombinationsMap, createCustomFieldsMap, createProductContent, createAttributeRulesMap, createMappedAttributes, processAvailabilityPerStore, getProductVideos as _getProductVideos, createMappedOptions, createSelectedOption2, formatCategories, createLabelsMap } from './utils';
|
5
|
+
import { assignCombinationsToAttributeRules, createCombinationsMap, createCustomFieldsMap, createProductContent, createAttributeRulesMap, createMappedAttributes, processAvailabilityPerStore, getProductVideos as _getProductVideos, createMappedOptions, createSelectedOption2, formatCategories, createLabelsMap, createCollapseKeyImagesMap } from './utils';
|
6
6
|
import { productsApi } from '../../api/productsApi';
|
7
7
|
import { assetsFieldsToMap } from '../../utils/assetsToMap';
|
8
8
|
export { AssetSourceDTO };
|
@@ -152,11 +152,33 @@ export function ProductProvider(_ref) {
|
|
152
152
|
function selectVariantByAttribute(key) {
|
153
153
|
var _combinations$key;
|
154
154
|
|
155
|
+
// Get by collapseKey for SD
|
156
|
+
var split = key.split(':');
|
157
|
+
|
158
|
+
if (split[0] === 'collapseKey') {
|
159
|
+
var _id = Object.keys(variants).find(el => variants[el].collapseKey === split[1]);
|
160
|
+
|
161
|
+
return setSelectedVariant(variants[_id]);
|
162
|
+
}
|
163
|
+
|
155
164
|
var id = (_combinations$key = combinations[key]) == null ? void 0 : _combinations$key.value;
|
156
165
|
setSelectedVariant(variants[id]);
|
157
166
|
}
|
158
167
|
|
159
168
|
function selectVariantByCombination(key, value) {
|
169
|
+
// Take collapseKey for SD
|
170
|
+
var split = value.split(':');
|
171
|
+
|
172
|
+
if (split[0] === 'collapseKey') {
|
173
|
+
var _id2 = Object.keys(variants).find(el => {
|
174
|
+
var _variants$el$attribut;
|
175
|
+
|
176
|
+
return variants[el].collapseKey === split[1] && ((_variants$el$attribut = variants[el].attributes.find(attr => attr.name === 'size')) == null ? void 0 : _variants$el$attribut.value) === key;
|
177
|
+
});
|
178
|
+
|
179
|
+
return setSelectedVariant(variants[_id2]);
|
180
|
+
}
|
181
|
+
|
160
182
|
var id = combinations[key].params[value];
|
161
183
|
setSelectedVariant(variants[id]);
|
162
184
|
}
|
@@ -219,12 +241,14 @@ export function ProductProvider(_ref) {
|
|
219
241
|
return result;
|
220
242
|
}
|
221
243
|
|
244
|
+
var collapsedImages = createCollapseKeyImagesMap(product);
|
222
245
|
var state = {
|
223
246
|
metaData,
|
224
247
|
seoData,
|
225
248
|
variants,
|
226
249
|
selectedVariant,
|
227
|
-
attributeRules
|
250
|
+
attributeRules,
|
251
|
+
collapsedImages
|
228
252
|
};
|
229
253
|
var functions = {
|
230
254
|
getVariantById,
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../../src/hooks/useProduct/index.tsx"],"names":["React","AssetSourceDTO","getTranslatableField","assignCombinationsToAttributeRules","createCombinationsMap","createCustomFieldsMap","createProductContent","createAttributeRulesMap","createMappedAttributes","processAvailabilityPerStore","getProductVideos","createMappedOptions","createSelectedOption2","formatCategories","createLabelsMap","productsApi","assetsFieldsToMap","ProductStateContext","createContext","undefined","CountDispatchContext","ProductProvider","product","children","defaultVariantId","mounted","setMounted","useState","combinations","attributeRules","setCombinationsAndAttributeRules","getCombinationsAndAttributeRules","variants","setVariants","getVariantsWithInventory","selectedVariant","setSelectedVariant","getDefaultVariant","metaData","useMemo","rootCategory","categories","rootCategoryId","resourceId","metaObj","_id","name","slug","description","shortDescription","metaDescription","brand","brands","resource","logo","assets","sources","url","category","length","reviewRatingStatistics","content","Boolean","map","seoData","seoObj","title","metaTitle","keywords","metaKeywords","customFields","mappedFields","custom","useEffect","data","variantsWithInventory","reduce","_","index","arr","currentVariant","mappedAttributes","mappedOptions","availableOptions","isAvailable","inventorySnapshot","canOrder","updatedVariant","inventory","hasAvailableQuantity","availableQuantity","quantity","attributes","options","selectedOptions","labels","getAttribute","rule","getSelectedAttribute","getAttributeByKey","key","find","a","value","getAvailabilityByStore","availabilities","mappedAttributeRules","attributesWithId","Object","keys","variantId","combinationsMap","selectVariantById","id","selectVariantByAttribute","selectVariantByCombination","params","selectVariantOptions","definitionKey","optionKey","newSelectedVariant","filter","opt","mappedSelectedOptions","option","attributeRule","values","result","forEach","currentKey","found","getVariantById","getVariantByAttribute","getVariantByCombination","getCustomFieldValue","field","getCombinationsForAttributeRule","state","functions","useProductState","context","useContext","Error","useProductFunctions","useProduct","config"],"mappings":";AAAA,OAAOA,KAAP,MAAkB,OAAlB;AACA,SAOEC,cAPF,QAQO,sBARP;AASA,SAASC,oBAAT,QAAqC,QAArC;AACA,SACEC,kCADF,EAEEC,qBAFF,EAGEC,qBAHF,EAIEC,oBAJF,EAKEC,uBALF,EAMEC,sBANF,EAOEC,2BAPF,EAQEC,gBAAgB,IAAhBA,iBARF,EASEC,mBATF,EAUEC,qBAVF,EAYEC,gBAZF,EAaEC,eAbF,QAcO,SAdP;AAeA,SAASC,WAAT,QAAoD,uBAApD;AACA,SAASC,iBAAT,QAA6C,yBAA7C;AAEA,SAASf,cAAT;AAyLA,IAAMgB,mBAAmB,gBAAGjB,KAAK,CAACkB,aAAN,CAE1BC,SAF0B,CAA5B;AAGA,IAAMC,oBAAoB,gBAAGpB,KAAK,CAACkB,aAAN,CAE3BC,SAF2B,CAA7B;AAIA,OAAO,SAASE,eAAT,OAIkB;AAAA,MAJO;AAC9BC,IAAAA,OAD8B;AAE9BC,IAAAA,QAF8B;AAG9BC,IAAAA;AAH8B,GAIP;AACvB,MAAM,CAACC,OAAD,EAAUC,UAAV,IAAwB1B,KAAK,CAAC2B,QAAN,CAAe,KAAf,CAA9B;AAEA,MAAM,CACJ;AAAEC,IAAAA,YAAF;AAAgBC,IAAAA;AAAhB,GADI,EAEJC,gCAFI,IAGF9B,KAAK,CAAC2B,QAAN,CAGDI,gCAHC,CAHJ;AAQA,MAAM,CAACC,QAAD,EAAWC,WAAX,IAA0BjC,KAAK,CAAC2B,QAAN,CAC9BO,wBAD8B,CAAhC;AAI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AApB,EAAkCkG,MAAlC,EAAmE;AACxE,SAAOlI,WAAW,CAACiI,UAAZ,CAAuBjG,IAAvB,EAA6BkG,MAA7B,CAAP;AACD","sourcesContent":["import React from 'react'\nimport {\n ProductDTO,\n ProductVariantDTO,\n AttributeRuleDTO,\n ProductAttributeDraftDTO,\n SelectedOptionDTO,\n ReviewRatingStatisticsDTO,\n AssetSourceDTO,\n} from '@sentecacommerce/sdk'\nimport { getTranslatableField } from '../../'\nimport {\n assignCombinationsToAttributeRules,\n createCombinationsMap,\n createCustomFieldsMap,\n createProductContent,\n createAttributeRulesMap,\n createMappedAttributes,\n processAvailabilityPerStore,\n getProductVideos,\n createMappedOptions,\n createSelectedOption2,\n SelectedOptionType,\n formatCategories,\n createLabelsMap,\n} from './utils'\nimport { productsApi, getProductBySlugConfig } from '../../api/productsApi'\nimport { assetsFieldsToMap, AssetsMap } from '../../utils/assetsToMap'\n\nexport { AssetSourceDTO }\nexport interface OptionsType {\n definitionKey: string\n label: string\n elements?: SubOptionType[]\n}\n\nexport interface SubOptionType {\n optionKey: string\n label: string\n imageIndex?: number\n}\n\nexport interface ContentType {\n key: string\n name?: string\n content?: string\n}\n\nexport interface MetaInfoCategoryType {\n name: string\n id: string\n link: string\n}\n\nexport interface MetaInformationType {\n _id?: string\n name?: string\n slug?: string\n description?: string\n shortDescription?: string\n reviewRatingStatistics?: ReviewRatingStatisticsDTO\n brand: {\n _id?: string\n name?: string\n slug?: string\n logo?: string\n }\n category: {\n _id?: string\n name?: string\n slug?: string\n }\n rootCategory: {\n _id?: string\n name?: string\n slug?: string\n }\n categories?: MetaInfoCategoryType[]\n content?: ContentType[]\n assets?: AssetsMap\n}\n\ninterface SeoInformationType {\n title?: string\n description?: string\n keywords?: string\n}\n\ninterface AttributeRulesType extends AttributeRuleDTO {\n label: string\n values: {\n [id: string]: {\n label: string\n extra: any\n combinations: {\n [id: string]: string\n }\n }\n }\n}\n\nexport interface VariantType\n extends Omit<\n ProductVariantDTO,\n 'attributes' | 'availableOptions' | 'selectedOptions' | 'labels'\n > {\n attributes: ProductAttributeDraftDTO[]\n options?: OptionsType[]\n selectedOptions: SelectedOptionDTO[]\n mappedSelectedOptions?: SelectedOptionType[]\n isAvailable: boolean\n quantity?: number\n inventory: {\n hasAvailableQuantity?: boolean\n availableQuantity?: number\n }\n labels?: string[]\n getAttribute: (\n rule: string\n ) => {\n id: string\n label: string\n name: string\n extra: any\n combinations: {\n [id: string]: string\n }\n }\n getAttributeByKey: (key: string) => undefined | any\n getAvailabilityByStore: () => InventoryAvailabilityType[] | undefined\n}\ninterface VariantMap {\n [productId: string]: VariantType\n}\n\nexport interface BooleanKVP {\n [sku: string]: boolean | undefined\n}\n\nexport interface AttributeRulesMap {\n [name: string]: AttributeRulesType\n}\n\nexport interface CombinationsMap {\n [id: string]: {\n value: string\n params: {\n [id: string]: string\n }\n }\n}\n\nexport interface InventoryAvailabilityType {\n storeName: string\n availableQuantity: number\n acceptsBackorders: boolean\n restockableInDays: number\n}\n\ntype ProductProviderProps = {\n children: React.ReactNode\n product?: ProductDTO\n defaultVariantId?: string\n query?: {\n storeKey?: string\n currencyCode?: string\n languageCode?: string\n priceListKey?: string\n time?: number\n merchantKey?: string\n expand?: string\n project?: string\n }\n}\n\ntype ProductStateContextType = {\n attributeRules: AttributeRulesMap\n metaData: MetaInformationType\n seoData: SeoInformationType\n variants?: VariantMap\n selectedVariant?: VariantType | null\n}\n\nexport type VideoType = {\n type: string\n source: string\n iframe: JSX.Element\n thumb: {\n url: string\n }\n}\n\ntype CountFunctionsContextType = {\n selectVariantById: (id: string) => void\n selectVariantByAttribute: (key: string) => void\n selectVariantByCombination: (key: string, value: string) => void\n selectVariantOptions: (optionId: string, elementId: string) => void\n getVariantById: (id: string) => VariantType\n getVariantByAttribute: (key: string) => VariantType\n getVariantByCombination: (key: string, value: string) => VariantType\n getCustomFieldValue: (field: string) => boolean | undefined\n getCombinationsForAttributeRule: (\n key: string,\n id: string\n ) => {\n label: string\n extra: any\n combinations: {\n [id: string]: string\n }\n }\n getProductVideos: () => VideoType[]\n}\n\nconst ProductStateContext = React.createContext<\n ProductStateContextType | undefined\n>(undefined)\nconst CountDispatchContext = React.createContext<\n CountFunctionsContextType | undefined\n>(undefined)\n\nexport function ProductProvider({\n product,\n children,\n defaultVariantId,\n}: ProductProviderProps) {\n const [mounted, setMounted] = React.useState(false)\n\n const [\n { combinations, attributeRules },\n setCombinationsAndAttributeRules,\n ] = React.useState<{\n combinations: CombinationsMap\n attributeRules: AttributeRulesMap\n }>(getCombinationsAndAttributeRules)\n\n const [variants, setVariants] = React.useState<VariantMap>(\n getVariantsWithInventory\n )\n\n const [\n selectedVariant,\n setSelectedVariant,\n ] = React.useState<VariantType | null>(getDefaultVariant)\n\n const metaData = React.useMemo(() => {\n const rootCategory = product?.categories?.[0]\n const rootCategoryId = rootCategory?.resourceId\n\n const metaObj: MetaInformationType = {\n _id: product?._id,\n name:\n getTranslatableField(selectedVariant?.name) ||\n getTranslatableField(product?.name),\n slug: getTranslatableField(product?.slug),\n description:\n getTranslatableField(selectedVariant?.description) ||\n getTranslatableField(product?.description),\n shortDescription:\n getTranslatableField(selectedVariant?.metaDescription) ||\n getTranslatableField(product?.metaDescription),\n brand: {\n _id: product?.brands?.[0]?.resourceId,\n name: getTranslatableField(product?.brands?.[0]?.resource?.name),\n slug: getTranslatableField(product?.brands?.[0]?.resource?.slug),\n logo: product?.brands?.[0]?.resource?.assets?.[0]?.sources?.[0]?.url,\n },\n category: {\n _id: product?.categories?.[product?.categories?.length - 1]?.resourceId,\n name: getTranslatableField(\n product?.categories?.[product?.categories?.length - 1]?.resource?.name\n ),\n slug: getTranslatableField(\n product?.categories?.[product?.categories?.length - 1]?.resource?.slug\n ),\n },\n rootCategory: {\n _id: rootCategoryId,\n name: getTranslatableField(rootCategory?.resource?.name),\n slug: getTranslatableField(rootCategory?.resource?.slug),\n },\n categories: formatCategories(product?.categories, rootCategoryId),\n reviewRatingStatistics: product?.reviewRatingStatistics,\n content: Boolean(\n selectedVariant?.content?.map(createProductContent).length\n )\n ? selectedVariant?.content?.map(createProductContent)\n : product?.content?.map(createProductContent),\n assets: assetsFieldsToMap(product?.assets),\n }\n return metaObj\n }, [\n product?._id,\n product?.brands,\n product?.content,\n product?.description,\n product?.metaDescription,\n product?.name,\n product?.slug,\n product?.assets,\n selectedVariant,\n ])\n\n const seoData = React.useMemo(() => {\n const seoObj: SeoInformationType = {\n title:\n getTranslatableField(selectedVariant?.metaTitle) ||\n getTranslatableField(product?.metaTitle),\n description:\n getTranslatableField(selectedVariant?.metaDescription) ||\n getTranslatableField(product?.metaDescription),\n keywords:\n getTranslatableField(selectedVariant?.metaKeywords) ||\n getTranslatableField(product?.metaKeywords),\n }\n return seoObj\n }, [\n product?.metaDescription,\n product?.metaKeywords,\n product?.metaTitle,\n selectedVariant,\n ])\n\n const customFields = React.useMemo(() => {\n const mappedFields = createCustomFieldsMap(product?.custom) as BooleanKVP\n return mappedFields\n }, [product?.custom])\n\n React.useEffect(() => {\n // prevent unnecessary calculations\n if (mounted) {\n setVariants(getVariantsWithInventory())\n }\n }, [product])\n\n React.useMemo(() => {\n // prevent unnecessary calculations\n if (!mounted) {\n return setMounted(true)\n }\n\n const data = getCombinationsAndAttributeRules()\n\n setCombinationsAndAttributeRules(data)\n }, [variants])\n\n function getVariantsWithInventory() {\n const variantsWithInventory = product?.variants?.reduce(\n (map: any, _, index, arr) => {\n const currentVariant = arr[index] as ProductVariantDTO\n\n const mappedAttributes = createMappedAttributes(currentVariant)\n\n const mappedOptions =\n createMappedOptions(currentVariant?.availableOptions) || []\n\n const isAvailable = currentVariant?.inventorySnapshot?.canOrder\n\n const updatedVariant: VariantType = {\n ...currentVariant,\n inventory: {\n hasAvailableQuantity: currentVariant.inventorySnapshot?.canOrder,\n availableQuantity:\n currentVariant.inventorySnapshot?.availableQuantity,\n },\n isAvailable: isAvailable ? true : false,\n quantity: isAvailable\n ? currentVariant?.inventorySnapshot?.availableQuantity\n : 0,\n attributes: mappedAttributes,\n options: mappedOptions,\n selectedOptions: [],\n labels: createLabelsMap(currentVariant.labels),\n getAttribute: (rule: string) =>\n getSelectedAttribute(rule, mappedAttributes),\n getAttributeByKey: (key: string) =>\n mappedAttributes.find((a) => a.name === key)?.value,\n getAvailabilityByStore: () =>\n processAvailabilityPerStore(\n currentVariant?.inventorySnapshot?.availabilities\n ),\n }\n\n map[currentVariant._id] = updatedVariant\n\n return map\n },\n {}\n )\n\n return variantsWithInventory || {}\n }\n\n function getCombinationsAndAttributeRules() {\n const mappedAttributeRules: AttributeRulesMap = createAttributeRulesMap(\n product\n )\n\n const attributesWithId = Object.keys(variants || {}).map((key) => {\n return {\n variantId: variants?.[key]._id,\n attributes: variants?.[key].attributes,\n }\n })\n\n const combinationsMap = createCombinationsMap(\n Object.keys(mappedAttributeRules),\n attributesWithId\n )\n\n assignCombinationsToAttributeRules(mappedAttributeRules, combinationsMap)\n\n return {\n combinations: combinationsMap,\n attributeRules: mappedAttributeRules,\n }\n }\n\n function getDefaultVariant() {\n if (!defaultVariantId) return null\n\n return variants[defaultVariantId]\n }\n\n function selectVariantById(id: string) {\n setSelectedVariant(variants[id])\n }\n\n function selectVariantByAttribute(key: string) {\n const id = combinations[key]?.value\n setSelectedVariant(variants[id])\n }\n\n function selectVariantByCombination(key: string, value: string) {\n const id = combinations[key].params[value]\n setSelectedVariant(variants[id])\n }\n\n function selectVariantOptions(definitionKey: string, optionKey: string) {\n if (selectedVariant) {\n const newSelectedVariant = { ...selectedVariant }\n\n newSelectedVariant.selectedOptions = newSelectedVariant.selectedOptions.filter(\n (opt) => opt.definitionKey !== definitionKey\n )\n\n newSelectedVariant.selectedOptions = [\n ...newSelectedVariant.selectedOptions,\n {\n definitionKey,\n optionKey,\n },\n ]\n\n newSelectedVariant.mappedSelectedOptions = newSelectedVariant.selectedOptions.map(\n (option) => createSelectedOption2(newSelectedVariant.options, option)\n )\n\n setSelectedVariant(newSelectedVariant)\n }\n }\n\n function getSelectedAttribute(rule: string, attributes: any[]) {\n const attributeRule = attributeRules[rule]?.values\n let result\n\n attributes.forEach((currentKey) => {\n const found = attributeRule?.[currentKey.value]\n if (found) result = { id: currentKey.value, name: rule, ...found }\n })\n\n return (result as unknown) as {\n id: string\n name: string\n label: string\n extra: any\n combinations: {\n [id: string]: string\n }\n }\n }\n\n function getVariantById(id: string) {\n return variants?.[id]\n }\n\n function getVariantByAttribute(key: string) {\n const id = combinations[key]?.value\n return variants?.[id]\n }\n\n function getVariantByCombination(key: string, value: string) {\n const id = combinations[key]?.params[value]\n return variants?.[id]\n }\n\n function getCustomFieldValue(field: string) {\n return customFields?.[field]\n }\n\n function getCombinationsForAttributeRule(key: string, id: string) {\n const result = attributeRules?.[key]?.values?.[id]\n return result\n }\n\n const state = {\n metaData,\n seoData,\n variants,\n selectedVariant,\n attributeRules,\n }\n\n const functions = {\n getVariantById,\n getVariantByAttribute,\n getVariantByCombination,\n selectVariantById,\n selectVariantByAttribute,\n selectVariantByCombination,\n getCombinationsForAttributeRule,\n selectVariantOptions,\n getCustomFieldValue,\n getProductVideos: () => getProductVideos(metaData.assets),\n }\n\n return (\n <ProductStateContext.Provider value={state}>\n <CountDispatchContext.Provider value={functions}>\n {children}\n </CountDispatchContext.Provider>\n </ProductStateContext.Provider>\n )\n}\n\nexport function useProductState() {\n const context = React.useContext(ProductStateContext)\n if (context === undefined) {\n throw new Error('useProductState must be used within a ProductProvider')\n }\n return context\n}\nexport function useProductFunctions() {\n const context = React.useContext(CountDispatchContext)\n if (context === undefined) {\n throw new Error('useProductDispatch must be used within a ProductProvider')\n }\n return context\n}\n\nexport function useProduct(slug: string, config?: getProductBySlugConfig) {\n return productsApi.useProduct(slug, config)\n}\n"],"file":"index.js"}
|
1
|
+
{"version":3,"sources":["../../../../src/hooks/useProduct/index.tsx"],"names":["React","AssetSourceDTO","getTranslatableField","assignCombinationsToAttributeRules","createCombinationsMap","createCustomFieldsMap","createProductContent","createAttributeRulesMap","createMappedAttributes","processAvailabilityPerStore","getProductVideos","createMappedOptions","createSelectedOption2","formatCategories","createLabelsMap","createCollapseKeyImagesMap","productsApi","assetsFieldsToMap","ProductStateContext","createContext","undefined","CountDispatchContext","ProductProvider","product","children","defaultVariantId","mounted","setMounted","useState","combinations","attributeRules","setCombinationsAndAttributeRules","getCombinationsAndAttributeRules","variants","setVariants","getVariantsWithInventory","selectedVariant","setSelectedVariant","getDefaultVariant","metaData","useMemo","rootCategory","categories","rootCategoryId","resourceId","metaObj","_id","name","slug","description","shortDescription","metaDescription","brand","brands","resource","logo","assets","sources","url","category","length","reviewRatingStatistics","content","Boolean","map","seoData","seoObj","title","metaTitle","keywords","metaKeywords","customFields","mappedFields","custom","useEffect","data","variantsWithInventory","reduce","_","index","arr","currentVariant","mappedAttributes","mappedOptions","availableOptions","isAvailable","inventorySnapshot","canOrder","updatedVariant","inventory","hasAvailableQuantity","availableQuantity","quantity","attributes","options","selectedOptions","labels","getAttribute","rule","getSelectedAttribute","getAttributeByKey","key","find","a","value","getAvailabilityByStore","availabilities","mappedAttributeRules","attributesWithId","Object","keys","variantId","combinationsMap","selectVariantById","id","selectVariantByAttribute","split","el","collapseKey","selectVariantByCombination","attr","params","selectVariantOptions","definitionKey","optionKey","newSelectedVariant","filter","opt","mappedSelectedOptions","option","attributeRule","values","result","forEach","currentKey","found","getVariantById","getVariantByAttribute","getVariantByCombination","getCustomFieldValue","field","getCombinationsForAttributeRule","collapsedImages","state","functions","useProductState","context","useContext","Error","useProductFunctions","useProduct","config"],"mappings":";AAAA,OAAOA,KAAP,MAAkB,OAAlB;AACA,SAOEC,cAPF,QAQO,sBARP;AASA,SAASC,oBAAT,QAAqC,QAArC;AACA,SACEC,kCADF,EAEEC,qBAFF,EAGEC,qBAHF,EAIEC,oBAJF,EAKEC,uBALF,EAMEC,sBANF,EAOEC,2BAPF,EAQEC,gBAAgB,IAAhBA,iBARF,EASEC,mBATF,EAUEC,qBAVF,EAYEC,gBAZF,EAaEC,eAbF,EAcEC,0BAdF,QAeO,SAf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AAMC,OAAO,GAAGlJ,KAAK,CAACmJ,UAAN,CAAiBjI,mBAAjB,CAAhB;;AACA,MAAIgI,OAAO,KAAK9H,SAAhB,EAA2B;AACzB,UAAM,IAAIgI,KAAJ,CAAU,uDAAV,CAAN;AACD;;AACD,SAAOF,OAAP;AACD;AACD,OAAO,SAASG,mBAAT,GAA+B;AACpC,MAAMH,OAAO,GAAGlJ,KAAK,CAACmJ,UAAN,CAAiB9H,oBAAjB,CAAhB;;AACA,MAAI6H,OAAO,KAAK9H,SAAhB,EAA2B;AACzB,UAAM,IAAIgI,KAAJ,CAAU,0DAAV,CAAN;AACD;;AACD,SAAOF,OAAP;AACD;AAED,OAAO,SAASI,UAAT,CAAoBtG,IAApB,EAAkCuG,MAAlC,EAAmE;AACxE,SAAOvI,WAAW,CAACsI,UAAZ,CAAuBtG,IAAvB,EAA6BuG,MAA7B,CAAP;AACD","sourcesContent":["import React from 'react'\nimport {\n ProductDTO,\n ProductVariantDTO,\n AttributeRuleDTO,\n ProductAttributeDraftDTO,\n SelectedOptionDTO,\n ReviewRatingStatisticsDTO,\n AssetSourceDTO,\n} from '@sentecacommerce/sdk'\nimport { getTranslatableField } from '../../'\nimport {\n assignCombinationsToAttributeRules,\n createCombinationsMap,\n createCustomFieldsMap,\n createProductContent,\n createAttributeRulesMap,\n createMappedAttributes,\n processAvailabilityPerStore,\n getProductVideos,\n createMappedOptions,\n createSelectedOption2,\n SelectedOptionType,\n formatCategories,\n createLabelsMap,\n createCollapseKeyImagesMap,\n} from './utils'\nimport { productsApi, getProductBySlugConfig } from '../../api/productsApi'\nimport { assetsFieldsToMap, AssetsMap } from '../../utils/assetsToMap'\n\nexport { AssetSourceDTO }\nexport interface OptionsType {\n definitionKey: string\n label: string\n elements?: SubOptionType[]\n}\n\nexport interface SubOptionType {\n optionKey: string\n label: string\n imageIndex?: number\n}\n\nexport interface ContentType {\n key: string\n name?: string\n content?: string\n}\n\nexport interface MetaInfoCategoryType {\n name: string\n id: string\n link: string\n}\n\nexport interface MetaInformationType {\n _id?: string\n name?: string\n slug?: string\n description?: string\n shortDescription?: string\n reviewRatingStatistics?: ReviewRatingStatisticsDTO\n brand: {\n _id?: string\n name?: string\n slug?: string\n logo?: string\n }\n category: {\n _id?: string\n name?: string\n slug?: string\n }\n rootCategory: {\n _id?: string\n name?: string\n slug?: string\n }\n categories?: MetaInfoCategoryType[]\n content?: ContentType[]\n assets?: AssetsMap\n}\n\ninterface SeoInformationType {\n title?: string\n description?: string\n keywords?: string\n}\n\ninterface AttributeRulesType extends AttributeRuleDTO {\n label: string\n values: {\n [id: string]: {\n label: string\n extra: any\n combinations: {\n [id: string]: string\n }\n }\n }\n}\n\nexport interface VariantType\n extends Omit<\n ProductVariantDTO,\n 'attributes' | 'availableOptions' | 'selectedOptions' | 'labels'\n > {\n attributes: ProductAttributeDraftDTO[]\n options?: OptionsType[]\n selectedOptions: SelectedOptionDTO[]\n mappedSelectedOptions?: SelectedOptionType[]\n isAvailable: boolean\n quantity?: number\n inventory: {\n hasAvailableQuantity?: boolean\n availableQuantity?: number\n }\n labels?: string[]\n getAttribute: (\n rule: string\n ) => {\n id: string\n label: string\n name: string\n extra: any\n combinations: {\n [id: string]: string\n }\n }\n getAttributeByKey: (key: string) => undefined | any\n getAvailabilityByStore: () => InventoryAvailabilityType[] | undefined\n}\ninterface VariantMap {\n [productId: string]: VariantType\n}\n\nexport interface BooleanKVP {\n [sku: string]: boolean | undefined\n}\n\nexport interface AttributeRulesMap {\n [name: string]: AttributeRulesType\n}\n\nexport interface CombinationsMap {\n [id: string]: {\n value: string\n params: {\n [id: string]: string\n }\n }\n}\n\nexport interface InventoryAvailabilityType {\n storeName: string\n availableQuantity: number\n acceptsBackorders: boolean\n restockableInDays: number\n}\n\ntype ProductProviderProps = {\n children: React.ReactNode\n product?: ProductDTO\n defaultVariantId?: string\n query?: {\n storeKey?: string\n currencyCode?: string\n languageCode?: string\n priceListKey?: string\n time?: number\n merchantKey?: string\n expand?: string\n project?: string\n }\n}\n\ntype ProductStateContextType = {\n attributeRules: AttributeRulesMap\n metaData: MetaInformationType\n seoData: SeoInformationType\n variants?: VariantMap\n selectedVariant?: VariantType | null\n}\n\nexport type VideoType = {\n type: string\n source: string\n iframe: JSX.Element\n thumb: {\n url: string\n }\n}\n\ntype CountFunctionsContextType = {\n selectVariantById: (id: string) => void\n selectVariantByAttribute: (key: string) => void\n selectVariantByCombination: (key: string, value: string) => void\n selectVariantOptions: (optionId: string, elementId: string) => void\n getVariantById: (id: string) => VariantType\n getVariantByAttribute: (key: string) => VariantType\n getVariantByCombination: (key: string, value: string) => VariantType\n getCustomFieldValue: (field: string) => boolean | undefined\n getCombinationsForAttributeRule: (\n key: string,\n id: string\n ) => {\n label: string\n extra: any\n combinations: {\n [id: string]: string\n }\n }\n getProductVideos: () => VideoType[]\n}\n\nconst ProductStateContext = React.createContext<\n ProductStateContextType | undefined\n>(undefined)\nconst CountDispatchContext = React.createContext<\n CountFunctionsContextType | undefined\n>(undefined)\n\nexport function ProductProvider({\n product,\n children,\n defaultVariantId,\n}: ProductProviderProps) {\n const [mounted, setMounted] = React.useState(false)\n\n const [\n { combinations, attributeRules },\n setCombinationsAndAttributeRules,\n ] = React.useState<{\n combinations: CombinationsMap\n attributeRules: AttributeRulesMap\n }>(getCombinationsAndAttributeRules)\n\n const [variants, setVariants] = React.useState<VariantMap>(\n getVariantsWithInventory\n )\n\n const [\n selectedVariant,\n setSelectedVariant,\n ] = React.useState<VariantType | null>(getDefaultVariant)\n\n const metaData = React.useMemo(() => {\n const rootCategory = product?.categories?.[0]\n const rootCategoryId = rootCategory?.resourceId\n\n const metaObj: MetaInformationType = {\n _id: product?._id,\n name:\n getTranslatableField(selectedVariant?.name) ||\n getTranslatableField(product?.name),\n slug: getTranslatableField(product?.slug),\n description:\n getTranslatableField(selectedVariant?.description) ||\n getTranslatableField(product?.description),\n shortDescription:\n getTranslatableField(selectedVariant?.metaDescription) ||\n getTranslatableField(product?.metaDescription),\n brand: {\n _id: product?.brands?.[0]?.resourceId,\n name: getTranslatableField(product?.brands?.[0]?.resource?.name),\n slug: getTranslatableField(product?.brands?.[0]?.resource?.slug),\n logo: product?.brands?.[0]?.resource?.assets?.[0]?.sources?.[0]?.url,\n },\n category: {\n _id: product?.categories?.[product?.categories?.length - 1]?.resourceId,\n name: getTranslatableField(\n product?.categories?.[product?.categories?.length - 1]?.resource?.name\n ),\n slug: getTranslatableField(\n product?.categories?.[product?.categories?.length - 1]?.resource?.slug\n ),\n },\n rootCategory: {\n _id: rootCategoryId,\n name: getTranslatableField(rootCategory?.resource?.name),\n slug: getTranslatableField(rootCategory?.resource?.slug),\n },\n categories: formatCategories(product?.categories, rootCategoryId),\n reviewRatingStatistics: product?.reviewRatingStatistics,\n content: Boolean(\n selectedVariant?.content?.map(createProductContent).length\n )\n ? selectedVariant?.content?.map(createProductContent)\n : product?.content?.map(createProductContent),\n assets: assetsFieldsToMap(product?.assets),\n }\n return metaObj\n }, [\n product?._id,\n product?.brands,\n product?.content,\n product?.description,\n product?.metaDescription,\n product?.name,\n product?.slug,\n product?.assets,\n selectedVariant,\n ])\n\n const seoData = React.useMemo(() => {\n const seoObj: SeoInformationType = {\n title:\n getTranslatableField(selectedVariant?.metaTitle) ||\n getTranslatableField(product?.metaTitle),\n description:\n getTranslatableField(selectedVariant?.metaDescription) ||\n getTranslatableField(product?.metaDescription),\n keywords:\n getTranslatableField(selectedVariant?.metaKeywords) ||\n getTranslatableField(product?.metaKeywords),\n }\n return seoObj\n }, [\n product?.metaDescription,\n product?.metaKeywords,\n product?.metaTitle,\n selectedVariant,\n ])\n\n const customFields = React.useMemo(() => {\n const mappedFields = createCustomFieldsMap(product?.custom) as BooleanKVP\n return mappedFields\n }, [product?.custom])\n\n React.useEffect(() => {\n // prevent unnecessary calculations\n if (mounted) {\n setVariants(getVariantsWithInventory())\n }\n }, [product])\n\n React.useMemo(() => {\n // prevent unnecessary calculations\n if (!mounted) {\n return setMounted(true)\n }\n\n const data = getCombinationsAndAttributeRules()\n\n setCombinationsAndAttributeRules(data)\n }, [variants])\n\n function getVariantsWithInventory() {\n const variantsWithInventory = product?.variants?.reduce(\n (map: any, _, index, arr) => {\n const currentVariant = arr[index] as ProductVariantDTO\n\n const mappedAttributes = createMappedAttributes(currentVariant)\n\n const mappedOptions =\n createMappedOptions(currentVariant?.availableOptions) || []\n\n const isAvailable = currentVariant?.inventorySnapshot?.canOrder\n\n const updatedVariant: VariantType = {\n ...currentVariant,\n inventory: {\n hasAvailableQuantity: currentVariant.inventorySnapshot?.canOrder,\n availableQuantity:\n currentVariant.inventorySnapshot?.availableQuantity,\n },\n isAvailable: isAvailable ? true : false,\n quantity: isAvailable\n ? currentVariant?.inventorySnapshot?.availableQuantity\n : 0,\n attributes: mappedAttributes,\n options: mappedOptions,\n selectedOptions: [],\n labels: createLabelsMap(currentVariant.labels),\n getAttribute: (rule: string) =>\n getSelectedAttribute(rule, mappedAttributes),\n getAttributeByKey: (key: string) =>\n mappedAttributes.find((a) => a.name === key)?.value,\n getAvailabilityByStore: () =>\n processAvailabilityPerStore(\n currentVariant?.inventorySnapshot?.availabilities\n ),\n }\n\n map[currentVariant._id] = updatedVariant\n\n return map\n },\n {}\n )\n\n return variantsWithInventory || {}\n }\n\n function getCombinationsAndAttributeRules() {\n const mappedAttributeRules: AttributeRulesMap = createAttributeRulesMap(\n product\n )\n\n const attributesWithId = Object.keys(variants || {}).map((key) => {\n return {\n variantId: variants?.[key]._id,\n attributes: variants?.[key].attributes,\n }\n })\n\n const combinationsMap = createCombinationsMap(\n Object.keys(mappedAttributeRules),\n attributesWithId\n )\n\n assignCombinationsToAttributeRules(mappedAttributeRules, combinationsMap)\n\n return {\n combinations: combinationsMap,\n attributeRules: mappedAttributeRules,\n }\n }\n\n function getDefaultVariant() {\n if (!defaultVariantId) return null\n\n return variants[defaultVariantId]\n }\n\n function selectVariantById(id: string) {\n setSelectedVariant(variants[id])\n }\n\n function selectVariantByAttribute(key: string) {\n // Get by collapseKey for SD\n const split = key.split(':')\n if (split[0] === 'collapseKey') {\n const id = Object.keys(variants).find(\n (el) => variants[el].collapseKey === split[1]\n )\n return setSelectedVariant(variants[id as string])\n }\n const id = combinations[key]?.value\n setSelectedVariant(variants[id])\n }\n\n function selectVariantByCombination(key: string, value: string) {\n // Take collapseKey for SD\n const split = value.split(':')\n if (split[0] === 'collapseKey') {\n const id = Object.keys(variants).find(\n (el) =>\n variants[el].collapseKey === split[1] &&\n variants[el].attributes.find((attr) => attr.name === 'size')\n ?.value === key\n )\n return setSelectedVariant(variants[id as string])\n }\n const id = combinations[key].params[value]\n setSelectedVariant(variants[id])\n }\n\n function selectVariantOptions(definitionKey: string, optionKey: string) {\n if (selectedVariant) {\n const newSelectedVariant = { ...selectedVariant }\n\n newSelectedVariant.selectedOptions = newSelectedVariant.selectedOptions.filter(\n (opt) => opt.definitionKey !== definitionKey\n )\n\n newSelectedVariant.selectedOptions = [\n ...newSelectedVariant.selectedOptions,\n {\n definitionKey,\n optionKey,\n },\n ]\n\n newSelectedVariant.mappedSelectedOptions = newSelectedVariant.selectedOptions.map(\n (option) => createSelectedOption2(newSelectedVariant.options, option)\n )\n\n setSelectedVariant(newSelectedVariant)\n }\n }\n\n function getSelectedAttribute(rule: string, attributes: any[]) {\n const attributeRule = attributeRules[rule]?.values\n let result\n\n attributes.forEach((currentKey) => {\n const found = attributeRule?.[currentKey.value]\n if (found) result = { id: currentKey.value, name: rule, ...found }\n })\n\n return (result as unknown) as {\n id: string\n name: string\n label: string\n extra: any\n combinations: {\n [id: string]: string\n }\n }\n }\n\n function getVariantById(id: string) {\n return variants?.[id]\n }\n\n function getVariantByAttribute(key: string) {\n const id = combinations[key]?.value\n return variants?.[id]\n }\n\n function getVariantByCombination(key: string, value: string) {\n const id = combinations[key]?.params[value]\n return variants?.[id]\n }\n\n function getCustomFieldValue(field: string) {\n return customFields?.[field]\n }\n\n function getCombinationsForAttributeRule(key: string, id: string) {\n const result = attributeRules?.[key]?.values?.[id]\n return result\n }\n\n const collapsedImages = createCollapseKeyImagesMap(product)\n\n const state = {\n metaData,\n seoData,\n variants,\n selectedVariant,\n attributeRules,\n collapsedImages,\n }\n\n const functions = {\n getVariantById,\n getVariantByAttribute,\n getVariantByCombination,\n selectVariantById,\n selectVariantByAttribute,\n selectVariantByCombination,\n getCombinationsForAttributeRule,\n selectVariantOptions,\n getCustomFieldValue,\n getProductVideos: () => getProductVideos(metaData.assets),\n }\n\n return (\n <ProductStateContext.Provider value={state}>\n <CountDispatchContext.Provider value={functions}>\n {children}\n </CountDispatchContext.Provider>\n </ProductStateContext.Provider>\n )\n}\n\nexport function useProductState() {\n const context = React.useContext(ProductStateContext)\n if (context === undefined) {\n throw new Error('useProductState must be used within a ProductProvider')\n }\n return context\n}\nexport function useProductFunctions() {\n const context = React.useContext(CountDispatchContext)\n if (context === undefined) {\n throw new Error('useProductDispatch must be used within a ProductProvider')\n }\n return context\n}\n\nexport function useProduct(slug: string, config?: getProductBySlugConfig) {\n return productsApi.useProduct(slug, config)\n}\n"],"file":"index.js"}
|
@@ -68,9 +68,23 @@ export var createProductContent = data => {
|
|
68
68
|
name: getTranslatableField(data.label),
|
69
69
|
content: getTranslatableField(data.content)
|
70
70
|
};
|
71
|
+
}; // Add grouped images for SD color variants
|
72
|
+
|
73
|
+
export var createCollapseKeyImagesMap = product => {
|
74
|
+
var _product$variants;
|
75
|
+
|
76
|
+
var mappedKeys = product == null ? void 0 : (_product$variants = product.variants) == null ? void 0 : _product$variants.reduce((res, cur) => {
|
77
|
+
if (!res[cur.collapseKey]) {
|
78
|
+
res[cur.collapseKey] = [];
|
79
|
+
}
|
80
|
+
|
81
|
+
res[cur.collapseKey].push(cur);
|
82
|
+
return res;
|
83
|
+
}, {});
|
84
|
+
return mappedKeys;
|
71
85
|
};
|
72
86
|
export var createAttributeRulesMap = product => {
|
73
|
-
var _product$attributeRul, _product$
|
87
|
+
var _product$attributeRul, _product$variants2;
|
74
88
|
|
75
89
|
var uniqueRules = product == null ? void 0 : (_product$attributeRul = product.attributeRules) == null ? void 0 : _product$attributeRul.filter(x => x.constraint === AttributeRuleDTOConstraintEnum.CombinationUnique);
|
76
90
|
|
@@ -98,7 +112,7 @@ export var createAttributeRulesMap = product => {
|
|
98
112
|
return map;
|
99
113
|
};
|
100
114
|
|
101
|
-
var mappedAttributeRules = product == null ? void 0 : (_product$
|
115
|
+
var mappedAttributeRules = product == null ? void 0 : (_product$variants2 = product.variants) == null ? void 0 : _product$variants2.map(v => v.attributes).flat().reduce(reduceVariantsToAttributeRuleValues, {});
|
102
116
|
return mappedAttributeRules;
|
103
117
|
};
|
104
118
|
export var createMappedOptions = options => {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../../../src/hooks/useProduct/utils/index.ts"],"names":["AttributeRuleDTOConstraintEnum","createEmbededVideo","getTranslatableField","createCustomFieldsMap","customFields","reduce","map","currentObj","field","value","createCombinationsMap","mappedAttributeRulesKeys","attributesArray","combinationsMap","forEach","key","p","currentKey","attributes","find","x","name","filtered","filter","currentCombination","params","variantId","attribute","assignCombinationsToAttributeRules","mappedAttributeRules","Object","keys","current","values","combinations","createProductContent","data","label","content","createAttributeRulesMap","product","uniqueRules","attributeRules","constraint","CombinationUnique","reduceVariantsToAttributeRuleValues","found","attributeName","valueData","extra","variants","v","flat","createMappedOptions","options","mappedOptions","currentOption","definitionKey","elements","subOption","optionKey","imageIndex","createSelectedOption2","selectedOption","availableOption","element","createSelectedOption","optionValue","createMappedAttributes","currentVariant","mappedAttributes","attributeArray","push","processAvailabilityPerStore","availabilities","isPhysical","acceptsBackorders","stockLocationName","restockableInDays","availableQuantity","storeName","getProductVideos","assets","youtube","videos","sources","a","embeded","type","source","url","iframe","thumb","thumbnail","formatCategories","categories","rootCategoryId","results","some","cat","resource","custom","customField","cats","result","category","resourceId","hasChildCategories","paths","parents","ancestors","parent","_id","Boolean","mainPaths","path","ancestor","formattedResults","id","link","slug","createLabelsMap","now","Date","getTime","currentLabels","el","validFrom","validTo"],"mappings":";A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V,CADrB;AAELiG,QAAAA,EAAE,EAAEb,QAAQ,CAACC,UAAT,IAAuB,EAFtB;AAGLa,QAAAA,IAAI,QAAMrH,oBAAoB,CAACkG,QAAQ,CAACoB,IAAV,CAA1B;AAHC,OAAP;AAKD;;AAED,QAAMrB,GAAG,GAAIM,QAAb;AAEA,WAAO;AACLpF,MAAAA,IAAI,EAAEnB,oBAAoB,CAACiG,GAAG,CAAC9E,IAAL,CADrB;AAELiG,MAAAA,EAAE,EAAEnB,GAAG,CAACa,GAAJ,IAAW,EAFV;AAGLO,MAAAA,IAAI,QAAMrH,oBAAoB,CAACiG,GAAG,CAACqB,IAAL,CAA1B;AAHC,KAAP;AAKD,GAlBwB,CAAzB;AAoBA,SAAOH,gBAAgB,IAAI,EAA3B;AACD,CA1FM;AA4FP,OAAO,IAAMI,eAAe,GAAIrF,IAAD,IAAqC;AAClE;AACA,MAAMsF,GAAG,GAAG,IAAIC,IAAJ,GAAWC,OAAX,EAAZ;AAEA,MAAMC,aAAa,GAAGzF,IAAH,oBAAGA,IAAI,CAAEb,MAAN,CAAcuG,EAAD,IAAQ;AACzC,QAAI,CAACA,EAAE,CAACC,SAAJ,IAAiB,CAACD,EAAE,CAACE,OAAzB,EAAkC;AAChC,aAAOF,EAAP;AACD,KAFD,MAEO;AACL,aAAOA,EAAE,CAACC,SAAH,GAAeL,GAAf,IAAsBI,EAAE,CAACE,OAAH,GAAaN,GAA1C;AACD;AACF,GANqB,CAAtB;AAQA,SAAOG,aAAP,oBAAOA,aAAa,CAAEvH,GAAf,CAAoBwH,EAAD,IAAQA,EAAE,CAAC/G,GAA9B,CAAP;AACD,CAbM","sourcesContent":["import {\n ProductAttributeDTO,\n CustomField,\n AttributeRuleDTOConstraintEnum,\n ProductDTO,\n ProductVariantDTO,\n InventoryAvailability,\n OptionDefinitionDTO,\n SelectedOptionDTO,\n IdReferenceDTO,\n CategoryDTO,\n ProductVariantLabelDTO,\n} from '@sentecacommerce/sdk'\n\nimport {\n AttributeRulesMap,\n CombinationsMap,\n BooleanKVP,\n InventoryAvailabilityType,\n MetaInformationType,\n OptionsType,\n} from '../index'\n\nimport { createEmbededVideo } from './createEmbededVideo'\n\nimport { getTranslatableField } from '../../../utils'\n\n// export const createMappedInventory = (\n// currentVariant: ProductVariantDraftDTO,\n// inventory?: SkuReservationResponseDTO\n// ) => {\n// const currentInventory = inventory?.find(\n// (x) => x.sku === currentVariant.sku\n// )\n\n// const mappedInventory = {\n// ...currentInventory,\n// status:\n// currentInventory?.status === SkuReservationDTOStatusEnum.Available\n// ? true\n// : false,\n// inventoryId: currentInventory?.inventoryReservations?.[0].inventoryId,\n// quantity: currentInventory?.inventoryReservations?.[0].quantity,\n// }\n\n// return mappedInventory\n// }\n\nexport const createCustomFieldsMap = (customFields?: CustomField[]) => {\n return customFields?.reduce((map: BooleanKVP, currentObj) => {\n map[currentObj.field] = currentObj.value\n return map\n }, {})\n}\n\nexport const createCombinationsMap = (\n mappedAttributeRulesKeys: string[],\n attributesArray: {\n variantId: string\n attributes: ProductAttributeDTO[]\n }[]\n) => {\n const combinationsMap: CombinationsMap = {}\n mappedAttributeRulesKeys.forEach((key) => {\n attributesArray.forEach((p) => {\n const currentKey = p.attributes.find((x) => x.name === key)\n const filtered = p.attributes.filter((x) => x.name !== key)\n\n let currentCombination = combinationsMap[currentKey?.value]\n\n if (!currentCombination) {\n currentCombination = {\n params: {},\n value: '',\n }\n }\n\n currentCombination.value = p.variantId\n\n filtered.forEach((attribute) => {\n currentCombination.params = {\n ...currentCombination.params,\n [attribute.value]: p.variantId,\n }\n })\n\n combinationsMap[currentKey?.value] = currentCombination\n })\n })\n\n return combinationsMap\n}\n\nexport const assignCombinationsToAttributeRules = (\n mappedAttributeRules: AttributeRulesMap,\n combinationsMap: CombinationsMap\n) => {\n Object.keys(mappedAttributeRules).forEach((key) => {\n const current = mappedAttributeRules[key].values\n Object.keys(current).forEach((currentKey) => {\n mappedAttributeRules[key].values[currentKey].combinations =\n combinationsMap[currentKey]?.params\n })\n })\n}\n\nexport const createProductContent = (\n data: any\n): { key: string; name: string; content: string } => {\n return {\n key: data.key,\n name: getTranslatableField(data.label),\n content: getTranslatableField(data.content),\n }\n}\n\nexport const createAttributeRulesMap = (product?: ProductDTO) => {\n const uniqueRules = product?.attributeRules?.filter(\n (x) => x.constraint === AttributeRuleDTOConstraintEnum.CombinationUnique\n )\n const reduceVariantsToAttributeRuleValues = (map: any, attribute: any) => {\n const found = uniqueRules?.find((x) => x.attributeName === attribute.name)\n if (found) {\n if (!map[attribute.name]) {\n map[attribute.name] = {\n ...found,\n label: getTranslatableField(attribute.data.label),\n values: {},\n }\n }\n\n map[attribute.name] = {\n ...map[attribute.name],\n values: {\n ...map[attribute.name].values,\n [attribute.value]: {\n label: getTranslatableField(attribute.valueData.label),\n extra: attribute.valueData.extra,\n },\n },\n }\n }\n\n return map\n }\n\n const mappedAttributeRules = product?.variants\n ?.map((v) => v.attributes)\n .flat()\n .reduce(reduceVariantsToAttributeRuleValues, {})\n\n return mappedAttributeRules\n}\n\nexport const createMappedOptions = (\n options?: OptionDefinitionDTO[]\n): OptionsType[] => {\n const mappedOptions =\n options?.map((currentOption) => {\n return {\n definitionKey: currentOption.key,\n label: getTranslatableField(currentOption?.label),\n elements: currentOption.options?.map((subOption) => {\n return {\n optionKey: subOption.key,\n label: getTranslatableField(subOption?.label),\n imageIndex: subOption?.imageIndex,\n }\n }),\n }\n }) || []\n\n return mappedOptions\n}\n\nexport type SelectedOptionType = {\n label?: string\n value?: { key?: string; label?: string; imageIndex?: number }\n}\n\nexport const createSelectedOption2 = (\n options?: OptionsType[],\n selectedOption?: SelectedOptionDTO\n): SelectedOptionType => {\n const currentOption = options?.find(\n (availableOption) =>\n availableOption.definitionKey === selectedOption?.definitionKey\n )\n\n const value = currentOption?.elements?.find(\n (element) => element.optionKey === selectedOption?.optionKey\n )\n\n return {\n label: currentOption?.label,\n value: {\n key: value?.optionKey,\n imageIndex: value?.imageIndex,\n label: value?.label,\n },\n }\n}\n\nexport const createSelectedOption = (\n options?: OptionDefinitionDTO[],\n selectedOption?: SelectedOptionDTO\n): SelectedOptionType => {\n const currentOption = options?.find(\n (availableOption) => availableOption.key === selectedOption?.definitionKey\n )\n\n const value = currentOption?.options?.find(\n (optionValue) => optionValue.key === selectedOption?.optionKey\n )\n\n return {\n label: getTranslatableField(currentOption?.label),\n value: {\n key: value?.key,\n imageIndex: value?.imageIndex,\n label: getTranslatableField(value?.label),\n },\n }\n}\n\nexport const createMappedAttributes = (currentVariant: ProductVariantDTO) => {\n const mappedAttributes =\n currentVariant.attributes?.reduce(\n (attributeArray: ProductAttributeDTO[], attribute) => {\n attributeArray.push({\n name: attribute.name,\n value: attribute.value,\n valueData: attribute.valueData,\n })\n return attributeArray\n },\n []\n ) || []\n\n return mappedAttributes\n}\n\nexport const processAvailabilityPerStore = (\n availabilities?: InventoryAvailability[]\n): InventoryAvailabilityType[] | undefined => {\n return availabilities\n ?.filter((x) => !x.isPhysical)\n ?.map(\n ({\n acceptsBackorders,\n stockLocationName,\n restockableInDays,\n availableQuantity,\n }) => {\n return {\n storeName: getTranslatableField(stockLocationName),\n availableQuantity,\n acceptsBackorders,\n restockableInDays: restockableInDays,\n }\n }\n )\n}\n\nexport const getProductVideos = (assets: MetaInformationType['assets']) => {\n if (assets?.youtube) {\n const videos = assets.youtube.sources.map((a) => {\n const embeded = createEmbededVideo(a)\n return {\n type: 'video',\n source: a.url,\n iframe: embeded.iframe,\n thumb: { url: embeded.thumbnail },\n }\n })\n\n return videos\n }\n return []\n}\n\nexport const formatCategories = (\n categories?: IdReferenceDTO[],\n rootCategoryId?: string\n) => {\n let results\n\n if (\n categories?.some((cat) =>\n cat.resource?.custom?.some(\n (customField: any) => customField.field === 'isTemporary'\n )\n )\n ) {\n type PathType = {\n [key: string]: string\n }\n type CategoryType = CategoryDTO & { hasChildCategories: boolean }\n\n const cats = categories.reduce((result, category) => {\n result[category.resourceId] = {\n ...category.resource,\n hasChildCategories: false,\n }\n\n return result\n }, {} as CategoryDTO[])\n\n const paths = Object.values(cats).reduce((result, category) => {\n const parents = (category?.ancestors as IdReferenceDTO[])\n .map((parent: any) => {\n return (cats?.[parent?.resourceId] as any)?._id\n })\n .filter(Boolean)\n\n parents.forEach((parent: any) => {\n ;(cats as CategoryType[])[parent].hasChildCategories = true\n })\n\n result[category._id as string] = [...parents, category._id]\n\n return result\n }, {} as PathType[])\n\n const mainPaths = Object.values(cats as CategoryType[] & IdReferenceDTO[])\n .filter((category: CategoryType) => category.hasChildCategories === false)\n .map((category) => paths?.[category._id as string])\n .map((paths) => paths.map((path: string) => cats?.[path]))\n .filter(\n (paths) =>\n !paths.some(\n (path: { custom: any }) =>\n path?.custom?.find(\n (custom: any) => custom.field === 'isTemporary'\n )?.value ?? false\n )\n )?.[0]\n .flat()\n\n results = mainPaths\n } else {\n results = categories?.filter(\n (cat) =>\n cat?.resourceId === rootCategoryId ||\n cat?.resource?.ancestors?.some(\n (ancestor: any) => ancestor.resource === rootCategoryId\n )\n )\n }\n\n const formattedResults = (results as IdReferenceDTO[])?.map((category) => {\n if (category.resource) {\n const resource = category.resource as CategoryDTO\n\n return {\n name: getTranslatableField(resource.name),\n id: category.resourceId || '',\n link: `/${getTranslatableField(resource.slug)}/c`,\n }\n }\n\n const cat = (category as unknown) as CategoryDTO\n\n return {\n name: getTranslatableField(cat.name),\n id: cat._id || '',\n link: `/${getTranslatableField(cat.slug)}/c`,\n }\n })\n\n return formattedResults || []\n}\n\nexport const createLabelsMap = (data?: ProductVariantLabelDTO[]) => {\n // Filter only labels that are currently active\n const now = new Date().getTime()\n\n const currentLabels = data?.filter((el) => {\n if (!el.validFrom || !el.validTo) {\n return el\n } else {\n return el.validFrom < now && el.validTo > now\n }\n })\n\n return currentLabels?.map((el) => el.key)\n}\n"],"file":"index.js"}
|
1
|
+
{"version":3,"sources":["../../../../../src/hooks/useProduct/utils/index.ts"],"names":["AttributeRuleDTOConstraintEnum","createEmbededVideo","getTranslatableField","createCustomFieldsMap","customFields","reduce","map","currentObj","field","value","createCombinationsMap","mappedAttributeRulesKeys","attributesArray","combinationsMap","forEach","key","p","currentKey","attributes","find","x","name","filtered","filter","currentCombination","params","variantId","attribute","assignCombinationsToAttributeRules","mappedAttributeRules","Object","keys","current","values","combinations","createProductContent","data","label","content","createCollapseKeyImagesMap","product","mappedKeys","variants","res","cur","collapseKey","push","createAttributeRulesMap","uniqueRules","attributeRules","constraint","CombinationUnique","reduceVariantsToAttributeRuleValues","found","attributeName","valueData","extra","v","flat","createMappedOptions","options","mappedOptions","currentOption","definitionKey","elements","subOption","optionKey","imageIndex","createSelectedOption2","selectedOption","availableOption","element","createSelectedOption","optionValue","createMappedAttributes","currentVariant","mappedAttributes","attributeArray","processAvailabilityPerStore","availabilities","isPhysical","acceptsBackorders","stockLocationName","restockableInDays","availableQuantity","storeName","getProductVideos","assets","youtube","videos","sources","a","embeded","type","source","url","iframe","thumb","thumbnail","formatCategories","categories","rootCategoryId","results","some","cat","resource","custom","customField","cats","result","category","resourceId","hasChildCategories","paths","parents","ancestors","parent","_id","Boolean","mainPaths","path","ancestor","formattedResults","id","link","slug","createLabelsMap","now","Date","getTime","currentLabels","el","validFrom","validTo"],"mappings":";AAAA,SAGEA,8BAHF,QAYO,sBAZP;AAuBA,SAASC,kBAAT,QAAmC,sBAAnC;AAEA,SAASC,oBAAT,QAAqC,gBAArC,C,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;;AAEA,OAAO,IAAMC,qBAAqB,GAAIC,YAAD,IAAkC;AACrE,SAAOA,YAAP,oBAAOA,YAAY,CAAEC,MAAd,CAAqB,CAACC,GAAD,EAAkBC,UAAlB,KAAiC;AAC3DD,IAAAA,GAAG,CAACC,UAAU,CAACC,KAAZ,CAAH,GAAwBD,UAAU,CAACE,KAAnC;AACA,WAAOH,GAAP;AACD,GAHM,EAGJ,EAHI,CAAP;AAID,CALM;AAOP,OAAO,IAA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ACpF,IAAV,CADrB;AAELsG,QAAAA,EAAE,EAAEb,QAAQ,CAACC,UAAT,IAAuB,EAFtB;AAGLa,QAAAA,IAAI,QAAM1H,oBAAoB,CAACuG,QAAQ,CAACoB,IAAV,CAA1B;AAHC,OAAP;AAKD;;AAED,QAAMrB,GAAG,GAAIM,QAAb;AAEA,WAAO;AACLzF,MAAAA,IAAI,EAAEnB,oBAAoB,CAACsG,GAAG,CAACnF,IAAL,CADrB;AAELsG,MAAAA,EAAE,EAAEnB,GAAG,CAACa,GAAJ,IAAW,EAFV;AAGLO,MAAAA,IAAI,QAAM1H,oBAAoB,CAACsG,GAAG,CAACqB,IAAL,CAA1B;AAHC,KAAP;AAKD,GAlBwB,CAAzB;AAoBA,SAAOH,gBAAgB,IAAI,EAA3B;AACD,CA1FM;AA4FP,OAAO,IAAMI,eAAe,GAAI1F,IAAD,IAAqC;AAClE;AACA,MAAM2F,GAAG,GAAG,IAAIC,IAAJ,GAAWC,OAAX,EAAZ;AAEA,MAAMC,aAAa,GAAG9F,IAAH,oBAAGA,IAAI,CAAEb,MAAN,CAAc4G,EAAD,IAAQ;AACzC,QAAI,CAACA,EAAE,CAACC,SAAJ,IAAiB,CAACD,EAAE,CAACE,OAAzB,EAAkC;AAChC,aAAOF,EAAP;AACD,KAFD,MAEO;AACL,aAAOA,EAAE,CAACC,SAAH,GAAeL,GAAf,IAAsBI,EAAE,CAACE,OAAH,GAAaN,GAA1C;AACD;AACF,GANqB,CAAtB;AAQA,SAAOG,aAAP,oBAAOA,aAAa,CAAE5H,GAAf,CAAoB6H,EAAD,IAAQA,EAAE,CAACpH,GAA9B,CAAP;AACD,CAbM","sourcesContent":["import {\n ProductAttributeDTO,\n CustomField,\n AttributeRuleDTOConstraintEnum,\n ProductDTO,\n ProductVariantDTO,\n InventoryAvailability,\n OptionDefinitionDTO,\n SelectedOptionDTO,\n IdReferenceDTO,\n CategoryDTO,\n ProductVariantLabelDTO,\n} from '@sentecacommerce/sdk'\n\nimport {\n AttributeRulesMap,\n CombinationsMap,\n BooleanKVP,\n InventoryAvailabilityType,\n MetaInformationType,\n OptionsType,\n} from '../index'\n\nimport { createEmbededVideo } from './createEmbededVideo'\n\nimport { getTranslatableField } from '../../../utils'\n\n// export const createMappedInventory = (\n// currentVariant: ProductVariantDraftDTO,\n// inventory?: SkuReservationResponseDTO\n// ) => {\n// const currentInventory = inventory?.find(\n// (x) => x.sku === currentVariant.sku\n// )\n\n// const mappedInventory = {\n// ...currentInventory,\n// status:\n// currentInventory?.status === SkuReservationDTOStatusEnum.Available\n// ? true\n// : false,\n// inventoryId: currentInventory?.inventoryReservations?.[0].inventoryId,\n// quantity: currentInventory?.inventoryReservations?.[0].quantity,\n// }\n\n// return mappedInventory\n// }\n\nexport const createCustomFieldsMap = (customFields?: CustomField[]) => {\n return customFields?.reduce((map: BooleanKVP, currentObj) => {\n map[currentObj.field] = currentObj.value\n return map\n }, {})\n}\n\nexport const createCombinationsMap = (\n mappedAttributeRulesKeys: string[],\n attributesArray: {\n variantId: string\n attributes: ProductAttributeDTO[]\n }[]\n) => {\n const combinationsMap: CombinationsMap = {}\n mappedAttributeRulesKeys.forEach((key) => {\n attributesArray.forEach((p) => {\n const currentKey = p.attributes.find((x) => x.name === key)\n const filtered = p.attributes.filter((x) => x.name !== key)\n\n let currentCombination = combinationsMap[currentKey?.value]\n\n if (!currentCombination) {\n currentCombination = {\n params: {},\n value: '',\n }\n }\n\n currentCombination.value = p.variantId\n\n filtered.forEach((attribute) => {\n currentCombination.params = {\n ...currentCombination.params,\n [attribute.value]: p.variantId,\n }\n })\n\n combinationsMap[currentKey?.value] = currentCombination\n })\n })\n\n return combinationsMap\n}\n\nexport const assignCombinationsToAttributeRules = (\n mappedAttributeRules: AttributeRulesMap,\n combinationsMap: CombinationsMap\n) => {\n Object.keys(mappedAttributeRules).forEach((key) => {\n const current = mappedAttributeRules[key].values\n Object.keys(current).forEach((currentKey) => {\n mappedAttributeRules[key].values[currentKey].combinations =\n combinationsMap[currentKey]?.params\n })\n })\n}\n\nexport const createProductContent = (\n data: any\n): { key: string; name: string; content: string } => {\n return {\n key: data.key,\n name: getTranslatableField(data.label),\n content: getTranslatableField(data.content),\n }\n}\n\n// Add grouped images for SD color variants\nexport const createCollapseKeyImagesMap = (product?: ProductDTO) => {\n const mappedKeys = product?.variants?.reduce((res, cur) => {\n if (!res[cur.collapseKey as string]) {\n res[cur.collapseKey as string] = []\n }\n res[cur.collapseKey as string].push(cur)\n return res\n }, {})\n\n return mappedKeys\n}\n\nexport const createAttributeRulesMap = (product?: ProductDTO) => {\n const uniqueRules = product?.attributeRules?.filter(\n (x) => x.constraint === AttributeRuleDTOConstraintEnum.CombinationUnique\n )\n const reduceVariantsToAttributeRuleValues = (map: any, attribute: any) => {\n const found = uniqueRules?.find((x) => x.attributeName === attribute.name)\n if (found) {\n if (!map[attribute.name]) {\n map[attribute.name] = {\n ...found,\n label: getTranslatableField(attribute.data.label),\n values: {},\n }\n }\n\n map[attribute.name] = {\n ...map[attribute.name],\n values: {\n ...map[attribute.name].values,\n [attribute.value]: {\n label: getTranslatableField(attribute.valueData.label),\n extra: attribute.valueData.extra,\n },\n },\n }\n }\n\n return map\n }\n\n const mappedAttributeRules = product?.variants\n ?.map((v) => v.attributes)\n .flat()\n .reduce(reduceVariantsToAttributeRuleValues, {})\n\n return mappedAttributeRules\n}\n\nexport const createMappedOptions = (\n options?: OptionDefinitionDTO[]\n): OptionsType[] => {\n const mappedOptions =\n options?.map((currentOption) => {\n return {\n definitionKey: currentOption.key,\n label: getTranslatableField(currentOption?.label),\n elements: currentOption.options?.map((subOption) => {\n return {\n optionKey: subOption.key,\n label: getTranslatableField(subOption?.label),\n imageIndex: subOption?.imageIndex,\n }\n }),\n }\n }) || []\n\n return mappedOptions\n}\n\nexport type SelectedOptionType = {\n label?: string\n value?: { key?: string; label?: string; imageIndex?: number }\n}\n\nexport const createSelectedOption2 = (\n options?: OptionsType[],\n selectedOption?: SelectedOptionDTO\n): SelectedOptionType => {\n const currentOption = options?.find(\n (availableOption) =>\n availableOption.definitionKey === selectedOption?.definitionKey\n )\n\n const value = currentOption?.elements?.find(\n (element) => element.optionKey === selectedOption?.optionKey\n )\n\n return {\n label: currentOption?.label,\n value: {\n key: value?.optionKey,\n imageIndex: value?.imageIndex,\n label: value?.label,\n },\n }\n}\n\nexport const createSelectedOption = (\n options?: OptionDefinitionDTO[],\n selectedOption?: SelectedOptionDTO\n): SelectedOptionType => {\n const currentOption = options?.find(\n (availableOption) => availableOption.key === selectedOption?.definitionKey\n )\n\n const value = currentOption?.options?.find(\n (optionValue) => optionValue.key === selectedOption?.optionKey\n )\n\n return {\n label: getTranslatableField(currentOption?.label),\n value: {\n key: value?.key,\n imageIndex: value?.imageIndex,\n label: getTranslatableField(value?.label),\n },\n }\n}\n\nexport const createMappedAttributes = (currentVariant: ProductVariantDTO) => {\n const mappedAttributes =\n currentVariant.attributes?.reduce(\n (attributeArray: ProductAttributeDTO[], attribute) => {\n attributeArray.push({\n name: attribute.name,\n value: attribute.value,\n valueData: attribute.valueData,\n })\n return attributeArray\n },\n []\n ) || []\n\n return mappedAttributes\n}\n\nexport const processAvailabilityPerStore = (\n availabilities?: InventoryAvailability[]\n): InventoryAvailabilityType[] | undefined => {\n return availabilities\n ?.filter((x) => !x.isPhysical)\n ?.map(\n ({\n acceptsBackorders,\n stockLocationName,\n restockableInDays,\n availableQuantity,\n }) => {\n return {\n storeName: getTranslatableField(stockLocationName),\n availableQuantity,\n acceptsBackorders,\n restockableInDays: restockableInDays,\n }\n }\n )\n}\n\nexport const getProductVideos = (assets: MetaInformationType['assets']) => {\n if (assets?.youtube) {\n const videos = assets.youtube.sources.map((a) => {\n const embeded = createEmbededVideo(a)\n return {\n type: 'video',\n source: a.url,\n iframe: embeded.iframe,\n thumb: { url: embeded.thumbnail },\n }\n })\n\n return videos\n }\n return []\n}\n\nexport const formatCategories = (\n categories?: IdReferenceDTO[],\n rootCategoryId?: string\n) => {\n let results\n\n if (\n categories?.some((cat) =>\n cat.resource?.custom?.some(\n (customField: any) => customField.field === 'isTemporary'\n )\n )\n ) {\n type PathType = {\n [key: string]: string\n }\n type CategoryType = CategoryDTO & { hasChildCategories: boolean }\n\n const cats = categories.reduce((result, category) => {\n result[category.resourceId] = {\n ...category.resource,\n hasChildCategories: false,\n }\n\n return result\n }, {} as CategoryDTO[])\n\n const paths = Object.values(cats).reduce((result, category) => {\n const parents = (category?.ancestors as IdReferenceDTO[])\n .map((parent: any) => {\n return (cats?.[parent?.resourceId] as any)?._id\n })\n .filter(Boolean)\n\n parents.forEach((parent: any) => {\n ;(cats as CategoryType[])[parent].hasChildCategories = true\n })\n\n result[category._id as string] = [...parents, category._id]\n\n return result\n }, {} as PathType[])\n\n const mainPaths = Object.values(cats as CategoryType[] & IdReferenceDTO[])\n .filter((category: CategoryType) => category.hasChildCategories === false)\n .map((category) => paths?.[category._id as string])\n .map((paths) => paths.map((path: string) => cats?.[path]))\n .filter(\n (paths) =>\n !paths.some(\n (path: { custom: any }) =>\n path?.custom?.find(\n (custom: any) => custom.field === 'isTemporary'\n )?.value ?? false\n )\n )?.[0]\n .flat()\n\n results = mainPaths\n } else {\n results = categories?.filter(\n (cat) =>\n cat?.resourceId === rootCategoryId ||\n cat?.resource?.ancestors?.some(\n (ancestor: any) => ancestor.resource === rootCategoryId\n )\n )\n }\n\n const formattedResults = (results as IdReferenceDTO[])?.map((category) => {\n if (category.resource) {\n const resource = category.resource as CategoryDTO\n\n return {\n name: getTranslatableField(resource.name),\n id: category.resourceId || '',\n link: `/${getTranslatableField(resource.slug)}/c`,\n }\n }\n\n const cat = (category as unknown) as CategoryDTO\n\n return {\n name: getTranslatableField(cat.name),\n id: cat._id || '',\n link: `/${getTranslatableField(cat.slug)}/c`,\n }\n })\n\n return formattedResults || []\n}\n\nexport const createLabelsMap = (data?: ProductVariantLabelDTO[]) => {\n // Filter only labels that are currently active\n const now = new Date().getTime()\n\n const currentLabels = data?.filter((el) => {\n if (!el.validFrom || !el.validTo) {\n return el\n } else {\n return el.validFrom < now && el.validTo > now\n }\n })\n\n return currentLabels?.map((el) => el.key)\n}\n"],"file":"index.js"}
|
@@ -11,6 +11,7 @@ export declare const createProductContent: (data: any) => {
|
|
11
11
|
name: string;
|
12
12
|
content: string;
|
13
13
|
};
|
14
|
+
export declare const createCollapseKeyImagesMap: (product?: ProductDTO | undefined) => {} | undefined;
|
14
15
|
export declare const createAttributeRulesMap: (product?: ProductDTO | undefined) => any;
|
15
16
|
export declare const createMappedOptions: (options?: OptionDefinitionDTO[] | undefined) => OptionsType[];
|
16
17
|
export declare type SelectedOptionType = {
|
package/package.json
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"name": "@sentecacommerce-theme/lib",
|
3
3
|
"sideEffects": false,
|
4
|
-
"version": "0.12.
|
4
|
+
"version": "0.12.63",
|
5
5
|
"main": "dist/cjs/index.js",
|
6
6
|
"module": "dist/esm/index.js",
|
7
7
|
"types": "dist/types/index.d.ts",
|
@@ -28,9 +28,9 @@
|
|
28
28
|
"build:types": "tsc --emitDeclarationOnly --declaration --declarationDir dist/types",
|
29
29
|
"dev": "yarn build:esm --watch"
|
30
30
|
},
|
31
|
-
"gitHead": "
|
31
|
+
"gitHead": "23b0e6c849dede416af70244dcb41af8310e90f6",
|
32
32
|
"dependencies": {
|
33
|
-
"@sentecacommerce-theme/base": "^0.12.
|
33
|
+
"@sentecacommerce-theme/base": "^0.12.63",
|
34
34
|
"@sentecacommerce/sdk": "2.0.133",
|
35
35
|
"body-scroll-lock": "^3.1.5",
|
36
36
|
"copy-to-clipboard": "^3.3.1",
|