import { orderStatuses } from '@appConstants'; import { GET_ORDERS } from '@graphql/queries/standalone/orders'; import type { IOrdersResponse } from '@types'; interface IOrdersArguments { userEmail: string; status?: string; after?: string; search: string; } interface IOrderVars { status: string; userEmail: string; first: number; after?: string; search: string; } export async function useOrders(args: IOrdersArguments) { const cartStore = useCartStore(); const variables = reactive({ status: args.status || '', userEmail: args.userEmail, first: 10, after: args.after, search: args.search, }); const { pending, data, error, refresh } = await useAsyncQuery(GET_ORDERS, variables); const orders = ref( data.value?.orders.edges.filter((order) => order.node.status !== orderStatuses.PENDING) ?? [], ); const pageInfo = computed(() => data.value?.orders.pageInfo ?? null); if (!error.value && data.value?.orders.edges) { if (args.status === orderStatuses.PENDING) { cartStore.setCurrentOrders(data.value?.orders.edges[0].node); } } watch( () => variables.after, async (newCursor, oldCursor) => { if (!newCursor || newCursor === oldCursor) return; await refresh(); const newEdges = data.value?.orders.edges ?? []; orders.value.push(...newEdges); }, ); watch( [ () => variables.status, () => variables.search, ], async () => { variables.after = ''; await refresh(); orders.value = data.value?.orders.edges ?? []; }, ); watch(error, (err) => { if (err) { console.error('useOrders error:', err); } }); return { pending, orders, pageInfo, variables, }; }