The complete code integration is done. Co-authored-by: Sagnik <sagnik7896@gmail.com> Reviewed-on: #18
47 lines
1.4 KiB
TypeScript
47 lines
1.4 KiB
TypeScript
import { useEffect } from 'react';
|
|
|
|
import { getChatLogs, getLeads } from '@/lib/api';
|
|
import { mapLeadRecordToStoreLead } from '@/lib/crmMappers';
|
|
import { useStore } from '@/store/useStore';
|
|
import type { ChatMessage } from '@/types';
|
|
|
|
export function useCrmBootstrap() {
|
|
const { setLeads, replaceMessages } = useStore();
|
|
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
const hydrate = async () => {
|
|
try {
|
|
const leads = await getLeads();
|
|
if (cancelled) return;
|
|
setLeads(leads.map(mapLeadRecordToStoreLead));
|
|
|
|
const messageEntries = await Promise.all(
|
|
leads.slice(0, 25).map(async (lead) => {
|
|
const logs = await getChatLogs(lead.id);
|
|
return [
|
|
lead.id,
|
|
logs.map((log): ChatMessage => ({
|
|
id: log.id,
|
|
sender: log.sender === 'lead' ? 'user' : 'oracle',
|
|
content: log.content,
|
|
timestamp: new Date(log.created_at ?? Date.now()),
|
|
})),
|
|
] as const;
|
|
}),
|
|
);
|
|
if (!cancelled) {
|
|
replaceMessages(Object.fromEntries(messageEntries));
|
|
}
|
|
} catch {
|
|
// Keep the current in-app fallback state if the CRM backend is unreachable.
|
|
}
|
|
};
|
|
|
|
void hydrate();
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [replaceMessages, setLeads]);
|
|
}
|