Skip to content

Commit

Permalink
fix: Reset form when isBusiness prop changes status
Browse files Browse the repository at this point in the history
  • Loading branch information
acasazza committed Jan 28, 2022
1 parent a3dfb19 commit 2c7da18
Show file tree
Hide file tree
Showing 8 changed files with 95 additions and 51 deletions.
47 changes: 4 additions & 43 deletions src/components/AddressInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,40 +10,11 @@ import { BaseInputComponentProps, AddressInputName } from '#typings'
import BillingAddressFormContext from '#context/BillingAddressFormContext'
import ShippingAddressFormContext from '#context/ShippingAddressFormContext'
import isEmpty from 'lodash/isEmpty'
import { businessMandatoryField } from '#utils/validateFormFields'

const propTypes = components.AddressInput.propTypes
const displayName = components.AddressInput.displayName

type CustomerOptionalField = Extract<
AddressInputName,
| 'billing_address_line_2'
| 'billing_address_company'
| 'shipping_address_line_2'
| 'shipping_address_company'
>

type BusinessOptionalField = Extract<
AddressInputName,
| 'billing_address_first_name'
| 'billing_address_last_name'
| 'shipping_address_first_name'
| 'shipping_address_last_name'
>

const businessOptionalFields: BusinessOptionalField[] = [
'billing_address_first_name',
'billing_address_last_name',
'shipping_address_first_name',
'shipping_address_last_name',
]

const customerOptionalFields: CustomerOptionalField[] = [
'billing_address_company',
'shipping_address_company',
'billing_address_line_2',
'shipping_address_line_2',
]

export type AddressInputProps = {
name: AddressInputName
} & Omit<BaseInputComponentProps, 'name'> &
Expand Down Expand Up @@ -92,19 +63,9 @@ const AddressInput: FunctionComponent<AddressInputProps> = (props) => {
setHasError(false)
}
}, [value, billingAddress?.errors, shippingAddress?.errors])
let mandatoryField = true
if (
(billingAddress.isBusiness || shippingAddress.isBusiness) &&
businessOptionalFields.includes(p.name as BusinessOptionalField)
) {
mandatoryField = false
}
if (
(!billingAddress.isBusiness || !shippingAddress.isBusiness) &&
customerOptionalFields.includes(p.name as CustomerOptionalField)
) {
mandatoryField = false
}
let mandatoryField = billingAddress.isBusiness
? businessMandatoryField(p.name, billingAddress.isBusiness)
: businessMandatoryField(p.name, shippingAddress.isBusiness)
const reqField = required !== undefined ? required : mandatoryField
const errorClassName =
billingAddress?.errorClassName || shippingAddress?.errorClassName
Expand Down
6 changes: 4 additions & 2 deletions src/components/AddressesContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,12 @@ const displayName = components.AddressesContainer.displayName
export type AddressesContainerProps = {
children: ReactNode
shipToDifferentAddress?: boolean
isBusiness?: boolean
}
const AddressesContainer: FunctionComponent<AddressesContainerProps> = (
props
) => {
const { children, shipToDifferentAddress = false } = props
const { children, shipToDifferentAddress = false, isBusiness = false } = props
const [state, dispatch] = useReducer(addressReducer, addressInitialState)
const { order, orderId, updateOrder } = useContext(OrderContext)
const config = useContext(CommerceLayerContext)
Expand All @@ -41,6 +42,7 @@ const AddressesContainer: FunctionComponent<AddressesContainerProps> = (
type: 'setShipToDifferentAddress',
payload: {
shipToDifferentAddress,
isBusiness,
},
})
return () => {
Expand All @@ -49,7 +51,7 @@ const AddressesContainer: FunctionComponent<AddressesContainerProps> = (
payload: {},
})
}
}, [shipToDifferentAddress])
}, [shipToDifferentAddress, isBusiness])
const contextValue = {
...state,
setAddressErrors: (errors: BaseError[], resource: AddressResource) =>
Expand Down
13 changes: 10 additions & 3 deletions src/components/BillingAddressForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ type BillingAddressFormProps = {
children: ReactNode
reset?: boolean
errorClassName?: string
isBusiness?: boolean
} & Omit<JSX.IntrinsicElements['form'], 'onSubmit'>

const BillingAddressForm: FunctionComponent<BillingAddressFormProps> = (
Expand All @@ -34,11 +33,11 @@ const BillingAddressForm: FunctionComponent<BillingAddressFormProps> = (
errorClassName,
autoComplete = 'on',
reset = false,
isBusiness = false,
...p
} = props
const { validation, values, errors, reset: resetForm } = useRapidForm()
const { setAddressErrors, setAddress } = useContext(AddressesContext)
const { setAddressErrors, setAddress, isBusiness } =
useContext(AddressesContext)
const {
saveAddressToCustomerAddressBook,
order,
Expand Down Expand Up @@ -125,6 +124,14 @@ const BillingAddressForm: FunctionComponent<BillingAddressFormProps> = (
}
}
}, [errors, values, reset, include, includeLoaded])
useEffect(() => {
if (ref) {
ref.current?.reset()
resetForm({ target: ref.current } as any)
setAddressErrors([], 'billing_address')
setAddress({ values: {} as Address, resource: 'billing_address' })
}
}, [isBusiness])
const setValue = (
name: AddressField | AddressInputName | AddressCountrySelectName,
value: any
Expand Down
3 changes: 3 additions & 0 deletions src/components/SaveAddressesButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ const SaveAddressesButton: FunctionComponent<SaveAddressesButtonProps> = (
saveAddresses,
billingAddressId,
shippingAddressId,
isBusiness,
} = useContext(AddressContext)
console.log('isBusiness', isBusiness)
const { order } = useContext(OrderContext)
const { addresses, isGuest } = useContext(CustomerContext)
const [forceDisable, setForceDisable] = useState(disabled)
Expand Down Expand Up @@ -81,6 +83,7 @@ const SaveAddressesButton: FunctionComponent<SaveAddressesButtonProps> = (
shipping_address,
shippingAddressId,
})
debugger
const disable =
disabled ||
customerEmail ||
Expand Down
24 changes: 21 additions & 3 deletions src/components/ShippingAddressForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const ShippingAddressForm: FunctionComponent<ShippingAddressFormProps> = (
...p
} = props
const { validation, values, errors, reset: resetForm } = useRapidForm()
const { setAddressErrors, setAddress, shipToDifferentAddress } =
const { setAddressErrors, setAddress, shipToDifferentAddress, isBusiness } =
useContext(AddressesContext)
const {
saveAddressToCustomerAddressBook,
Expand Down Expand Up @@ -96,7 +96,13 @@ const ShippingAddressForm: FunctionComponent<ShippingAddressFormProps> = (
})
}
}
setAddress({ values: values as Address, resource: 'shipping_address' })
setAddress({
values: {
...values,
...(isBusiness && { business: isBusiness }),
} as Address,
resource: 'shipping_address',
})
}
const checkboxChecked =
ref.current?.querySelector(
Expand All @@ -117,6 +123,14 @@ const ShippingAddressForm: FunctionComponent<ShippingAddressFormProps> = (
}
}
}, [values, errors, shipToDifferentAddress, reset, include, includeLoaded])
useEffect(() => {
if (ref) {
ref.current?.reset()
resetForm({ target: ref.current } as any)
setAddressErrors([], 'shipping_address')
setAddress({ values: {} as Address, resource: 'shipping_address' })
}
}, [isBusiness])
const setValue = (
name: AddressField | AddressInputName | AddressCountrySelectName,
value: any
Expand All @@ -125,7 +139,11 @@ const ShippingAddressForm: FunctionComponent<ShippingAddressFormProps> = (
[name.replace('shipping_address_', '')]: value,
}
setAddress({
values: { ...values, ...field },
values: {
...values,
...field,
...(isBusiness && { business: isBusiness }),
},
resource: 'shipping_address',
})
}
Expand Down
1 change: 1 addition & 0 deletions src/reducers/AddressReducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export interface AddressActionPayload {
shipToDifferentAddress: boolean
billingAddressId: string
shippingAddressId: string
isBusiness: boolean
}

export type AddressState = Partial<AddressActionPayload>
Expand Down
1 change: 1 addition & 0 deletions src/utils/addressesManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export const billingAddressController: BillingAddressController = ({
requiresBillingInfo,
}) => {
let billingDisable = !isEmpty(errors) || isEmpty(billing_address)
debugger
if (isEmpty(errors) && !isEmpty(billing_address)) {
let billingInfo = [...addressFields]
if (requiresBillingInfo) billingInfo = [...billingInfo, 'billing_info']
Expand Down
51 changes: 51 additions & 0 deletions src/utils/validateFormFields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { BaseState } from '#typings/index'
import { ResourceErrorType, BaseError } from '#typings/errors'
import { AddressField, addressFields } from '#reducers/AddressReducer'
import { AddressCreate } from '@commercelayer/sdk'
import { AddressInputName } from '#typings'

const EMAIL_PATTERN = /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$/

Expand Down Expand Up @@ -94,6 +95,7 @@ export interface FieldsExist {
}

export const fieldsExist: FieldsExist = (address, schema = addressFields) => {
console.log('address', address)
if (!address['business']) {
const required = without(schema, 'line_2', 'company')
const validAddress = keys(address).filter((k) =>
Expand All @@ -109,4 +111,53 @@ export const fieldsExist: FieldsExist = (address, schema = addressFields) => {
}
}

type CustomerOptionalField = Extract<
AddressInputName,
| 'billing_address_line_2'
| 'billing_address_company'
| 'shipping_address_line_2'
| 'shipping_address_company'
>

type BusinessOptionalField = Extract<
AddressInputName,
| 'billing_address_first_name'
| 'billing_address_last_name'
| 'shipping_address_first_name'
| 'shipping_address_last_name'
>

const businessOptionalFields: BusinessOptionalField[] = [
'billing_address_first_name',
'billing_address_last_name',
'shipping_address_first_name',
'shipping_address_last_name',
]

const customerOptionalFields: CustomerOptionalField[] = [
'billing_address_company',
'shipping_address_company',
'billing_address_line_2',
'shipping_address_line_2',
]

export function businessMandatoryField(
fieldName: AddressInputName,
isBusiness?: boolean
) {
if (
isBusiness &&
businessOptionalFields.includes(fieldName as BusinessOptionalField)
) {
return false
}
if (
!isBusiness &&
customerOptionalFields.includes(fieldName as CustomerOptionalField)
) {
return false
}
return true
}

export default validateFormFields

0 comments on commit 2c7da18

Please sign in to comment.