UNPKG

@shopgate/engage

Version:
61 lines • 9.45 kB
function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}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);}import sortBy from'lodash/sortBy';import setWith from'lodash/setWith';import{i18n}from'@shopgate/engage/core';/** * @param {Object} attribute Customer attribute. * @returns {string} */var mapCustomerAttributeType=function mapCustomerAttributeType(attribute){if(attribute.values&&attribute.values.length){if(attribute.type==='collectionOfValues'){return'multiselect';}return'select';}switch(attribute.type){case'number':return'number';case'boolean':return'checkbox';case'date':return'date';case'callingNumber':return'phone_picker';default:return'text';}};/** * Generates customer attributes form field config * @param {Object} options Options for the helper * @param {Array} options.customerAttributes Customer attributes. * @param {Array} options.supportedCountries A list of supported countries. * @param {Array} options.countrySortOrder Sort order for supported countries. * @param {Object} options.userLocation User location for better phone picker defaults. * @param {boolean} options.allowPleaseChoose Allows please choose option for required attributes. * @returns {Object} */export var generateCustomerAttributesFields=function generateCustomerAttributesFields(_ref){var customerAttributes=_ref.customerAttributes,supportedCountries=_ref.supportedCountries,countrySortOrder=_ref.countrySortOrder,userLocation=_ref.userLocation,_ref$allowPleaseChoos=_ref.allowPleaseChoose,allowPleaseChoose=_ref$allowPleaseChoos===void 0?true:_ref$allowPleaseChoos;return _extends({},Object.assign.apply(Object,[{}].concat(sortBy(customerAttributes,['sequenceId']).map(function(attribute){return _defineProperty({},"attribute_".concat(attribute.code),_extends({type:mapCustomerAttributeType(attribute),label:"".concat(attribute.name," ").concat(attribute.isRequired?'*':'')},attribute.values?{options:_extends({},!attribute.isRequired?{'':''}:{},{},attribute.isRequired&&attribute.type!=='collectionOfValues'&&allowPleaseChoose?{'':i18n.text('common.please_choose')}:{},{},Object.assign.apply(Object,[{}].concat(sortBy(attribute.values,['sequenceId']).map(function(option){return _defineProperty({},option.code,option.name);}))))}:{},{},attribute.type==='callingNumber'?{config:{supportedCountries:supportedCountries,countrySortOrder:countrySortOrder,userLocation:userLocation}}:null));}))));};/** * Generates form constraints for attributes. * @param {Object} customerAttributes Customer attributes. * @returns {Object} */export var generateFormConstraints=function generateFormConstraints(customerAttributes){return _extends({},Object.assign.apply(Object,[{}].concat(customerAttributes.map(function(attribute){var constraint={};if(attribute.isRequired||attribute.type==='date'){constraint["attribute_".concat(attribute.code)]={};}if(attribute.isRequired){constraint["attribute_".concat(attribute.code)].presence={message:'validation.required',allowEmpty:false};}if(attribute.type==='date'){constraint["attribute_".concat(attribute.code)].datetime={dateOnly:true,message:'validation.date'};}return constraint;}))));};/** * Maps the type of an attribute value. * @param {Object|string|string[]|number} value Attribute value. * @param {*} attribute The attribute configuration. * @returns {Object|string|number} */var mapAttributeType=function mapAttributeType(value,attribute){var _attribute$values;// Multi select if(attribute.type==='collectionOfValues'){return(value||[]).map(function(v){return{code:v};});}// Single select. if((_attribute$values=attribute.values)===null||_attribute$values===void 0?void 0:_attribute$values.length){return{code:value.toString()};}// Number type. if(attribute.type==='number'){return value.length?parseFloat(value.replace(',','.')||0):null;}// Text types (date is just a formatted text) if(attribute.type==='text'||attribute.type==='date'){return value!==null?value.toString():'';}return value;};/** * Extracts attributes from form data as expected by the API. * @param {Object} customerAttributes Customer attributes. * @param {Object} formData Form data. * @returns {Object} */export var extractAttributes=function extractAttributes(customerAttributes,formData){return customerAttributes.map(function(attribute){return{code:attribute.code,value:mapAttributeType(formData["attribute_".concat(attribute.code)],attribute)};})// Removes wrong numbers (sometimes generated by the form builder when emptying the field) .filter(function(attribute){return!Number.isNaN(attribute.value);})// Removes all attributes that are empty / no longer set. .filter(function(attribute){var _attribute$value,_attribute$value2,_attribute$value2$cod,_attribute$value3,_attribute$value3$,_attribute$value3$$co;return(// Any number. typeof attribute.value==='number'||// Non-empty strings. typeof attribute.value==='string'&&attribute.value.length||// Booleans are always allowed. attribute.value===true||attribute.value===false||// Object containing the code. !Array.isArray((_attribute$value=attribute.value)===null||_attribute$value===void 0?void 0:_attribute$value.code)&&((_attribute$value2=attribute.value)===null||_attribute$value2===void 0?void 0:(_attribute$value2$cod=_attribute$value2.code)===null||_attribute$value2$cod===void 0?void 0:_attribute$value2$cod.length)||(// Array containing at least one code. (_attribute$value3=attribute.value)===null||_attribute$value3===void 0?void 0:(_attribute$value3$=_attribute$value3[0])===null||_attribute$value3$===void 0?void 0:(_attribute$value3$$co=_attribute$value3$.code)===null||_attribute$value3$$co===void 0?void 0:_attribute$value3$$co.length));});};/** * Extracts the default values for the form * @param {Object} customerAttributes Customer attributes. * @returns {Object} */export var extractDefaultValues=function extractDefaultValues(customerAttributes){return Object.assign.apply(Object,[{}].concat(customerAttributes.map(function(attribute){var value=attribute.value;if(value){if(Array.isArray(value)&&value[0]&&_typeof(value[0])==='object'){// Multi select L:95 value=value.reduce(function(acc,val){return[].concat(acc,[val.code]);},[]);}else if(_typeof(value)==='object'){// Single select L:100 value=value.code;}else if(value!==true&&value!==false){value=value.toString();}}return _defineProperty({},"attribute_".concat(attribute.code),value);})));};/** * Converts pipeline validation errors * @param {Array} errors The errors * @param {Array} attributes Attributes that where sent with the register request. Used to retrieve * extra form field for attribute validation errors. * @returns {Object|null} */export var convertPipelineValidationErrors=function convertPipelineValidationErrors(errors){var attributes=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];if(!Array.isArray(errors)||errors.length===0){return null;}var converted=errors.reduce(function(result,error){var _error$path=error.path,path=_error$path===void 0?[]:_error$path,code=error.code,_error$subentityPath=error.subentityPath,subentityPath=_error$subentityPath===void 0?[]:_error$subentityPath,displayMessage=error.displayMessage;var message=error.message;if(path.length===0&&subentityPath.length===0){result.general.push(error);return result;}var validationPath;if(path.length>0){message=i18n.text('validation.checkField');validationPath=path.slice(2).join('.');}else if(subentityPath.length>0&&subentityPath.includes('attributes')){/** * Validation errors for customer attributes needs special handling. They are sent * as an array to the server, which only includes the fields where an actual value was set. * The subentityPath of attribute validation errors will only contain an array index which * needs to be mapped to tha actual field id. * * So here in the first step, we search for the subentity path entry that comes after the * "attributes" entry and convert it back to an integer which can be used to determine * and entry within the attribute data that was used for the request. */var attributeIndex=parseInt(subentityPath[subentityPath.indexOf('attributes')+1],10);message=i18n.text('validation.checkField');// Retrieve the attribute code to mock a validation path that can be used to find the correct // form field. validationPath="attributes.attribute_".concat(attributes[attributeIndex].code);}else if(subentityPath.length>0){var field=subentityPath[subentityPath.length-1];if(code===409&&field==='emailAddress'){message=i18n.text('validation.emailConflict');}else{message=i18n.text('validation.checkField');}validationPath=subentityPath.join('.');}if(validationPath){setWith(result.validation,validationPath,displayMessage||message,Object);}return result;},{validation:{},general:[]});return converted;};