All files / src/api/suppliers/hooks useSupplierSearchQuery.ts

100% Statements 67/67
100% Branches 3/3
100% Functions 2/2
100% Lines 67/67

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 681x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 3x 3x 3x 3x 3x  
/**
 * @file useSupplierSearchQuery.ts
 * @module api/suppliers/hooks/useSupplierSearchQuery
 *
 * @summary
 * React Query hook for searching suppliers.
 * Client-side filtering for instant search feedback.
 *
 * @enterprise
 * - Client-side filtering for instant search feedback
 * - Searches name, email, phone, contactName fields
 * - Returns full supplier rows for display flexibility
 * - Case-insensitive matching
 */
 
import { useQuery } from '@tanstack/react-query';
import { getSuppliersPage } from '../supplierListFetcher';
import type { SupplierRow } from '../types';
 
/**
 * Hook to search suppliers by query string.
 * Searches within loaded suppliers (client-side filtering).
 * Useful for autocomplete and search dialogs.
 *
 * @param query - Search query string (e.g., supplier name or email)
 * @param enabled - Whether to fetch (defaults to true)
 * @returns React Query result with filtered supplier results
 *
 * @enterprise
 * - Only fetches when query length >= 2 characters
 * - Client-side filtering for instant search feedback
 * - Returns full supplier rows for display flexibility
 * - Case-insensitive matching
 *
 * @example
 * ```typescript
 * const { data: results } = useSupplierSearchQuery('acme', searchQuery.length >= 2);
 *
 * <Autocomplete
 *   options={results || []}
 *   getOptionLabel={(s) => s.name}
 * />
 * ```
 */
export const useSupplierSearchQuery = (
  query: string,
  enabled: boolean = true,
) => {
  return useQuery({
    queryKey: ['suppliers', 'search', query],
    queryFn: async (): Promise<SupplierRow[]> => {
      if (!query.trim()) return [];
 
      // Fetch suppliers using backend search
      const response = await getSuppliersPage({
        page: 1,
        pageSize: 1000, // Fetch more suppliers for search
        q: query,
      });
 
      return response.items;
    },
    enabled: enabled && query.length >= 2,
    staleTime: 60_000, // 1 minute
    gcTime: 5 * 60_000, // 5 minutes
  });
};