UNPKG

@shopgate/engage

Version:
23 lines • 9.66 kB
import _regeneratorRuntime from"@babel/runtime/regenerator";var _excluded=["serviceLevels"];function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}function _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded);var key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++){key=sourceSymbolKeys[i];if(excluded.indexOf(key)>=0)continue;if(!Object.prototype.propertyIsEnumerable.call(source,key))continue;target[key]=source[key];}}return target;}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return{};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i<sourceKeys.length;i++){key=sourceKeys[i];if(excluded.indexOf(key)>=0)continue;target[key]=source[key];}return target;}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_nonIterableRest();}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance");}function _iterableToArrayLimit(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"]!=null)_i["return"]();}finally{if(_d)throw _e;}}return _arr;}function _arrayWithHoles(arr){if(Array.isArray(arr))return arr;}import{hot}from'react-hot-loader/root';import React,{useCallback,useEffect,useMemo,useState}from'react';import PropTypes from'prop-types';import{css}from'glamor';import classNames from'classnames';import CryptoJs from'crypto-js';import sortBy from'lodash/sortBy';import uniqBy from'lodash/uniqBy';import{themeConfig}from'@shopgate/pwa-common/helpers/config';import{i18n}from'@shopgate/engage/core';import{RadioGroupV2 as RadioGroup,RadioCard,MessageBar}from'@shopgate/engage/components';import{useCheckoutContext}from'@shopgate/engage/checkout/hooks/common';import ShippingMethod from"./ShippingMethod";import connect from"./connector";var variables=themeConfig.variables;var styles={root:css({padding:"0 ".concat(variables.gap.big,"px ").concat(variables.gap.xbig,"px")}).toString(),headline:css({fontSize:'1.25rem',fontWeight:'normal',padding:"0 ".concat(variables.gap.small,"px 0 0"),margin:"0 0 ".concat(variables.gap.small,"px 0"),color:'var(--color-text-high-emphasis)',textTransform:'none'}).toString(),container:css({border:'1px solid #eaeaea',' li:nth-child(2n)':{background:'var(--color-background-accent)'}}).toString(),containerSingle:css({padding:variables.gap.small}).toString(),card:css({display:'flex',alignItems:'center'}).toString(),errorMessage:css({margin:0}).toString(),iOSCard:css({width:'100%',overflow:'hidden',marginBottom:variables.gap.big}).toString()};/** * Hashes a shipping method * @param {Object} method A shipping method * @returns {string} */var hashShippingMethod=function hashShippingMethod(method){if(!method){return null;}var code=method.code,_method$serviceLevel=method.serviceLevel,serviceLevelCode=_method$serviceLevel.code,carrierCode=_method$serviceLevel.carrier.code;return CryptoJs.MD5("".concat(code," ").concat(serviceLevelCode," ").concat(carrierCode)).toString();};/** * Custom replacement for the wrapper component of the RadioCard * @param {Object} props The component props * @returns {JSX} */var CardComponent=function CardComponent(_ref){var children=_ref.children;return React.createElement("li",{className:styles.card},children);};CardComponent.defaultProps={children:null};/** * The shipping methods component. * @returns {JSX} */var ShippingMethods=function ShippingMethods(_ref2){var orderHasDirectShipItems=_ref2.orderHasDirectShipItems;var _useCheckoutContext=useCheckoutContext(),shippingAddress=_useCheckoutContext.shippingAddress,updateShippingMethod=_useCheckoutContext.updateShippingMethod,isLoading=_useCheckoutContext.isLoading,order=_useCheckoutContext.order;var _ref3=(shippingAddress===null||shippingAddress===void 0?void 0:shippingAddress.orderSegment)||{},_ref3$selectedShippin=_ref3.selectedShippingMethod,selectedShippingMethod=_ref3$selectedShippin===void 0?null:_ref3$selectedShippin,_ref3$availableShippi=_ref3.availableShippingMethods,availableShippingMethods=_ref3$availableShippi===void 0?[]:_ref3$availableShippi;var _useState=useState(hashShippingMethod(selectedShippingMethod)),_useState2=_slicedToArray(_useState,2),selectedHash=_useState2[0],setSelectedHash=_useState2[1];useEffect(function(){// Update the selected hash when the selected shipping method updates setSelectedHash(hashShippingMethod(selectedShippingMethod));},[selectedShippingMethod]);/** * The component actually doesn't render shipping methods, but service levels. To improve * data handling, we transform the original data structure to the shape which is required for * the update request. */var shippingMethods=useMemo(function(){// Flat map all service levels of all shipping methods and aggregate with parent (method) data. var unsortedLevels=availableShippingMethods.flatMap(function(method){var serviceLevels=method.serviceLevels,methodData=_objectWithoutProperties(method,_excluded);return serviceLevels.map(function(serviceLevel){var entry=_extends({},methodData,{serviceLevel:serviceLevel});var hash=hashShippingMethod(entry);return _extends({},entry,{hash:hash});});});// Remove duplicated shipping levels that originated from different shipping methods. var dedupedLevels=uniqBy(unsortedLevels,function(_ref4){var _serviceLevel$carrier;var serviceLevel=_ref4.serviceLevel;return"".concat(serviceLevel.code,"#").concat((_serviceLevel$carrier=serviceLevel.carrier)===null||_serviceLevel$carrier===void 0?void 0:_serviceLevel$carrier.code);});// Show cheapest service level first followed by alphabetic name. return sortBy(dedupedLevels,['serviceLevel.cost','serviceLevel.name']);},[availableShippingMethods]);var onChange=useCallback(/*#__PURE__*/function(){var _ref5=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(event,value){var _shippingMethod$servi,_shippingMethod$servi2,_shippingMethod$servi3;var shippingMethod;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:// Determine the selected shipping method by its hash shippingMethod=shippingMethods.find(function(_ref6){var hash=_ref6.hash;return value===hash;});if(shippingMethod){_context.next=3;break;}return _context.abrupt("return");case 3:// Update the local state setSelectedHash(shippingMethod===null||shippingMethod===void 0?void 0:shippingMethod.hash);// Perform the update request _context.next=6;return updateShippingMethod({code:shippingMethod===null||shippingMethod===void 0?void 0:shippingMethod.code,serviceLevel:{code:shippingMethod===null||shippingMethod===void 0?void 0:(_shippingMethod$servi=shippingMethod.serviceLevel)===null||_shippingMethod$servi===void 0?void 0:_shippingMethod$servi.code,carrier:{code:shippingMethod===null||shippingMethod===void 0?void 0:(_shippingMethod$servi2=shippingMethod.serviceLevel)===null||_shippingMethod$servi2===void 0?void 0:(_shippingMethod$servi3=_shippingMethod$servi2.carrier)===null||_shippingMethod$servi3===void 0?void 0:_shippingMethod$servi3.code}}});case 6:case"end":return _context.stop();}},_callee);}));return function(_x,_x2){return _ref5.apply(this,arguments);};}(),[shippingMethods,updateShippingMethod]);if((order===null||order===void 0?void 0:order.status)!=='new'||!orderHasDirectShipItems){return null;}if(shippingMethods.length===0){return React.createElement("div",{className:styles.root},React.createElement("h3",{className:styles.headline},i18n.text('checkout.shippingMethod.title')),React.createElement(MessageBar,{messages:[{type:'error',message:i18n.text("checkout.shippingMethod.errors.".concat(!shippingAddress?'noShippingAddress':'invalidShippingAddress'))}],classNames:{container:styles.errorMessage},showIcons:true}));}return React.createElement("div",{className:styles.root},React.createElement("h3",{className:styles.headline},i18n.text('checkout.shippingMethod.title')),shippingMethods.length===1?React.createElement("div",{className:classNames(styles.container,styles.containerSingle)},React.createElement(ShippingMethod,{shippingMethod:shippingMethods[0]})):React.createElement(RadioGroup,{name:"shipping-methods",value:selectedHash,onChange:onChange,component:"ul",classes:{root:styles.container},disabled:isLoading},shippingMethods.map(function(shippingMethod){return React.createElement(RadioCard,{renderCard:CardComponent,value:shippingMethod.hash,key:shippingMethod.hash},React.createElement(ShippingMethod,{shippingMethod:shippingMethod}));})));};ShippingMethods.defaultProps={orderHasDirectShipItems:false};export default hot(connect(ShippingMethods));