1 import { useMutation, UseMutationOptions } from "@tanstack/react-query"
2
3 import { queryKeysFactory } from "../../lib/query-key-factory"
4
5 import { HttpTypes } from "@medusajs/types"
6 import { sdk } from "../../lib/client"
7 import { queryClient } from "../../lib/query-client"
8 import { ordersQueryKeys } from "./orders"
9 import { FetchError } from "@medusajs/js-sdk"
10
11 const FULFILLMENTS_QUERY_KEY = "fulfillments" as const
12 export const fulfillmentsQueryKeys = queryKeysFactory(FULFILLMENTS_QUERY_KEY)
13
14 export const useCreateFulfillment = (
15 options?: UseMutationOptions<any, FetchError, any>
16 ) => {
17 return useMutation({
18 mutationFn: (payload: any) => sdk.admin.fulfillment.create(payload),
19 onSuccess: (data: any, variables: any, context: any) => {
20 queryClient.invalidateQueries({ queryKey: fulfillmentsQueryKeys.lists() })
21 queryClient.invalidateQueries({
22 queryKey: ordersQueryKeys.all,
23 })
24 options?.onSuccess?.(data, variables, context)
25 },
26 ...options,
27 })
28 }
29
30 export const useCancelFulfillment = (
31 id: string,
32 options?: UseMutationOptions<any, FetchError, any>
33 ) => {
34 return useMutation({
35 mutationFn: () => sdk.admin.fulfillment.cancel(id),
36 onSuccess: (data: any, variables: any, context: any) => {
37 queryClient.invalidateQueries({ queryKey: fulfillmentsQueryKeys.lists() })
38 queryClient.invalidateQueries({
39 queryKey: ordersQueryKeys.all,
40 })
41 options?.onSuccess?.(data, variables, context)
42 },
43 ...options,
44 })
45 }
46
47 export const useCreateFulfillmentShipment = (
48 fulfillmentId: string,
49 options?: UseMutationOptions<
50 { fulfillment: HttpTypes.AdminFulfillment },
51 FetchError,
52 HttpTypes.AdminCreateFulfillmentShipment
53 >
54 ) => {
55 return useMutation({
56 mutationFn: (payload: HttpTypes.AdminCreateFulfillmentShipment) =>
57 sdk.admin.fulfillment.createShipment(fulfillmentId, payload),
58 onSuccess: (data: any, variables: any, context: any) => {
59 queryClient.invalidateQueries({
60 queryKey: ordersQueryKeys.all,
61 })
62 options?.onSuccess?.(data, variables, context)
63 },
64 ...options,
65 })
66 }