vchikalkin d8f374d5da feat(customers): add getCustomers API and enhance customer queries
- Introduced getCustomers action and corresponding server method to fetch customer data with pagination and sorting.
- Updated hooks to support infinite querying of customers, improving data handling in components.
- Refactored ContactsList and related components to utilize the new customer fetching logic, enhancing user experience.
- Adjusted filter labels in dropdowns for better clarity and user understanding.
2025-09-10 12:50:54 +03:00

84 lines
2.2 KiB
TypeScript

'use client';
import { getCustomer, getCustomers, updateCustomer } from '@/actions/api/customers';
import { isCustomerBanned } from '@repo/utils/customer';
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useSession } from 'next-auth/react';
export const useCustomerQuery = (variables?: Parameters<typeof getCustomer>[0]) => {
const { data: session } = useSession();
const telegramId =
variables?.telegramId === undefined ? session?.user?.telegramId : variables?.telegramId;
return useQuery({
enabled: Boolean(telegramId),
queryFn: () => getCustomer({ telegramId }),
queryKey: ['customer', telegramId],
});
};
export const useCustomersQuery = (
variables: Parameters<typeof getCustomers>[0],
enabled?: boolean,
) =>
useQuery({
enabled,
queryFn: () => getCustomers(variables),
queryKey: ['customers', variables],
staleTime: 60 * 1_000,
});
export const useCustomersInfiniteQuery = (
variables: Omit<Parameters<typeof getCustomers>[0], 'pagination'>,
{ enabled = true, pageSize = 10 } = {},
) => {
const queryFunction = ({ pageParam: page = 1 }) =>
getCustomers({
...variables,
pagination: {
page,
pageSize,
},
});
return useInfiniteQuery({
enabled,
getNextPageParam: (lastPage, _allPages, lastPageParameter) => {
if (!lastPage?.customers?.length) return undefined;
return lastPageParameter + 1;
},
initialPageParam: 1,
queryFn: queryFunction,
queryKey: ['customers', variables, 'infinite'],
staleTime: 60 * 1_000,
});
};
export const useIsBanned = () => {
const { data: { customer } = {} } = useCustomerQuery();
if (!customer) return false;
return isCustomerBanned(customer);
};
export const useCustomerMutation = () => {
const { data: session } = useSession();
const telegramId = session?.user?.telegramId;
const queryClient = useQueryClient();
const handleOnSuccess = () => {
if (!telegramId) return;
queryClient.invalidateQueries({
queryKey: ['customer', telegramId],
});
};
return useMutation({
mutationFn: updateCustomer,
onSuccess: handleOnSuccess,
});
};