use-enriched-company.ts2.2 KBView on GitHub /**
* Hook for enriching company profiles with Crustdata
*
* Manual-only enrichment - does NOT auto-enrich on mount
* Prevents re-enrichment if data was refreshed within the past 7 days
*/
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { trpcClient } from '@/providers/query-provider';
import { toast } from 'sonner';
const MIN_DAYS_BETWEEN_ENRICHMENT = 7;
export function useEnrichedCompany(domain: string) {
const queryClient = useQueryClient();
// Get profile (read-only, no auto-enrichment)
const profileQuery = useQuery({
queryKey: ['enrichment', 'company', domain],
queryFn: () => trpcClient.enrichment.getCompanyProfile.query({ domain }),
staleTime: 5 * 60 * 1000,
retry: false,
});
// Enrich mutation (user action)
const enrichMutation = useMutation({
mutationFn: () => trpcClient.enrichment.enrichCompany.mutate({ domain }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['enrichment', 'company', domain] });
},
onError: (error) => {
console.error('[useEnrichedCompany] Enrichment failed:', error);
},
});
const company = profileQuery.data?.data;
const metadata = profileQuery.data?.metadata;
const isEnriched = metadata?.isEnriched || false;
// Check if data was recently refreshed (within 7 days)
const isRecentlyRefreshed = (): boolean => {
if (!metadata?.lastRefreshedAt) return false;
const refreshDate = new Date(metadata.lastRefreshedAt);
const daysSinceRefresh = (Date.now() - refreshDate.getTime()) / (1000 * 60 * 60 * 24);
return daysSinceRefresh <= MIN_DAYS_BETWEEN_ENRICHMENT;
};
// Wrapper function that checks freshness before enriching
const enrich = async () => {
if (isRecentlyRefreshed()) {
const daysSinceRefresh = metadata?.daysSinceRefresh || 0;
toast.info(
`This company was enriched ${daysSinceRefresh} day${daysSinceRefresh === 1 ? '' : 's'} ago. Enrichment is limited to once per week.`,
);
return;
}
return enrichMutation.mutateAsync();
};
return {
company,
metadata,
isLoading: profileQuery.isLoading,
isEnriched,
enrich,
isEnriching: enrichMutation.isPending,
enrichError: enrichMutation.error,
};
}