Skip to content

Commit

Permalink
feat: Start implementing new SDK
Browse files Browse the repository at this point in the history
  • Loading branch information
acasazza committed Nov 22, 2021
1 parent 376f551 commit 4107d1e
Show file tree
Hide file tree
Showing 11 changed files with 202 additions and 148 deletions.
2 changes: 1 addition & 1 deletion src/components/AddressesContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const AddressesContainer: FunctionComponent<AddressesContainerProps> = (
) => {
const { children, shipToDifferentAddress = false } = props
const [state, dispatch] = useReducer(addressReducer, addressInitialState)
const { order, orderId, getOrder } = useContext(OrderContext)
const { order, orderId, getOrder, updateOrder } = useContext(OrderContext)
const config = useContext(CommerceLayerContext)
useEffect(() => {
dispatch({
Expand Down
7 changes: 5 additions & 2 deletions src/components/BillingAddressContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,13 @@ const BillingAddressContainer: FunctionComponent<Props> = (props) => {
billingAddressInitialState
)
const config = useContext(CommerceLayerContext)
const { order, getOrder } = useContext(OrderContext)
const { order, getOrder, include, addResourceToInclude } =
useContext(OrderContext)
const { shipToDifferentAddress, setCloneAddress } = useContext(AddressContext)
useEffect(() => {
if (!include?.includes('billing_address')) {
addResourceToInclude({ newResource: 'billing_address' })
}
if (order && config) {
setBillingCustomerAddressId({
dispatch,
Expand All @@ -55,7 +59,6 @@ const BillingAddressContainer: FunctionComponent<Props> = (props) => {
config,
dispatch,
order,
getOrder,
shipToDifferentAddress,
customerAddressId: options?.customerAddressId,
})
Expand Down
19 changes: 14 additions & 5 deletions src/components/CustomerContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import OrderContext from '#context/OrderContext'
import CommerceLayerContext from '#context/CommerceLayerContext'
import components from '#config/components'
import { saveCustomerUser } from '#reducers/CustomerReducer'
import { getOrderContext } from '#reducers/OrderReducer'
import CustomerContext from '#context/CustomerContext'
import { defaultCustomerContext } from '#context/CustomerContext'
import { BaseError } from '#typings/errors'
Expand All @@ -30,14 +29,24 @@ export type CustomerContainer = {
const CustomerContainer: FunctionComponent<CustomerContainer> = (props) => {
const { children, isGuest = false } = props
const [state, dispatch] = useReducer(customerReducer, customerInitialState)
const { order, getOrder } = useContext(OrderContext)
const { order, addResourceToInclude, include, updateOrder } =
useContext(OrderContext)
const config = useContext(CommerceLayerContext)
useEffect(() => {
if (!include?.includes('available_customer_payment_sources') && !isGuest) {
addResourceToInclude({
newResource: 'available_customer_payment_sources',
})
}
if (config.accessToken && isEmpty(state.addresses) && !isGuest) {
getCustomerAddresses({ config, dispatch })
}
if (config.accessToken && order && isEmpty(state.payments) && !isGuest) {
getCustomerPaymentSources({ config, dispatch, order })
if (
order &&
include?.includes('available_customer_payment_sources') &&
!isGuest
) {
getCustomerPaymentSources({ dispatch, order })
}
return () => {
dispatch({ type: 'setCustomerEmail', payload: {} })
Expand All @@ -51,7 +60,7 @@ const CustomerContainer: FunctionComponent<CustomerContainer> = (props) => {
config,
customerEmail,
dispatch,
getOrder: getOrder as getOrderContext,
updateOrder,
order,
})
},
Expand Down
8 changes: 8 additions & 0 deletions src/components/OrderContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import orderReducer, {
OrderCodeType,
AddResourceToInclude,
orderInitialState,
UpdateOrderArgs,
} from '#reducers/OrderReducer'
import CommerceLayerContext from '#context/CommerceLayerContext'
import OrderContext, { defaultOrderContext } from '#context/OrderContext'
Expand Down Expand Up @@ -124,6 +125,13 @@ const OrderContainer: FunctionComponent<OrderContainerProps> = (props) => {
dispatch,
resourcesIncluded: state.include,
}),
updateOrder: async (args: UpdateOrderArgs) =>
await defaultOrderContext['updateOrder']({
...args,
dispatch,
config,
include: state.include,
}),
}
}, [state])
return (
Expand Down
3 changes: 3 additions & 0 deletions src/context/OrderContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
removeGiftCardOrCouponCode,
saveAddressToCustomerAddressBook,
addResourceToInclude,
updateOrder,
} from '#reducers/OrderReducer'
import { Order } from '@commercelayer/sdk'

Expand All @@ -25,6 +26,7 @@ type DefaultContext = {
saveAddressToCustomerAddressBook: SaveAddressToCustomerAddressBook
addResourceToInclude: typeof addResourceToInclude
getOrder: (id: string) => Promise<void | Order>
updateOrder: typeof updateOrder
} & OrderState

export const defaultOrderContext = {
Expand All @@ -36,6 +38,7 @@ export const defaultOrderContext = {
saveAddressToCustomerAddressBook,
addResourceToInclude,
getOrder: async () => {},
updateOrder,
}

const OrderContext = createContext<DefaultContext>(defaultOrderContext)
Expand Down
106 changes: 57 additions & 49 deletions src/reducers/AddressReducer.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import baseReducer from '#utils/baseReducer'
import { Dispatch } from 'react'
import { BaseError } from '#typings/errors'
import { BaseError, ResourceErrorType } from '#typings/errors'
import { CommerceLayerConfig } from '#context/CommerceLayerContext'
import { Address, Order, OrderCollection } from '@commercelayer/js-sdk'
import { Address, AddressCreate, Order, OrderUpdate } from '@commercelayer/sdk'
import isEmpty from 'lodash/isEmpty'
import getSdk from '#utils/getSdk'
import { updateOrder } from './OrderReducer'

export type AddressActionType =
| 'setErrors'
Expand Down Expand Up @@ -40,14 +42,17 @@ export const addressFields: AddressField[] = [
'zip_code',
]

export type AddressResource = 'billingAddress' | 'shippingAddress'
export type AddressResource = Extract<
ResourceErrorType,
'billing_address' | 'shipping_address'
>

export type AddressSchema = Record<AddressField | string, string>
export type AddressSchema = Address

export interface AddressActionPayload {
errors: BaseError[]
billingAddress: AddressSchema
shippingAddress: AddressSchema
billingAddress: AddressCreate
shippingAddress: AddressCreate
shipToDifferentAddress: boolean
billingAddressId: string
shippingAddressId: string
Expand All @@ -67,7 +72,7 @@ export const addressInitialState: AddressState = {
export interface SetAddressErrors {
<V extends BaseError[]>(args: {
errors: V
resource: 'billingAddress' | 'shippingAddress'
resource: Extract<ResourceErrorType, 'billing_address' | 'shipping_address'>
dispatch?: Dispatch<AddressAction>
currentErrors?: V
}): void
Expand All @@ -86,8 +91,8 @@ export interface SetAddress {
export interface SaveAddresses {
(params: {
orderId?: string
order?: OrderCollection | null
getOrder?: (orderId: string) => void
order?: Order | null
updateOrder?: typeof updateOrder
config: CommerceLayerConfig
state: AddressState
dispatch: Dispatch<AddressAction>
Expand All @@ -101,13 +106,13 @@ export const setAddressErrors: SetAddressErrors = ({
resource,
}) => {
const billingErrors =
resource === 'billingAddress'
? errors.filter((e) => e.resource === 'billingAddress')
: currentErrors.filter((e) => e.resource === 'billingAddress')
resource === 'billing_address'
? errors.filter((e) => e.resource === resource)
: currentErrors.filter((e) => e.resource === resource)
const shippingErrors =
resource === 'shippingAddress'
? errors.filter((e) => e.resource === 'shippingAddress')
: currentErrors.filter((e) => e.resource === 'shippingAddress')
resource === 'shipping_address'
? errors.filter((e) => e.resource === resource)
: currentErrors.filter((e) => e.resource === resource)
const finalErrors = [...billingErrors, ...shippingErrors]
dispatch &&
dispatch({
Expand All @@ -130,22 +135,22 @@ export const setAddress: SetAddress = ({ values, resource, dispatch }) => {

type SetCloneAddress = (
id: string,
resource: 'billingAddress' | 'shippingAddress',
resource: AddressResource,
dispatch: Dispatch<AddressAction>
) => void

export const setCloneAddress: SetCloneAddress = (id, resource, dispatch) => {
dispatch({
type: 'setCloneAddress',
payload: {
[`${resource}Id`]: id,
[`${resource}_id`]: id,
},
})
}

export const saveAddresses: SaveAddresses = async ({
config,
getOrder,
updateOrder,
order,
state,
}) => {
Expand All @@ -157,38 +162,41 @@ export const saveAddresses: SaveAddresses = async ({
shippingAddressId,
} = state
try {
const currentBillingAddressRef = order?.billingAddress()?.reference
const orderAttributes: Partial<Record<string, any>> = {
_billingAddressCloneId: billingAddressId,
_shippingAddressCloneId: billingAddressId,
}
if (currentBillingAddressRef === billingAddressId) {
orderAttributes._billingAddressCloneId = order?.billingAddress()?.id
orderAttributes._shippingAddressCloneId = order?.billingAddress()?.id
}
if (!isEmpty(billingAddress) && billingAddress) {
delete orderAttributes._billingAddressCloneId
delete orderAttributes._shippingAddressCloneId
orderAttributes._shippingAddressSameAsBilling = true
orderAttributes.billingAddress = await Address.withCredentials(
config
).create(billingAddress)
}
if (shipToDifferentAddress) {
delete orderAttributes._shippingAddressSameAsBilling
if (shippingAddressId)
orderAttributes._shippingAddressCloneId = shippingAddressId
if (!isEmpty(shippingAddress) && shippingAddress) {
delete orderAttributes._shippingAddressCloneId
orderAttributes.shippingAddress = await Address.withCredentials(
config
).create(shippingAddress)
// const currentBillingAddressRef = order?.billingAddress()?.reference
const sdk = getSdk(config)
if (order) {
const currentBillingAddressRef = order?.billing_address?.reference
const orderAttributes: OrderUpdate = {
id: order?.id,
_billing_address_clone_id: billingAddressId,
_shipping_address_clone_id: billingAddressId,
}
if (currentBillingAddressRef === billingAddressId) {
orderAttributes._billing_address_clone_id = order?.billing_address?.id
orderAttributes._shipping_address_clone_id = order?.shipping_address?.id
}
if (!isEmpty(billingAddress) && billingAddress) {
delete orderAttributes._billing_address_clone_id
delete orderAttributes._shipping_address_clone_id
orderAttributes._shipping_address_same_as_billing = true
const address = await sdk.addresses.create(billingAddress)
orderAttributes.billing_address = sdk.addresses.relationship(address.id)
}
if (shipToDifferentAddress) {
delete orderAttributes._shipping_address_same_as_billing
if (shippingAddressId)
orderAttributes._shipping_address_clone_id = shippingAddressId
if (!isEmpty(shippingAddress) && shippingAddress) {
delete orderAttributes._shipping_address_clone_id
const address = await sdk.addresses.create(shippingAddress)
orderAttributes.shipping_address = sdk.addresses.relationship(
address.id
)
}
}
if (!isEmpty(orderAttributes) && updateOrder) {
await updateOrder({ id: order.id, attributes: orderAttributes })
}
}
if (order && getOrder && !isEmpty(orderAttributes)) {
const o = await Order.build({ id: order.id })
await o.withCredentials(config).update(orderAttributes)
await getOrder(order.id)
}
} catch (error) {
console.error(error)
Expand Down
27 changes: 11 additions & 16 deletions src/reducers/BillingAddressReducer.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import baseReducer from '#utils/baseReducer'
import { Dispatch } from 'react'
import { CommerceLayerConfig } from '#context/CommerceLayerContext'
import { Address, OrderCollection } from '@commercelayer/js-sdk'
import { AddressUpdate, Order } from '@commercelayer/sdk'
import { getOrderContext } from '#reducers/OrderReducer'
import getSdk from '#utils/getSdk'

export type BillingAddressActionType =
| 'setBillingAddress'
Expand Down Expand Up @@ -30,8 +31,7 @@ export type SetBillingAddress = (
options?: {
config: CommerceLayerConfig
dispatch: Dispatch<BillingAddressAction>
order?: OrderCollection
getOrder?: getOrderContext
order?: Order
shipToDifferentAddress?: boolean
customerAddressId?: string
}
Expand All @@ -41,12 +41,12 @@ export const setBillingAddress: SetBillingAddress = async (id, options) => {
try {
if (options?.order) {
if (options.customerAddressId) {
const address = await Address.withCredentials(options.config).find(id)
if (address.reference !== options.customerAddressId) {
await address.withCredentials(options.config).update({
reference: options.customerAddressId,
})
const sdk = getSdk(options.config)
const attributes: AddressUpdate = {
id,
reference: options.customerAddressId,
}
await sdk.addresses.update(attributes)
}
options.dispatch({
type: 'setBillingAddress',
Expand All @@ -56,13 +56,13 @@ export const setBillingAddress: SetBillingAddress = async (id, options) => {
})
}
} catch (error) {
console.error(error)
console.error('Set billing address', error)
}
}

type SetBillingCustomerAddressId = (args: {
dispatch: Dispatch<BillingAddressAction>
order: OrderCollection
order: Order
setCloneAddress: (
id: string,
resource: 'billingAddress' | 'shippingAddress'
Expand All @@ -74,13 +74,8 @@ export const setBillingCustomerAddressId: SetBillingCustomerAddressId = async ({
order,
setCloneAddress,
}) => {
let customerAddressId = order?.billingAddress()?.customerAddressId
const customerAddressId = order?.billing_address?.reference
try {
if (!customerAddressId) {
// @ts-ignore
const address = await order.loadBillingAddress()
customerAddressId = address?.reference
}
if (customerAddressId) {
dispatch({
type: 'setBillingCustomerAddressId',
Expand Down
Loading

0 comments on commit 4107d1e

Please sign in to comment.