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>

apps/admin/src/App.tsx CHANGED
@@ -99,6 +99,10 @@ function AppShell() {
99
  <Route path="/kb" element={<KnowledgeBasePage />} />
100
  <Route path="/campaign-history" element={<CampaignHistoryPage />} />
101
  <Route path="/whatsapp-templates" element={<TemplatesPage />} />
 
 
 
 
102
  </Routes>
103
  </MainLayout>
104
  );
 
99
  <Route path="/kb" element={<KnowledgeBasePage />} />
100
  <Route path="/campaign-history" element={<CampaignHistoryPage />} />
101
  <Route path="/whatsapp-templates" element={<TemplatesPage />} />
102
+ <Route
103
+ path="/conversations"
104
+ element={isCrmActive ? <CrmConversationalDashboard /> : <ConversationalDashboard />}
105
+ />
106
  </Routes>
107
  </MainLayout>
108
  );
apps/admin/src/pages/KnowledgeBasePage.tsx CHANGED
@@ -4,6 +4,7 @@ import { Database, Trash2, RefreshCw, Search, ChevronLeft, ChevronRight, Loader2
4
  import { api } from '../lib/api';
5
  import { useAuth } from '../lib/auth';
6
  import { useTenant } from '../lib/tenant';
 
7
  import { logError } from '../lib/logger';
8
 
9
  interface KbEntry {
@@ -24,6 +25,7 @@ const PAGE_SIZE = 20;
24
 
25
  export default function KnowledgeBasePage() {
26
  const { t } = useTranslation();
 
27
  const { token } = useAuth();
28
  const { selectedOrgId } = useTenant();
29
  const [data, setData] = useState<KbResponse | null>(null);
@@ -73,8 +75,15 @@ export default function KnowledgeBasePage() {
73
  setReindexing(true);
74
  try {
75
  await api.post(`/v1/organizations/${selectedOrgId}/index-kb`, {}, token);
76
- } catch (err) {
77
- logError('[KB] Re-index failed:', err);
 
 
 
 
 
 
 
78
  } finally {
79
  setReindexing(false);
80
  }
 
4
  import { api } from '../lib/api';
5
  import { useAuth } from '../lib/auth';
6
  import { useTenant } from '../lib/tenant';
7
+ import { useToast } from '../hooks/useToast';
8
  import { logError } from '../lib/logger';
9
 
10
  interface KbEntry {
 
25
 
26
  export default function KnowledgeBasePage() {
27
  const { t } = useTranslation();
28
+ const toast = useToast();
29
  const { token } = useAuth();
30
  const { selectedOrgId } = useTenant();
31
  const [data, setData] = useState<KbResponse | null>(null);
 
75
  setReindexing(true);
76
  try {
77
  await api.post(`/v1/organizations/${selectedOrgId}/index-kb`, {}, token);
78
+ toast.success('Réindexation lancée avec succès');
79
+ } catch (err: any) {
80
+ const msg: string = err?.message ?? '';
81
+ if (msg.toLowerCase().includes('no kb url') || msg.toLowerCase().includes('not configured')) {
82
+ toast.error('Aucune URL de base de connaissances configurée. Ajoutez une URL dans Paramètres.');
83
+ } else {
84
+ logError('[KB] Re-index failed:', err);
85
+ toast.error('Échec de la réindexation');
86
+ }
87
  } finally {
88
  setReindexing(false);
89
  }
apps/admin/src/pages/TemplatesPage.tsx CHANGED
@@ -57,6 +57,7 @@ export default function TemplatesPage() {
57
  const [syncing, setSyncing] = useState(false);
58
  const [search, setSearch] = useState('');
59
  const [isModalOpen, setIsModalOpen] = useState(false);
 
60
 
61
  // Form State
62
  const [newTemplate, setNewTemplate] = useState({
@@ -107,11 +108,17 @@ export default function TemplatesPage() {
107
  const fetchTemplates = async () => {
108
  if (!token || !selectedOrgId) return;
109
  setLoading(true);
 
110
  try {
111
  const data = await api.get(`/v1/whatsapp/templates`, token, selectedOrgId);
112
  setTemplates(data);
113
- } catch (err) {
114
- logError('[TEMPLATES] Fetch failed:', err);
 
 
 
 
 
115
  } finally {
116
  setLoading(false);
117
  }
@@ -196,6 +203,24 @@ export default function TemplatesPage() {
196
  </div>
197
  </div>
198
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  {/* Filters & Search */}
200
  <div className="relative mb-8">
201
  <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
 
57
  const [syncing, setSyncing] = useState(false);
58
  const [search, setSearch] = useState('');
59
  const [isModalOpen, setIsModalOpen] = useState(false);
60
+ const [wabaNotConfigured, setWabaNotConfigured] = useState(false);
61
 
62
  // Form State
63
  const [newTemplate, setNewTemplate] = useState({
 
108
  const fetchTemplates = async () => {
109
  if (!token || !selectedOrgId) return;
110
  setLoading(true);
111
+ setWabaNotConfigured(false);
112
  try {
113
  const data = await api.get(`/v1/whatsapp/templates`, token, selectedOrgId);
114
  setTemplates(data);
115
+ } catch (err: any) {
116
+ const msg: string = err?.message ?? '';
117
+ if (msg.toLowerCase().includes('waba') || msg.toLowerCase().includes('not configured') || msg.includes('400')) {
118
+ setWabaNotConfigured(true);
119
+ } else {
120
+ logError('[TEMPLATES] Fetch failed:', err);
121
+ }
122
  } finally {
123
  setLoading(false);
124
  }
 
203
  </div>
204
  </div>
205
 
206
+ {/* WABA not configured banner */}
207
+ {wabaNotConfigured && (
208
+ <motion.div
209
+ initial={{ opacity: 0, y: -10 }}
210
+ animate={{ opacity: 1, y: 0 }}
211
+ className="flex items-start gap-4 bg-amber-50 border border-amber-200 rounded-2xl p-5 mb-8"
212
+ >
213
+ <AlertTriangle className="w-5 h-5 text-amber-500 shrink-0 mt-0.5" />
214
+ <div>
215
+ <p className="font-bold text-amber-800 text-sm">WhatsApp Business non configuré</p>
216
+ <p className="text-amber-700 text-sm mt-1">
217
+ Cette organisation n'a pas encore de compte WhatsApp Business (WABA) associé.
218
+ Rendez-vous dans <strong>Paramètres → Intégration WhatsApp</strong> pour configurer votre numéro et votre WABA ID.
219
+ </p>
220
+ </div>
221
+ </motion.div>
222
+ )}
223
+
224
  {/* Filters & Search */}
225
  <div className="relative mb-8">
226
  <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
apps/api/src/routes/organizations.ts CHANGED
@@ -14,6 +14,18 @@ import { OrganizationCreationSchema, createOrganizationWithAdmin } from '../serv
14
  type P<K extends string = 'id'> = { Params: Record<K, string> };
15
  type Q<T extends Record<string, string | undefined>> = { Querystring: T };
16
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  export async function organizationRoutes(fastify: FastifyInstance) {
18
  const PersonalityConfigSchema = z.object({
19
  botName: z.string().optional(),
@@ -34,9 +46,11 @@ export async function organizationRoutes(fastify: FastifyInstance) {
34
  return orgs.map(decryptSecrets);
35
  });
36
 
37
- // 2. Get specific organization
38
  fastify.get<P>('/:id', async (req, reply) => {
39
- const { id } = req.params;
 
 
40
  const org = await prisma.organization.findUnique({
41
  where: { id },
42
  include: { phoneNumbers: true }
@@ -159,9 +173,11 @@ export async function organizationRoutes(fastify: FastifyInstance) {
159
  }
160
  });
161
 
162
- // 6. Update AI Personality
163
  fastify.patch<P>('/:id/personality', async (req, reply) => {
164
- const { id } = req.params;
 
 
165
  const body = PersonalityConfigSchema.partial().safeParse(req.body);
166
  if (!body.success) return reply.code(400).send({ error: body.error.flatten() });
167
 
@@ -185,7 +201,8 @@ export async function organizationRoutes(fastify: FastifyInstance) {
185
 
186
  // 7. Knowledge Base
187
  fastify.post<P>('/:id/upload-kb', async (req, reply) => {
188
- const { id } = req.params;
 
189
  const parts = req.parts();
190
  let fileBuffer: Buffer | null = null, filename = 'kb.pdf', mimeType = 'application/pdf';
191
 
@@ -202,28 +219,34 @@ export async function organizationRoutes(fastify: FastifyInstance) {
202
  return reply.send({ ok: true, ...result });
203
  });
204
 
205
- fastify.get<P>('/:id/kb-stats', async (req) => {
206
- return KBService.getStats(req.params.id);
 
 
207
  });
208
 
209
  fastify.post<P>('/:id/index-kb', async (req, reply) => {
210
- const { id } = req.params;
 
211
  const org = await prisma.organization.findUnique({ where: { id } });
212
- if (!org?.knowledgeBaseUrl) return reply.code(400).send({ error: 'No KB URL' });
213
 
214
  const { whatsappQueue } = await import('../services/queue');
215
  await whatsappQueue.add('process-kb', { organizationId: id, url: org.knowledgeBaseUrl });
216
  return { ok: true };
217
  });
218
 
219
- fastify.get<P & Q<{ page?: string; limit?: string }>>('/:id/kb', async (req) => {
220
- const { id } = req.params;
 
221
  const { page = '1', limit = '50' } = req.query;
222
  return KBService.listChunks(id, parseInt(page), parseInt(limit));
223
  });
224
 
225
  fastify.delete<P<'id' | 'entryId'>>('/:id/kb/:entryId', async (req, reply) => {
226
- const { id, entryId } = req.params;
 
 
227
  const ok = await KBService.deleteChunk(id, entryId);
228
  return ok ? { ok: true } : reply.code(404).send({ error: 'Not found' });
229
  });
 
14
  type P<K extends string = 'id'> = { Params: Record<K, string> };
15
  type Q<T extends Record<string, string | undefined>> = { Querystring: T };
16
 
17
+ const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
18
+
19
+ /**
20
+ * Resolve org by UUID or slug — handles the case where the frontend stores a slug
21
+ * in sessionStorage instead of a UUID (e.g. "xamle-admin-org" instead of the actual UUID).
22
+ */
23
+ async function resolveOrgId(idOrSlug: string): Promise<string | null> {
24
+ if (UUID_REGEX.test(idOrSlug)) return idOrSlug;
25
+ const org = await prisma.organization.findUnique({ where: { slug: idOrSlug }, select: { id: true } });
26
+ return org?.id ?? null;
27
+ }
28
+
29
  export async function organizationRoutes(fastify: FastifyInstance) {
30
  const PersonalityConfigSchema = z.object({
31
  botName: z.string().optional(),
 
46
  return orgs.map(decryptSecrets);
47
  });
48
 
49
+ // 2. Get specific organization (accepts UUID or slug)
50
  fastify.get<P>('/:id', async (req, reply) => {
51
+ const { id: idOrSlug } = req.params;
52
+ const id = await resolveOrgId(idOrSlug);
53
+ if (!id) return reply.code(404).send({ error: 'Organization not found' });
54
  const org = await prisma.organization.findUnique({
55
  where: { id },
56
  include: { phoneNumbers: true }
 
173
  }
174
  });
175
 
176
+ // 6. Update AI Personality (accepts UUID or slug)
177
  fastify.patch<P>('/:id/personality', async (req, reply) => {
178
+ const { id: idOrSlug } = req.params;
179
+ const id = await resolveOrgId(idOrSlug);
180
+ if (!id) return reply.code(404).send({ error: 'Organization not found' });
181
  const body = PersonalityConfigSchema.partial().safeParse(req.body);
182
  if (!body.success) return reply.code(400).send({ error: body.error.flatten() });
183
 
 
201
 
202
  // 7. Knowledge Base
203
  fastify.post<P>('/:id/upload-kb', async (req, reply) => {
204
+ const id = await resolveOrgId(req.params.id);
205
+ if (!id) return reply.code(404).send({ error: 'Organization not found' });
206
  const parts = req.parts();
207
  let fileBuffer: Buffer | null = null, filename = 'kb.pdf', mimeType = 'application/pdf';
208
 
 
219
  return reply.send({ ok: true, ...result });
220
  });
221
 
222
+ fastify.get<P>('/:id/kb-stats', async (req, reply) => {
223
+ const id = await resolveOrgId(req.params.id);
224
+ if (!id) return reply.code(404).send({ error: 'Organization not found' });
225
+ return KBService.getStats(id);
226
  });
227
 
228
  fastify.post<P>('/:id/index-kb', async (req, reply) => {
229
+ const id = await resolveOrgId(req.params.id);
230
+ if (!id) return reply.code(404).send({ error: 'Organization not found' });
231
  const org = await prisma.organization.findUnique({ where: { id } });
232
+ if (!org?.knowledgeBaseUrl) return reply.code(400).send({ error: 'No KB URL configured for this organization' });
233
 
234
  const { whatsappQueue } = await import('../services/queue');
235
  await whatsappQueue.add('process-kb', { organizationId: id, url: org.knowledgeBaseUrl });
236
  return { ok: true };
237
  });
238
 
239
+ fastify.get<P & Q<{ page?: string; limit?: string }>>('/:id/kb', async (req, reply) => {
240
+ const id = await resolveOrgId(req.params.id);
241
+ if (!id) return reply.code(404).send({ error: 'Organization not found' });
242
  const { page = '1', limit = '50' } = req.query;
243
  return KBService.listChunks(id, parseInt(page), parseInt(limit));
244
  });
245
 
246
  fastify.delete<P<'id' | 'entryId'>>('/:id/kb/:entryId', async (req, reply) => {
247
+ const id = await resolveOrgId(req.params.id);
248
+ if (!id) return reply.code(404).send({ error: 'Organization not found' });
249
+ const { entryId } = req.params;
250
  const ok = await KBService.deleteChunk(id, entryId);
251
  return ok ? { ok: true } : reply.code(404).send({ error: 'Not found' });
252
  });