CognxSafeTrack Claude Sonnet 4.6 commited on
Commit ·
9f72dd7
1
Parent(s): 98240fd
fix(conversations): resolve /conversations blank page + slug→UUID KB routes + WABA banner
Browse files- Add missing /conversations route to App.tsx (was nav-linked but unregistered)
- Apply resolveOrgId() to all 5 KB routes so slug-based org IDs (e.g. xamle-admin-org) no longer cause 404/400
- TemplatesPage: detect WABA-not-configured 400 and show amber banner instead of silently failing
- KnowledgeBasePage: show toast on index-kb 400 (no KB URL) with actionable message
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Files changed (4)
98 unmodified lines9910010110210310498 unmodified lines<Route path="/kb" element={<KnowledgeBasePage />} /><Route path="/campaign-history" element={<CampaignHistoryPage />} /><Route path="/whatsapp-templates" element={<TemplatesPage />} /></Routes></MainLayout>);98 unmodified lines9910010110210310410510610710898 unmodified lines<Route path="/kb" element={<KnowledgeBasePage />} /><Route path="/campaign-history" element={<CampaignHistoryPage />} /><Route path="/whatsapp-templates" element={<TemplatesPage />} /><Routepath="/conversations"element={isCrmActive ? <CrmConversationalDashboard /> : <ConversationalDashboard />}/></Routes></MainLayout>);
3 unmodified lines45678914 unmodified lines24252627282943 unmodified lines73747576777879803 unmodified linesimport { api } from '../lib/api';import { useAuth } from '../lib/auth';import { useTenant } from '../lib/tenant';import { logError } from '../lib/logger';interface KbEntry {14 unmodified linesexport default function KnowledgeBasePage() {const { t } = useTranslation();const { token } = useAuth();const { selectedOrgId } = useTenant();const [data, setData] = useState<KbResponse | null>(null);43 unmodified linessetReindexing(true);try {await api.post(`/v1/organizations/${selectedOrgId}/index-kb`, {}, token);} catch (err) {logError('[KB] Re-index failed:', err);} finally {setReindexing(false);}3 unmodified lines4567891014 unmodified lines2526272829303143 unmodified lines7576777879808182838485868788893 unmodified linesimport { api } from '../lib/api';import { useAuth } from '../lib/auth';import { useTenant } from '../lib/tenant';import { useToast } from '../hooks/useToast';import { logError } from '../lib/logger';interface KbEntry {14 unmodified linesexport default function KnowledgeBasePage() {const { t } = useTranslation();const toast = useToast();const { token } = useAuth();const { selectedOrgId } = useTenant();const [data, setData] = useState<KbResponse | null>(null);43 unmodified linessetReindexing(true);try {await api.post(`/v1/organizations/${selectedOrgId}/index-kb`, {}, token);toast.success('Réindexation lancée avec succès');} catch (err: any) {const msg: string = err?.message ?? '';if (msg.toLowerCase().includes('no kb url') || msg.toLowerCase().includes('not configured')) {toast.error('Aucune URL de base de connaissances configurée. Ajoutez une URL dans Paramètres.');} else {logError('[KB] Re-index failed:', err);toast.error('Échec de la réindexation');}} finally {setReindexing(false);}
56 unmodified lines57585960616244 unmodified lines10710810911011111211311411511611778 unmodified lines19619719819920020156 unmodified linesconst [syncing, setSyncing] = useState(false);const [search, setSearch] = useState('');const [isModalOpen, setIsModalOpen] = useState(false);// Form Stateconst [newTemplate, setNewTemplate] = useState({44 unmodified linesconst fetchTemplates = async () => {if (!token || !selectedOrgId) return;setLoading(true);try {const data = await api.get(`/v1/whatsapp/templates`, token, selectedOrgId);setTemplates(data);} catch (err) {logError('[TEMPLATES] Fetch failed:', err);} finally {setLoading(false);}78 unmodified lines</div></div>{/* Filters & Search */}<div className="relative mb-8"><Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />56 unmodified lines5758596061626344 unmodified lines10810911011111211311411511611711811912012112212312478 unmodified lines20320420520620720820921021121221321421521621721821922022122222322422522656 unmodified linesconst [syncing, setSyncing] = useState(false);const [search, setSearch] = useState('');const [isModalOpen, setIsModalOpen] = useState(false);const [wabaNotConfigured, setWabaNotConfigured] = useState(false);// Form Stateconst [newTemplate, setNewTemplate] = useState({44 unmodified linesconst fetchTemplates = async () => {if (!token || !selectedOrgId) return;setLoading(true);setWabaNotConfigured(false);try {const data = await api.get(`/v1/whatsapp/templates`, token, selectedOrgId);setTemplates(data);} catch (err: any) {const msg: string = err?.message ?? '';if (msg.toLowerCase().includes('waba') || msg.toLowerCase().includes('not configured') || msg.includes('400')) {setWabaNotConfigured(true);} else {logError('[TEMPLATES] Fetch failed:', err);}} finally {setLoading(false);}78 unmodified lines</div></div>{/* WABA not configured banner */}{wabaNotConfigured && (<motion.divinitial={{ opacity: 0, y: -10 }}animate={{ opacity: 1, y: 0 }}className="flex items-start gap-4 bg-amber-50 border border-amber-200 rounded-2xl p-5 mb-8"><AlertTriangle className="w-5 h-5 text-amber-500 shrink-0 mt-0.5" /><div><p className="font-bold text-amber-800 text-sm">WhatsApp Business non configuré</p><p className="text-amber-700 text-sm mt-1">Cette organisation n'a pas encore de compte WhatsApp Business (WABA) associé.Rendez-vous dans <strong>Paramètres → Intégration WhatsApp</strong> pour configurer votre numéro et votre WABA ID.</p></div></motion.div>)}{/* Filters & Search */}<div className="relative mb-8"><Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
13 unmodified lines14151617181914 unmodified lines343536373839404142116 unmodified lines15916016116216316416516616717 unmodified lines18518618718818919019110 unmodified lines20220320420520620720820921021121221321421521621721821922022122222322422522622722822913 unmodified linestype P<K extends string = 'id'> = { Params: Record<K, string> };type Q<T extends Record<string, string | undefined>> = { Querystring: T };export async function organizationRoutes(fastify: FastifyInstance) {const PersonalityConfigSchema = z.object({botName: z.string().optional(),14 unmodified linesreturn orgs.map(decryptSecrets);});// 2. Get specific organizationfastify.get<P>('/:id', async (req, reply) => {const { id } = req.params;const org = await prisma.organization.findUnique({where: { id },include: { phoneNumbers: true }116 unmodified lines}});// 6. Update AI Personalityfastify.patch<P>('/:id/personality', async (req, reply) => {const { id } = req.params;const body = PersonalityConfigSchema.partial().safeParse(req.body);if (!body.success) return reply.code(400).send({ error: body.error.flatten() });17 unmodified lines// 7. Knowledge Basefastify.post<P>('/:id/upload-kb', async (req, reply) => {const { id } = req.params;const parts = req.parts();let fileBuffer: Buffer | null = null, filename = 'kb.pdf', mimeType = 'application/pdf';10 unmodified linesreturn reply.send({ ok: true, ...result });});fastify.get<P>('/:id/kb-stats', async (req) => {return KBService.getStats(req.params.id);});fastify.post<P>('/:id/index-kb', async (req, reply) => {const { id } = req.params;const org = await prisma.organization.findUnique({ where: { id } });if (!org?.knowledgeBaseUrl) return reply.code(400).send({ error: 'No KB URL' });const { whatsappQueue } = await import('../services/queue');await whatsappQueue.add('process-kb', { organizationId: id, url: org.knowledgeBaseUrl });return { ok: true };});fastify.get<P & Q<{ page?: string; limit?: string }>>('/:id/kb', async (req) => {const { id } = req.params;const { page = '1', limit = '50' } = req.query;return KBService.listChunks(id, parseInt(page), parseInt(limit));});fastify.delete<P<'id' | 'entryId'>>('/:id/kb/:entryId', async (req, reply) => {const { id, entryId } = req.params;const ok = await KBService.deleteChunk(id, entryId);return ok ? { ok: true } : reply.code(404).send({ error: 'Not found' });});13 unmodified lines14151617181920212223242526272829303114 unmodified lines4647484950515253545556116 unmodified lines17317417517617717817918018118218317 unmodified lines20120220320420520620720810 unmodified lines21922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125213 unmodified linestype P<K extends string = 'id'> = { Params: Record<K, string> };type Q<T extends Record<string, string | undefined>> = { Querystring: T };const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;/*** Resolve org by UUID or slug — handles the case where the frontend stores a slug* in sessionStorage instead of a UUID (e.g. "xamle-admin-org" instead of the actual UUID).*/async function resolveOrgId(idOrSlug: string): Promise<string | null> {if (UUID_REGEX.test(idOrSlug)) return idOrSlug;const org = await prisma.organization.findUnique({ where: { slug: idOrSlug }, select: { id: true } });return org?.id ?? null;}export async function organizationRoutes(fastify: FastifyInstance) {const PersonalityConfigSchema = z.object({botName: z.string().optional(),14 unmodified linesreturn orgs.map(decryptSecrets);});// 2. Get specific organization (accepts UUID or slug)fastify.get<P>('/:id', async (req, reply) => {const { id: idOrSlug } = req.params;const id = await resolveOrgId(idOrSlug);if (!id) return reply.code(404).send({ error: 'Organization not found' });const org = await prisma.organization.findUnique({where: { id },include: { phoneNumbers: true }116 unmodified lines}});// 6. Update AI Personality (accepts UUID or slug)fastify.patch<P>('/:id/personality', async (req, reply) => {const { id: idOrSlug } = req.params;const id = await resolveOrgId(idOrSlug);if (!id) return reply.code(404).send({ error: 'Organization not found' });const body = PersonalityConfigSchema.partial().safeParse(req.body);if (!body.success) return reply.code(400).send({ error: body.error.flatten() });17 unmodified lines// 7. Knowledge Basefastify.post<P>('/:id/upload-kb', async (req, reply) => {const id = await resolveOrgId(req.params.id);if (!id) return reply.code(404).send({ error: 'Organization not found' });const parts = req.parts();let fileBuffer: Buffer | null = null, filename = 'kb.pdf', mimeType = 'application/pdf';10 unmodified linesreturn reply.send({ ok: true, ...result });});fastify.get<P>('/:id/kb-stats', async (req, reply) => {const id = await resolveOrgId(req.params.id);if (!id) return reply.code(404).send({ error: 'Organization not found' });return KBService.getStats(id);});fastify.post<P>('/:id/index-kb', async (req, reply) => {const id = await resolveOrgId(req.params.id);if (!id) return reply.code(404).send({ error: 'Organization not found' });const org = await prisma.organization.findUnique({ where: { id } });if (!org?.knowledgeBaseUrl) return reply.code(400).send({ error: 'No KB URL configured for this organization' });const { whatsappQueue } = await import('../services/queue');await whatsappQueue.add('process-kb', { organizationId: id, url: org.knowledgeBaseUrl });return { ok: true };});fastify.get<P & Q<{ page?: string; limit?: string }>>('/:id/kb', async (req, reply) => {const id = await resolveOrgId(req.params.id);if (!id) return reply.code(404).send({ error: 'Organization not found' });const { page = '1', limit = '50' } = req.query;return KBService.listChunks(id, parseInt(page), parseInt(limit));});fastify.delete<P<'id' | 'entryId'>>('/:id/kb/:entryId', async (req, reply) => {const id = await resolveOrgId(req.params.id);if (!id) return reply.code(404).send({ error: 'Organization not found' });const { entryId } = req.params;const ok = await KBService.deleteChunk(id, entryId);return ok ? { ok: true } : reply.code(404).send({ error: 'Not found' });});
apps/admin/src/App.tsx+4
apps/admin/src/pages/KnowledgeBasePage.tsx+11-2
apps/admin/src/pages/TemplatesPage.tsx+27-2
apps/api/src/routes/organizations.ts+35-12