Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add requiresBillingInfo prop to the ResourceAddress component #815

Merged
merged 3 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/app-elements/src/hooks/useOverlay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,10 @@ export function useOverlay(options?: OverlayOptions): OverlayHook {
[search, options?.queryParam]
)

const Empty = useCallback(() => null, [])

return {
Overlay: show ? Overlay : () => null,
Overlay: show ? Overlay : Empty,
close,
open
}
Expand Down
2 changes: 1 addition & 1 deletion packages/app-elements/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ export {
export {
ResourceAddress,
ResourceAddressFormFields,
resourceAddressFormFieldsSchema,
getResourceAddressFormFieldsSchema,
useResourceAddressOverlay,
type ResourceAddressFormFieldsProps,
type ResourceAddressProps
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const setup = (): RenderResult => {
<MockTokenProvider kind='integration' appSlug='orders' devMode>
<CoreSdkProvider>
<ResourceAddress
resource={presetAddresses.withNotes}
address={presetAddresses.withNotes}
showBillingInfo
editable
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ import { Text } from '#ui/atoms/Text'
import { type Address } from '@commercelayer/sdk'
import { Note, PencilSimple, Phone } from '@phosphor-icons/react'
import isEmpty from 'lodash/isEmpty'
import { useEffect, useState } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { useResourceAddressOverlay } from './useResourceAddressOverlay'

export interface ResourceAddressProps {
/**
* Resource of type `Address`
*/
resource?: Address | null | undefined
address?: Address | null
/**
* Optional address title (if added it will be shown in bold on top of address infos)
*/
Expand All @@ -30,6 +30,11 @@ export interface ResourceAddressProps {
* @default false
*/
showBillingInfo?: boolean
/**
* Optional setting to define if given `Address` `billing_info` data is required.
* @default false
*/
requiresBillingInfo?: boolean
/**
* Optional setting to define if given `Address` `billing_info` data is visible.
* @default true
Expand All @@ -50,35 +55,53 @@ export interface ResourceAddressProps {
*/
export const ResourceAddress = withSkeletonTemplate<ResourceAddressProps>(
({
resource,
address,
title,
editable = false,
showBillingInfo = false,
requiresBillingInfo = false,
showNotes = true,
onCreate,
onUpdate
}) => {
const [address, setAddress] = useState<Address | null | undefined>(resource)
const [stateAddress, setStateAddress] = useState<
Address | null | undefined
>(address)
const { canUser } = useTokenProvider()

const handleOnUpdate = useCallback<
NonNullable<ResourceAddressProps['onUpdate']>
>(
(address) => {
onUpdate?.(address)
setStateAddress(address)
},
[onUpdate, setStateAddress]
)

const handleOnCreate = useCallback<
NonNullable<ResourceAddressProps['onCreate']>
>(
(address) => {
onCreate?.(address)
setStateAddress(address)
},
[onUpdate, setStateAddress]
)

const { ResourceAddressOverlay, openAddressOverlay } =
useResourceAddressOverlay({
address,
address: stateAddress,
showBillingInfo,
requiresBillingInfo,
showNotes,
onCreate: (address) => {
onCreate?.(address)
setAddress(address)
},
onUpdate: (address) => {
onUpdate?.(address)
setAddress(address)
}
onCreate: handleOnCreate,
onUpdate: handleOnUpdate
})

useEffect(() => {
setAddress(resource)
}, [resource?.id])
setStateAddress(address)
}, [address?.id])

return (
<>
Expand All @@ -91,62 +114,62 @@ export const ResourceAddress = withSkeletonTemplate<ResourceAddressProps>(
</Text>
</Spacer>
)}
{address != null ? (
{stateAddress != null ? (
<>
<Text
tag='div'
data-testid='ResourceAddress-fullName'
weight={title == null ? 'bold' : undefined}
variant={title != null ? 'info' : undefined}
>
{address.full_name}
{stateAddress.full_name}
</Text>
<Text
tag='div'
variant='info'
data-testid='ResourceAddress-address'
>
{address.line_1} {address.line_2}
{stateAddress.line_1} {stateAddress.line_2}
<br />
{address.city} {address.state_code} {address.zip_code} (
{address.country_code})
{stateAddress.city} {stateAddress.state_code}{' '}
{stateAddress.zip_code} ({stateAddress.country_code})
</Text>

{address.billing_info != null && showBillingInfo ? (
{stateAddress.billing_info != null && showBillingInfo ? (
<Text
tag='div'
variant='info'
data-testid='ResourceAddress-billingInfo'
>
{address.billing_info}
{stateAddress.billing_info}
</Text>
) : null}

{!isEmpty(address.phone) ||
(showNotes && !isEmpty(address.notes)) ? (
{!isEmpty(stateAddress.phone) ||
(showNotes && !isEmpty(stateAddress.notes)) ? (
<>
<Spacer top='4' bottom='4'>
<Hr variant='dashed' />
</Spacer>
<div className='grid gap-1'>
{!isEmpty(address.phone) && (
{!isEmpty(stateAddress.phone) && (
<div className='flex gap-2 '>
{/* mt-[2px] to keep icon aligned with text */}
<Text tag='div' variant='info' className='mt-[2px]'>
<Phone weight='bold' />
</Text>
<Text tag='div' size='small' variant='info'>
{address.phone}
{stateAddress.phone}
</Text>
</div>
)}
{showNotes && !isEmpty(address.notes) && (
{showNotes && !isEmpty(stateAddress.notes) && (
<div className='flex gap-2'>
<Text tag='div' variant='info' className='mt-[2px]'>
<Note weight='bold' />
</Text>
<Text tag='div' size='small' variant='info'>
{address.notes}
{stateAddress.notes}
</Text>
</div>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,38 @@ import { withSkeletonTemplate } from '#ui/atoms/SkeletonTemplate'
import { Spacer } from '#ui/atoms/Spacer'
import { HookedForm } from '#ui/forms/Form/HookedForm'
import { HookedValidationApiError } from '#ui/forms/ReactHookForm/HookedValidationApiError'
import { type Address } from '@commercelayer/sdk'
import { zodResolver } from '@hookform/resolvers/zod'
import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { type ResourceAddressProps } from './ResourceAddress'
import {
ResourceAddressFormFields,
resourceAddressFormFieldsSchema,
getResourceAddressFormFieldsSchema,
type ResourceAddressFormFieldsProps
} from './ResourceAddressFormFields'

interface ResourceAddressFormProps
extends Omit<ResourceAddressFormFieldsProps, 'name'> {
address?: Address | null | undefined
onChange: (updatedAddress: Address) => void
onCreate: (createdAddress: Address) => void
}
extends Omit<ResourceAddressFormFieldsProps, 'name'>,
Pick<
ResourceAddressProps,
'address' | 'onCreate' | 'onUpdate' | 'requiresBillingInfo'
> {}

export const ResourceAddressForm =
withSkeletonTemplate<ResourceAddressFormProps>(
({
address,
showBillingInfo = false,
requiresBillingInfo = false,
showNotes = true,
onChange,
onUpdate,
onCreate
}) => {
const methods = useForm({
defaultValues: address ?? undefined,
resolver: zodResolver(resourceAddressFormFieldsSchema)
resolver: zodResolver(
getResourceAddressFormFieldsSchema({ requiresBillingInfo })
)
})

const [apiError, setApiError] = useState<any>()
Expand All @@ -47,7 +50,7 @@ export const ResourceAddressForm =
await sdkClient.addresses
.update({ ...formValues, id: address.id })
.then((address) => {
onChange(address)
onUpdate?.(address)
})
.catch((error) => {
setApiError(error)
Expand All @@ -56,7 +59,7 @@ export const ResourceAddressForm =
await sdkClient.addresses
.create({ ...formValues })
.then((address) => {
onCreate(address)
onCreate?.(address)
})
.catch((error) => {
setApiError(error)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { HookedInputTextArea } from '#ui/forms/InputTextArea'
import React, { useEffect, useState } from 'react'
import { useFormContext } from 'react-hook-form'
import { z } from 'zod'
import { type ResourceAddressProps } from './ResourceAddress'

const zodRequiredField = z
.string({
Expand All @@ -18,49 +19,55 @@ const zodRequiredField = z
message: 'Required field'
})

export const resourceAddressFormFieldsSchema = z
.object({
business: z.boolean().nullish().default(false),
first_name: z.string().nullish(),
last_name: z.string().nullish(),
company: z.string().nullish(),
line_1: zodRequiredField,
line_2: z.string().nullish(),
city: zodRequiredField,
zip_code: z.string().nullish(),
state_code: zodRequiredField,
country_code: zodRequiredField,
phone: zodRequiredField,
billing_info: z.string().nullish(),
notes: z.string().nullish()
})
.superRefine((data, ctx) => {
if (data.business === true) {
if (data.company == null || data.company.length === 0) {
ctx.addIssue({
code: 'custom',
path: ['company'],
message: 'Required field'
})
}
} else {
if (data.first_name == null || data.first_name.length === 0) {
ctx.addIssue({
code: 'custom',
path: ['first_name'],
message: 'Required field'
})
}
export const getResourceAddressFormFieldsSchema = ({
requiresBillingInfo = false
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
}: Pick<ResourceAddressProps, 'requiresBillingInfo'> = {}) =>
z
.object({
business: z.boolean().nullish().default(false),
first_name: z.string().nullish(),
last_name: z.string().nullish(),
company: z.string().nullish(),
line_1: zodRequiredField,
line_2: z.string().nullish(),
city: zodRequiredField,
zip_code: z.string().nullish(),
state_code: zodRequiredField,
country_code: zodRequiredField,
phone: zodRequiredField,
billing_info: requiresBillingInfo
? zodRequiredField
: z.string().nullish(),
notes: z.string().nullish()
})
.superRefine((data, ctx) => {
if (data.business === true) {
if (data.company == null || data.company.length === 0) {
ctx.addIssue({
code: 'custom',
path: ['company'],
message: 'Required field'
})
}
} else {
if (data.first_name == null || data.first_name.length === 0) {
ctx.addIssue({
code: 'custom',
path: ['first_name'],
message: 'Required field'
})
}

if (data.last_name == null || data.last_name.length === 0) {
ctx.addIssue({
code: 'custom',
path: ['last_name'],
message: 'Required field'
})
if (data.last_name == null || data.last_name.length === 0) {
ctx.addIssue({
code: 'custom',
path: ['last_name'],
message: 'Required field'
})
}
}
}
})
})

export interface ResourceAddressFormFieldsProps {
/**
Expand Down Expand Up @@ -223,7 +230,9 @@ const SelectCountry: React.FC<{ namePrefix: string }> = ({ namePrefix }) => {
const SelectStates: React.FC<{ namePrefix: string }> = ({ namePrefix }) => {
const [states, setStates] = useState<InputSelectValue[] | undefined>()
const { watch, setValue } =
useFormContext<z.infer<typeof resourceAddressFormFieldsSchema>>()
useFormContext<
z.infer<ReturnType<typeof getResourceAddressFormFieldsSchema>>
>()
const [forceTextInput, setForceTextInput] = useState(false)

const countryCode = watch('country_code')
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export { ResourceAddress, type ResourceAddressProps } from './ResourceAddress'
export {
ResourceAddressFormFields,
resourceAddressFormFieldsSchema,
getResourceAddressFormFieldsSchema,
type ResourceAddressFormFieldsProps
} from './ResourceAddressFormFields'
export { useResourceAddressOverlay } from './useResourceAddressOverlay'
Loading