import { useQuery } from "@tanstack/react-query"; import { customersService } from "@/services/customers.service"; /** * Registered customer companies, as Autocomplete options. The picker is an * Autocomplete rather than a Select on purpose: a company that is not on the * system yet is typed in, and only the name is kept. */ export function useCompanyOptions() { const { data, isLoading } = useQuery({ queryKey: ["companies-autocomplete"], queryFn: () => customersService.list({ page: 1, pageSize: 1000 }), staleTime: 5 * 60 * 1000, }); const companies = data?.items ?? []; // Company names are not unique — Mantine throws on duplicate option values, // so the list is deduped by the trimmed name. const names = [...new Set(companies.map((c) => c.name.trim()).filter(Boolean))]; return { loading: isLoading, names, /** * Name → company id, only when exactly one company carries that name. An * ambiguous name resolves to nothing rather than to an arbitrary company: * the container keeps the typed name and no wrong customer is attached. */ resolveId: (name: string): string | undefined => { const key = name.trim().toLowerCase(); const matches = companies.filter((c) => c.name.trim().toLowerCase() === key); return matches.length === 1 ? matches[0].id : undefined; }, }; }