use-enriched-person.ts2.3 KBView on GitHub /**
* Hook for enriching person 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 useEnrichedPerson(email: string, linkedinUrl?: string) {
const queryClient = useQueryClient();
// Get profile (read-only, no auto-enrichment)
const profileQuery = useQuery({
queryKey: ['enrichment', 'person', email],
queryFn: () => trpcClient.enrichment.getPersonProfile.query({ email }),
staleTime: 5 * 60 * 1000,
retry: false,
});
// Enrich mutation (user action)
const enrichMutation = useMutation({
mutationFn: () => trpcClient.enrichment.enrichPerson.mutate({ email, linkedinUrl }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['enrichment', 'person', email] });
},
onError: (error) => {
console.error('[useEnrichedPerson] Enrichment failed:', error);
},
});
const profile = profileQuery.data?.data;
const metadata = profileQuery.data?.metadata;
const isEnriched = metadata?.isEnriched || false;
const canEnrich = true;
// 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 contact was enriched ${daysSinceRefresh} day${daysSinceRefresh === 1 ? '' : 's'} ago. Enrichment is limited to once per week.`,
);
return;
}
return enrichMutation.mutateAsync();
};
return {
profile,
metadata,
isLoading: profileQuery.isLoading,
isEnriched,
canEnrich,
enrich,
isEnriching: enrichMutation.isPending,
enrichError: enrichMutation.error,
};
}