import baseReducer from '#utils/baseReducer' ; import { Dispatch } from 'react' ; import { CommerceLayerConfig } from '#context/CommerceLayerContext' ; import { Order } from '@commercelayer/sdk' ; import { getOrderContext } from '#reducers/OrderReducer' ; import { AddressResource } from './AddressReducer' ; import getSdk from '#utils/getSdk' ; import { AddressUpdate } from '@commercelayer/sdk' ; export type ShippingAddressActionType = 'setShippingAddress' | 'setShippingCustomerAddressId' | 'cleanup' ; export interface ShippingAddressActionPayload { _shipping_address_clone_id : string ; shippingCustomerAddressId : string ; } export type ShippingAddressState = Partial < ShippingAddressActionPayload > ; export interface ShippingAddressAction { type : ShippingAddressActionType ; payload : Partial < ShippingAddressActionPayload > ; } export const shippingAddressInitialState = { _shipping_address_clone_id : '' , } ; export type SetShippingAddress = ( id : string , options ? : { config : CommerceLayerConfig ; dispatch : Dispatch < ShippingAddressAction > ; order ? : Order | null ; getOrder ? : getOrderContext ; customerAddressId ? : string ; } ) => Promise < void > ; export const setShippingAddress = async ( id , options ) => { try { if ( options ?. order ) { if ( options . customerAddressId ) { const sdk = getSdk ( options . config ) ; const attributes = { id , reference : options . customerAddressId , } ; await sdk . addresses . update ( attributes ) ; } options . dispatch ( { type : 'setShippingAddress' , payload : { _shipping_address_clone_id : id , } , } ) ; } } catch ( error ) { console . error ( error ) ; } } ; type SetShippingCustomerAddressId = ( args : { dispatch : Dispatch < ShippingAddressAction > ; order : Order ; setCloneAddress : ( id : string , resource : AddressResource ) => void ; } ) => void ; export const setShippingCustomerAddressId = async ( { dispatch , order , setCloneAddress } ) => { const customerAddressId = order ?. shipping_address ?. reference ; try { if ( customerAddressId ) { dispatch ( { type : 'setShippingCustomerAddressId' , payload : { shippingCustomerAddressId : customerAddressId } , } ) ; setCloneAddress ( customerAddressId , 'shipping_address' ) ; } } catch ( error ) { console . error ( 'error' , error ) ; } } ; const type = [ 'setShippingAddress' , 'setShippingCustomerAddressId' , 'cleanup' , ] ; const shippingAddressReducer = ( state , reducer ) : ShippingAddressState => baseReducer < ShippingAddressState , ShippingAddressAction , ShippingAddressActionType [ ] > ( state , reducer , type ) ; export default shippingAddressReducer ;