Files
edr-platform/apps/edr-freight-web/backoffice/src/components/warehouses/useCompanyOptions.ts
Hagernesh a183f00657 fix(container-returns): dedupe company names in the return picker
freight.companies allows duplicate names, and Mantine v9 throws on duplicate
Autocomplete option values, taking down the whole Container Returns page with
a render error.

Dedupes the option list by trimmed name. resolveId now returns an id only
when exactly one company carries the name — an ambiguous name resolves to
nothing, so the return keeps the typed company name rather than silently
attaching to whichever duplicate happened to come first.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-28 12:11:08 +00:00

38 lines
1.3 KiB
TypeScript

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;
},
};
}