Skip to content

Commit

Permalink
feat: updated account, cart, currency and payments hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
field123 committed Jan 12, 2024
1 parent f5fdfb0 commit 3626f92
Show file tree
Hide file tree
Showing 18 changed files with 253 additions and 15 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useElasticPath } from "../../elasticpath"
import { UseQueryOptionsWrapper } from "../../types"
import { AccountAddress, ResourcePage } from "@moltin/sdk"
import { useQuery, UseQueryResult } from "@tanstack/react-query"
import { queryKeysFactory } from "../../shared/util/query-keys-factory"

const ACCOUNT_ADDRESSES_QUERY_KEY = "account-addresses" as const

export const accountAddressesQueryKeys = queryKeysFactory(
ACCOUNT_ADDRESSES_QUERY_KEY,
)
type AccountAddressesQueryKey = typeof accountAddressesQueryKeys

export function useAccountAddresses(
accountId: string,
options?: UseQueryOptionsWrapper<
ResourcePage<AccountAddress>,
Error,
ReturnType<AccountAddressesQueryKey["list"] & string>
> & { ep?: { accountMemberToken?: string } },
): Partial<ResourcePage<AccountAddress>> &
Omit<UseQueryResult<ResourcePage<AccountAddress>, Error>, "data"> {
const { client } = useElasticPath()
const { data, ...rest } = useQuery({
queryKey: [...accountAddressesQueryKeys.list({ accountId })],
queryFn: () =>
client.AccountAddresses.All({
account: accountId,
...(options?.ep?.accountMemberToken && {
token: options.ep.accountMemberToken,
}),
}),
...options,
})

return { ...data, ...rest } as const
}
1 change: 1 addition & 0 deletions packages/react-shopper-hooks/src/account/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from "./hooks/use-account-member"
export * from "./hooks/use-authed-account-member"
export * from "./account-provider"
export * from "./hooks/use-account-addresses"
11 changes: 11 additions & 0 deletions packages/react-shopper-hooks/src/cart/cart-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
useAddBundleProductToCart,
useAddProductToCart,
useAddPromotionToCart,
useDeleteCartItems,
} from "./hooks"
import { useRemovePromotionCode } from "./hooks/use-remove-promotion"

Expand All @@ -33,6 +34,7 @@ export const CartItemsContext = createContext<
useScopedAddBundleProductToCart: () => ReturnType<
typeof useAddBundleProductToCart
>
useClearCart: () => ReturnType<typeof useDeleteCartItems>
} & Omit<ReturnType<typeof useGetCart>, "data">)
| undefined
>(undefined)
Expand Down Expand Up @@ -127,6 +129,14 @@ export function CartProvider({
},
})

const clearCart = () =>
useDeleteCartItems(cartId, {
onSuccess: async (updatedData) => {
setCartQueryData(updatedData)
await invalidateCartQuery()
},
})

return (
<CartItemsContext.Provider
value={{
Expand All @@ -139,6 +149,7 @@ export function CartProvider({
useScopedRemovePromotion: removePromotion,
useScopedAddProductToCart: addProductToCart,
useScopedAddBundleProductToCart: addBundleItemToCart,
useClearCart: clearCart,
...rest,
}}
>
Expand Down
5 changes: 4 additions & 1 deletion packages/react-shopper-hooks/src/cart/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
export * from "./use-get-cart"
export * from "./use-remove-cart-item"
export * from "./use-update-cart-items"
export * from "./use-add-cart-item"
export * from "./use-add-product"
export * from "./use-add-promotion"
export * from "./use-add-bundle-product-to-cart"
export * from "./use-checkout"
export * from "./use-add-custom-item"
export * from "./use-delete-cart-items"
31 changes: 31 additions & 0 deletions packages/react-shopper-hooks/src/cart/hooks/use-add-custom-item.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { useMutation, UseMutationOptions } from "@tanstack/react-query"
import { CartItemsResponse } from "@moltin/sdk"
import { useElasticPath } from "../../elasticpath"

export type CartAddCustomItemReq = {
type: "custom_item"
name: string
description?: string
sku?: string
quantity: number
price: {
amount: number
includes_tax: boolean
}
custom_inputs?: Record<string, any>
shipping_group_id?: string
tax?: any[]
}

export const useAddCustomItemToCart = (
cartId: string,
options?: UseMutationOptions<CartItemsResponse, Error, CartAddCustomItemReq>,
) => {
const { client } = useElasticPath()
return useMutation({
mutationFn: async (props) => {
return client.Cart(cartId).AddCustomItem(props)
},
...options,
})
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { useMutation, UseMutationOptions } from "@tanstack/react-query"
import { useElasticPath } from "../../elasticpath"
import { CartAdditionalHeaders, CartItemsResponse } from "@moltin/sdk"
import { SelectedOptions } from "../types/bundle.type"

type CartAddProductReq = {
productId: string
Expand Down
75 changes: 75 additions & 0 deletions packages/react-shopper-hooks/src/cart/hooks/use-checkout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { useMutation, UseMutationOptions } from "@tanstack/react-query"
import { useElasticPath } from "../../elasticpath"
import {
Address,
CartAdditionalHeaders,
CheckoutCustomer,
CheckoutCustomerObject,
Order,
Resource,
} from "@moltin/sdk"

export type UseCheckoutReq = {
customer: string | CheckoutCustomer | CheckoutCustomerObject
billingAddress: Partial<Address>
shippingAddress?: Partial<Address>
additionalHeaders?: CartAdditionalHeaders
}

export const useCheckout = (
cartId: string,
options?: UseMutationOptions<Resource<Order>, Error, UseCheckoutReq>,
) => {
const { client } = useElasticPath()
return useMutation({
mutationFn: async ({
customer,
billingAddress,
shippingAddress,
additionalHeaders,
}: UseCheckoutReq) => {
return client
.Cart(cartId)
.Checkout(customer, billingAddress, shippingAddress, additionalHeaders)
},
...options,
})
}

export type UseCheckoutWithAccountReq = {
contact: string | CheckoutCustomer | CheckoutCustomerObject
billingAddress: Partial<Address>
token: string
shippingAddress?: Partial<Address>
additionalHeaders?: CartAdditionalHeaders
}

export const useCheckoutWithAccount = (
cartId: string,
options?: UseMutationOptions<
Resource<Order>,
Error,
UseCheckoutWithAccountReq
>,
) => {
const { client } = useElasticPath()
return useMutation({
mutationFn: async ({
contact,
billingAddress,
shippingAddress,
token,
additionalHeaders,
}: UseCheckoutWithAccountReq) => {
return client.Cart(cartId).CheckoutWithAccountManagementToken(
contact,
billingAddress,
shippingAddress,
token,
// @ts-ignore TODO: Fix type definition in js-sdk
additionalHeaders,
)
},
...options,
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { useMutation, UseMutationOptions } from "@tanstack/react-query"
import { useElasticPath } from "../../elasticpath"
import { CartItemsResponse } from "@moltin/sdk"

type CartDeleteCartItemsReq = {}

export const useDeleteCartItems = (
cartId: string,
options?: UseMutationOptions<
CartItemsResponse,
Error,
CartDeleteCartItemsReq
>,
) => {
const { client } = useElasticPath()
return useMutation({
mutationFn: async () => {
return client.Cart(cartId).RemoveAllItems()
},
...options,
})
}
2 changes: 1 addition & 1 deletion packages/react-shopper-hooks/src/cart/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ export * from "./cart-provider"
export * from "./use-cart-hook"
export * from "./types/cart-types"
export * from "./hooks"
export * from "./util/enhance-cart-response"
export * from "./util"
28 changes: 16 additions & 12 deletions packages/react-shopper-hooks/src/cart/util/enhance-cart-response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,11 @@ import { CartState, RefinedCartItem } from "../../cart"
import { groupCartItems } from "./group-cart-items"

export function enhanceCartResponse(
cart?: ResourceIncluded<Cart, CartIncluded>,
): CartState | undefined {
if (!cart) {
return undefined
}

const items =
cart.included?.items
.filter(
(item) => item.type === "cart_item" || item.type === "custom_item",
)
.sort(sortItemByCreatedAsc) ?? []
cart: ResourceIncluded<Cart, CartIncluded>,
): CartState {
const items = !!cart.included?.items
? enhanceCartItems(cart.included.items)
: []

const groupedItems = groupCartItems(cart.included?.items ?? [])

Expand All @@ -33,3 +26,14 @@ function sortItemByCreatedAsc(a: CartItem, b: CartItem) {
new Date(b.meta.timestamps.created_at).getTime()
)
}

export function enhanceCartItems(items: CartItem[]) {
const enhanced =
items
?.filter(
(item) => item.type === "cart_item" || item.type === "custom_item",
)
.sort(sortItemByCreatedAsc) ?? []

return enhanced as ReadonlyArray<RefinedCartItem>
}
2 changes: 2 additions & 0 deletions packages/react-shopper-hooks/src/cart/util/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./enhance-cart-response"
export * from "./group-cart-items"
1 change: 1 addition & 0 deletions packages/react-shopper-hooks/src/currency/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./use-currencies"
27 changes: 27 additions & 0 deletions packages/react-shopper-hooks/src/currency/hooks/use-currencies.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { useElasticPath } from "../../elasticpath"
import { UseQueryOptionsWrapper } from "../../types"
import type { Currency, ResourcePage } from "@moltin/sdk"
import { useQuery, UseQueryResult } from "@tanstack/react-query"
import { queryKeysFactory } from "../../shared/util/query-keys-factory"

const CURRENCY_QUERY_KEY = "currency" as const

export const currencyQueryKeys = queryKeysFactory(CURRENCY_QUERY_KEY)
type CurrencyQueryKey = typeof currencyQueryKeys

export function useCurrencies(
options?: UseQueryOptionsWrapper<
ResourcePage<Currency, never>,
Error,
ReturnType<CurrencyQueryKey["list"]>
>,
): Partial<ResourcePage<Currency, never>> &
Omit<UseQueryResult<ResourcePage<Currency, never>, Error>, "data"> {
const { client } = useElasticPath()
const { data, ...rest } = useQuery({
queryKey: currencyQueryKeys.list(),
queryFn: () => client.Currencies.All(),
...options,
})
return { ...data, ...rest } as const
}
1 change: 1 addition & 0 deletions packages/react-shopper-hooks/src/currency/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./hooks"
2 changes: 2 additions & 0 deletions packages/react-shopper-hooks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ export * from "./store"
export * from "./product"
export * from "./account"
export * from "./elasticpath"
export * from "./payments"
export * from "./currency"
export * from "@elasticpath/shopper-common"
1 change: 1 addition & 0 deletions packages/react-shopper-hooks/src/payments/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./use-payments"
20 changes: 20 additions & 0 deletions packages/react-shopper-hooks/src/payments/hooks/use-payments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { useMutation, UseMutationOptions } from "@tanstack/react-query"
import { useElasticPath } from "../../elasticpath"
import { ConfirmPaymentResponse, PaymentRequestBody } from "@moltin/sdk"

export type UsePaymentsReq = {
orderId: string
payment: PaymentRequestBody
}

export const usePayments = (
options?: UseMutationOptions<ConfirmPaymentResponse, Error, UsePaymentsReq>,
) => {
const { client } = useElasticPath()
return useMutation({
mutationFn: async ({ orderId, payment }: UsePaymentsReq) => {
return client.Orders.Payment(orderId, payment)
},
...options,
})
}
1 change: 1 addition & 0 deletions packages/react-shopper-hooks/src/payments/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./hooks"

0 comments on commit 3626f92

Please sign in to comment.