Skip to content

Commit

Permalink
feat: add a company extra field check
Browse files Browse the repository at this point in the history
  • Loading branch information
b3aton authored and kris liu committed Jul 20, 2022
1 parent 4095ae8 commit 29f6334
Show file tree
Hide file tree
Showing 7 changed files with 175 additions and 53 deletions.
57 changes: 46 additions & 11 deletions apps/storefront/src/pages/registered/RegisterComplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { RegisteredContext } from './context/RegisteredContext'
import RegisteredStepButton from './component/RegisteredStepButton'
import { B3CustomForm } from '../../components'

import { createBCCompanyUser, createB2BCompanyUser } from '../../shared/service/b2b'
import { createBCCompanyUser, createB2BCompanyUser, uploadB2BFile } from '../../shared/service/b2b'

import {
RegisterFileds, CustomFieldItems, Base64, validatorRules,
Expand Down Expand Up @@ -52,7 +52,7 @@ export default function RegisterComplete(props: RegisterCompleteProps) {
const {
contactInformation, bcContactInformationFields, passwordInformation, accountType,
additionalInformation, addressBasicFields, addressExtraFields, companyInformation,
emailMarketingNewsletter,
emailMarketingNewsletter, companyAttachment, companyExtraFields,
} = state

const emailName = accountType === '1' ? 'workEmailAddress' : 'emailAddress'
Expand Down Expand Up @@ -182,16 +182,18 @@ export default function RegisterComplete(props: RegisterCompleteProps) {
b2bFields.customerId = customerId || ''
b2bFields.storeHash = (window as any).b3?.setting?.storeHash || 'rtmh8fqr05'
if (companyInformation) {
const extraFields:Array<CustomFieldItems> = []
companyInformation.forEach((item: any) => {
if (item.name === 'companyName' || item.name === 'companyEmail' || item.name === 'companyPhoneNumber') {
b2bFields[item.name] = item?.default || ''
} else {
const itemExtraField: CustomFieldItems = {}
itemExtraField.fieldName = Base64.decode(item.name)
itemExtraField.fieldValue = item?.default || ''
extraFields.push(itemExtraField)
}
b2bFields[item.name] = item?.default || ''
})
}

if (companyExtraFields) {
const extraFields:Array<CustomFieldItems> = []
companyExtraFields.forEach((item: any) => {
const itemExtraField: CustomFieldItems = {}
itemExtraField.fieldName = Base64.decode(item.name)
itemExtraField.fieldValue = item?.default || ''
extraFields.push(itemExtraField)
})
b2bFields.extraFields = extraFields
}
Expand Down Expand Up @@ -221,6 +223,33 @@ export default function RegisterComplete(props: RegisterCompleteProps) {
})
}

let attachments: File[] = []
if (companyAttachment) {
companyAttachment.forEach((field: any) => {
if (field.name === 'companyAttachments') {
attachments = field.default
}
})
}

try {
const fileResponse = await Promise.all(attachments.map(
(file: File) => uploadB2BFile({
file,
type: 'companyAttachedFile',
}),
))

b2bFields.fileList = fileResponse.reduce((fileList: any, res: any) => {
if (res.code === 200) {
fileList = [...fileList, res.data]
}
return fileList
}, [])
} catch (error) {
b2bFields.fileList = []
}

return createB2BCompanyUser(b2bFields)
}

Expand Down Expand Up @@ -268,6 +297,12 @@ export default function RegisterComplete(props: RegisterCompleteProps) {
}
handleNext()
} catch (error) {
dispatch({
type: 'loading',
payload: {
isLoading: false,
},
})
console.log(error, 'error')
} finally {
dispatch({
Expand Down
37 changes: 20 additions & 17 deletions apps/storefront/src/pages/registered/Registered.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,23 +89,26 @@ export default function Registered() {

const filterPasswordInformation = customerAccount.length && customerAccount.filter((field: RegisterFileds) => !field.custom && field.fieldType === 'password')
const newPasswordInformation: Array<RegisterFileds> = conversionDataFormat(filterPasswordInformation)
dispatch({
type: 'all',
payload: {
accountType: '1',
isLoading: false,
storeName,
contactInformation: [...contactInformationFields],
additionalInformation: [...newAdditionalInformation],
bcContactInformationFields: [...bcContactInformationFields],
companyInformation: [...companyInformationFields, ...newCompanyExtraFields],
companyAttachment: [...companyAttachmentsFields],
addressBasicFields: [...addressInformationFields],
addressExtraFields: [...addressExtraFields],
countryList: [...countries],
passwordInformation: [...newPasswordInformation],
},
})
if (dispatch) {
dispatch({
type: 'all',
payload: {
accountType: '1',
isLoading: false,
storeName,
contactInformation: [...contactInformationFields],
additionalInformation: [...newAdditionalInformation],
bcContactInformationFields: [...bcContactInformationFields],
companyExtraFields: [...newCompanyExtraFields],
companyInformation: [...companyInformationFields],
companyAttachment: [...companyAttachmentsFields],
addressBasicFields: [...addressInformationFields],
addressExtraFields: [...addressExtraFields],
countryList: [...countries],
passwordInformation: [...newPasswordInformation],
},
})
}
setLogo(registerLogo)
} catch (e) {
console.log(e)
Expand Down
116 changes: 95 additions & 21 deletions apps/storefront/src/pages/registered/RegisteredDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {

import {
Box,
Alert,
} from '@mui/material'

import styled from '@emotion/styled'
Expand All @@ -23,8 +24,11 @@ import {
addressInformationFields,
Country,
State,
Base64,
} from './config'

import { validateBCCompanyExtraFields } from '../../shared/service/b2b'

const InformationFourLabels = styled('h4')(() => ({
marginBottom: '20px',
}))
Expand All @@ -36,18 +40,27 @@ const AddressBox = styled(Box)(() => ({
},
}))

const TipContent = styled('div')(() => ({
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
}))

export default function RegisteredDetail(props: any) {
const { handleBack, handleNext, activeStep } = props

const { state, dispatch } = useContext(RegisteredContext)

const [errorMessage, setErrorMessage] = useState('')

const {
accountType,
companyInformation = [],
companyAttachment = [],
addressBasicFields = [],
addressExtraFields = [],
countryList = [],
companyExtraFields = [],
} = state

const {
Expand Down Expand Up @@ -85,7 +98,7 @@ export default function RegisteredDetail(props: any) {
}
}

setValue('state', stateCode && stateList.find((state: State) => state.stateCode === stateCode) ? stateCode : '')
setValue('state', stateCode && (stateList.find((state: State) => state.stateCode === stateCode) || stateList.length === 0) ? stateCode : '')

dispatch({
type: 'stateList',
Expand All @@ -112,40 +125,101 @@ export default function RegisteredDetail(props: any) {
return () => subscription.unsubscribe()
}, [countryList])

const setRegisterFiledsValue = (formFields: Array<any>, formData: CustomFieldItems) => formFields.map((fields) => {
fields.default = formData[fields.name] || fields.default
return fields
const showLading = (isShow = false) => {
dispatch({
type: 'loading',
payload: {
isLoading: isShow,
},
})
}

const getErrorMessage = (data: any, errorKey: string) => {
if (data[errorKey] && typeof data[errorKey] === 'object') {
const errors = data[errorKey]

let message = ''
Object.keys(errors).forEach((error) => {
message += `${error}:${errors[error]}`
})

return message
}

return data.errMsg || ''
}

const setRegisterFiledsValue = (formFields: Array<any>, formData: CustomFieldItems) => formFields.map((field) => {
field.default = formData[field.name] || field.default
return field
})

const handleAccountToFinish = (event: MouseEvent) => {
handleSubmit((data: CustomFieldItems) => {
const newCompanyInformation = setRegisterFiledsValue(companyInformation, data)
const newCompanyAttachment = setRegisterFiledsValue(companyAttachment, data)
const newAddressBasicFields = setRegisterFiledsValue(addressBasicFields, data)
const newAddressExtraFields = setRegisterFiledsValue(addressExtraFields, data)

dispatch({
type: 'all',
payload: {
companyInformation: [...newCompanyInformation],
companyAttachment: [...newCompanyAttachment],
addressBasicFields: [...newAddressBasicFields],
addressExtraFields: [...newAddressExtraFields],
},
})
handleNext()
handleSubmit(async (data: CustomFieldItems) => {
showLading(true)

try {
const extraFields = companyExtraFields.map((field: any) => ({
fieldName: Base64.decode(field.name),
fieldValue: data[field.name] || field.default,
}))

const res = await validateBCCompanyExtraFields({
extraFields,
})

if (res.code !== 200) {
setErrorMessage(getErrorMessage(res.data, 'extraFields'))
showLading(false)
return
}

setErrorMessage('')

const newCompanyInformation = setRegisterFiledsValue(companyInformation, data)
const newCompanyExtraFields = setRegisterFiledsValue(companyExtraFields, data)
const newCompanyAttachment = setRegisterFiledsValue(companyAttachment, data)
const newAddressBasicFields = setRegisterFiledsValue(addressBasicFields, data)
const newAddressExtraFields = setRegisterFiledsValue(addressExtraFields, data)

dispatch({
type: 'all',
payload: {
companyInformation: [...newCompanyInformation],
companyExtraFields: [...newCompanyExtraFields],
companyAttachment: [...newCompanyAttachment],
addressBasicFields: [...newAddressBasicFields],
addressExtraFields: [...newAddressExtraFields],
},
})
showLading(false)
handleNext()
} catch (error) {
showLading(false)
}
})(event)
}

return (
<div>
{
errorMessage && (
<Alert
severity="error"
>
<TipContent>
{ errorMessage }
</TipContent>
</Alert>
)
}
{
accountType === '1' ? (
<>
<Box>
<InformationFourLabels>Business Details</InformationFourLabels>
<B3CustomForm
formFields={companyInformation}
formFields={[...companyInformation, ...companyExtraFields]}
errors={errors}
control={control}
getValues={getValues}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ interface RegisterState {
bcContactInformationFields?: Array<RegisterFileds> | Array<[]>,
emailMarketingNewsletter?: Boolean,
companyInformation?: Array<RegisterFileds> | Array<[]>,
companyExtraFields?: Array<RegisterFileds> | Array<[]>,
companyAttachment?: Array<RegisterFileds> | Array<[]>,
addressBasicFields?: Array<RegisterFileds> | Array<[]>,
addressExtraFields?: Array<RegisterFileds> | Array<[]>,
Expand Down Expand Up @@ -43,6 +44,7 @@ const initState = {
accountType: '',
emailMarketingNewsletter: false,
companyInformation: [],
companyExtraFields: [],
companyAttachment: [],
addressBasicFields: [],
addressExtraFields: [],
Expand Down
4 changes: 4 additions & 0 deletions apps/storefront/src/shared/service/b2b/api/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,8 @@ interface CustomFieldItems {
[key: string]: any
}

const storeHash = (window as any).b3?.setting?.storeHash || 'rtmh8fqr05'

export const createBCCompanyUser = (data: CustomFieldItems): CustomFieldItems => B3Request.post('/api/v2/proxy', RequestType.B2BRest, data)

export const validateBCCompanyExtraFields = (data: CustomFieldItems): CustomFieldItems => B3Request.post('/api/v2/extra-fields/company/validate', RequestType.B2BRest, { ...data, storeHash })
10 changes: 6 additions & 4 deletions apps/storefront/src/shared/service/b2b/graphql/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,13 @@ const conversionData = (data: CustomFieldItems) => {
}
let str = '{'
Object.keys(data).forEach((item: any, index) => {
if (typeof data[item] === 'string' || typeof data[item] === 'number' || typeof data[item] === 'undefined') {
if (typeof data[item] === 'string' || typeof data[item] === 'number') {
if (index === Object.keys(data).length - 1) {
str += `${item}: `
str += `${JSON.stringify(data[item])}`
str += `${JSON.stringify(`${data[item]}`)}`
} else {
str += `${item}: `
str += `${JSON.stringify(data[item])}, `
str += `${JSON.stringify(`${data[item]}`)}, `
}
}

Expand Down Expand Up @@ -116,7 +116,9 @@ const createCompanyUser = (data: any) => `mutation{
city: "${data.city}",
state: "${data.state}",
zipCode: "${data.zipCode}",
extraFields: ${conversionArr(data.extraFields)}}) {
extraFields: ${conversionArr(data.extraFields)}
fileList: ${conversionArr(data.fileList)}
}) {
company {
id,
companyStatus,
Expand Down
2 changes: 2 additions & 0 deletions apps/storefront/src/shared/service/b2b/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {

import {
createBCCompanyUser,
validateBCCompanyExtraFields,
} from './api/register'

export {
Expand All @@ -24,4 +25,5 @@ export {
uploadB2BFile,
createB2BCompanyUser,
storeB2BBasicInfo,
validateBCCompanyExtraFields,
}

0 comments on commit 29f6334

Please sign in to comment.