@adatechnology/conversations-ui 0.1.0-rc.4 → 0.1.0-rc.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-LITPZCWW.js +1465 -0
- package/dist/index.d.ts +223 -29
- package/dist/index.js +316 -366
- package/dist/preview/index.d.ts +92 -3
- package/dist/preview/index.js +627 -103
- package/dist/types-CeixG2Z9.d.ts +324 -0
- package/package.json +2 -2
- package/src/Avatar.tsx +13 -2
- package/src/ConversationDocumentsPanel.tsx +342 -24
- package/src/ConversationListItem.tsx +18 -2
- package/src/DocumentsLibrary.tsx +322 -0
- package/src/FileIcon.test.ts +83 -0
- package/src/FileIcon.tsx +88 -11
- package/src/Lightbox.tsx +18 -3
- package/src/MediaRenderer.tsx +5 -2
- package/src/MessageBubble.tsx +18 -2
- package/src/MessageComposer.tsx +20 -3
- package/src/WhatsAppMessageEditor.tsx +28 -4
- package/src/hooks/useConversationActions.ts +56 -0
- package/src/hooks/useConversationDocuments.ts +11 -7
- package/src/hooks/useConversationList.ts +15 -9
- package/src/hooks/useConversationMessages.ts +2 -2
- package/src/index.ts +32 -11
- package/src/lib/cn.test.ts +29 -0
- package/src/lib/createMediaUrlResolver.ts +33 -0
- package/src/lib/paginated.test.ts +33 -0
- package/src/lib/paginated.ts +26 -0
- package/src/preview/MediaTypesPreview.tsx +87 -0
- package/src/preview/createMockConversationsApi.ts +175 -15
- package/src/preview/index.ts +6 -1
- package/src/preview/mockDocumentsSearch.test.ts +57 -0
- package/src/preview/preview.test.ts +5 -3
- package/src/preview/previewFileSamples.test.ts +151 -0
- package/src/preview/previewFileSamples.ts +74 -0
- package/src/preview/previewFixtures.ts +288 -1
- package/src/preview/previewMediaSource.test.ts +62 -0
- package/src/preview/previewMediaSource.ts +91 -0
- package/src/providers/types.ts +127 -9
- package/src/settings/WhatsAppCreateTemplateForm.tsx +3 -1
- package/src/useWaitingNotifications.ts +74 -29
- package/dist/chunk-4R6Y43DQ.js +0 -726
- package/dist/types-C0PtaO7S.d.ts +0 -207
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
import type { MessagePayload } from '../types'
|
|
8
|
-
import type { ConversationSummary } from '../providers/types'
|
|
8
|
+
import type { ConversationDocument, ConversationSummary } from '../providers/types'
|
|
9
9
|
|
|
10
10
|
// Datas fixas: fixture com data relativa ao relógio faz o mesmo cenário renderizar diferente a
|
|
11
11
|
// cada execução, e separadores de dia deixam de ser verificáveis.
|
|
@@ -71,6 +71,24 @@ export const PREVIEW_CONVERSATIONS: readonly ConversationSummary[] = [
|
|
|
71
71
|
unread: 1,
|
|
72
72
|
currentState: 'list_import',
|
|
73
73
|
},
|
|
74
|
+
{
|
|
75
|
+
// Cobre TODO tipo que o composer aceita (DEFAULT_ACCEPTED_FILE_TYPES: image/*, video/*,
|
|
76
|
+
// audio/*, .pdf, .doc, .docx, .xls, .xlsx, .zip) mais sticker. Existe para que cada ramo do
|
|
77
|
+
// MediaRenderer e cada ícone/cor do FileIcon apareçam em algum lugar — ramo sem fixture é ramo
|
|
78
|
+
// que ninguém olha até quebrar em produção.
|
|
79
|
+
id: '5511944443333',
|
|
80
|
+
whatsappNumber: '5511944443333',
|
|
81
|
+
clientName: 'Rita Documentos',
|
|
82
|
+
lastContent: 'segue a planilha do pedido',
|
|
83
|
+
lastDirection: 'inbound',
|
|
84
|
+
lastAt: at('15:10:00'),
|
|
85
|
+
lastInboundAt: at('15:10:00'),
|
|
86
|
+
mode: 'human',
|
|
87
|
+
assignedUserId: 'agent-1',
|
|
88
|
+
waitingHuman: false,
|
|
89
|
+
unread: 3,
|
|
90
|
+
currentState: 'human_handling',
|
|
91
|
+
},
|
|
74
92
|
]
|
|
75
93
|
|
|
76
94
|
export const PREVIEW_MESSAGES: Readonly<Record<string, readonly MessagePayload[]>> = {
|
|
@@ -150,4 +168,273 @@ export const PREVIEW_MESSAGES: Readonly<Record<string, readonly MessagePayload[]
|
|
|
150
168
|
timestamp: at('13:31:00'),
|
|
151
169
|
},
|
|
152
170
|
],
|
|
171
|
+
// Um tipo por mensagem, na ordem em que o MediaRenderer os trata.
|
|
172
|
+
'5511944443333': [
|
|
173
|
+
{
|
|
174
|
+
id: 'fixture-doc-image',
|
|
175
|
+
type: 'image',
|
|
176
|
+
mediaId: 'preview-image-1',
|
|
177
|
+
mimeType: 'image/png',
|
|
178
|
+
caption: 'foto da prateleira',
|
|
179
|
+
direction: 'inbound',
|
|
180
|
+
sender: 'customer',
|
|
181
|
+
timestamp: at('15:00:00'),
|
|
182
|
+
},
|
|
183
|
+
{
|
|
184
|
+
id: 'fixture-doc-video',
|
|
185
|
+
type: 'video',
|
|
186
|
+
mediaId: 'preview-video-1',
|
|
187
|
+
mimeType: 'video/mp4',
|
|
188
|
+
direction: 'inbound',
|
|
189
|
+
sender: 'customer',
|
|
190
|
+
timestamp: at('15:01:00'),
|
|
191
|
+
},
|
|
192
|
+
{
|
|
193
|
+
id: 'fixture-doc-audio',
|
|
194
|
+
type: 'audio',
|
|
195
|
+
mediaId: 'preview-audio-2',
|
|
196
|
+
mimeType: 'audio/ogg',
|
|
197
|
+
direction: 'inbound',
|
|
198
|
+
sender: 'customer',
|
|
199
|
+
timestamp: at('15:02:00'),
|
|
200
|
+
},
|
|
201
|
+
{
|
|
202
|
+
id: 'fixture-doc-sticker',
|
|
203
|
+
type: 'sticker',
|
|
204
|
+
mediaId: 'preview-sticker-1',
|
|
205
|
+
mimeType: 'image/webp',
|
|
206
|
+
direction: 'inbound',
|
|
207
|
+
sender: 'customer',
|
|
208
|
+
timestamp: at('15:03:00'),
|
|
209
|
+
},
|
|
210
|
+
// Os cinco ramos do FileIcon: pdf, doc, xls, zip e o genérico do fallback.
|
|
211
|
+
{
|
|
212
|
+
id: 'fixture-doc-pdf',
|
|
213
|
+
type: 'document',
|
|
214
|
+
uploadId: 'preview/documentos/nota-fiscal.pdf',
|
|
215
|
+
filename: 'nota-fiscal.pdf',
|
|
216
|
+
mimeType: 'application/pdf',
|
|
217
|
+
sizeBytes: 184_320,
|
|
218
|
+
direction: 'inbound',
|
|
219
|
+
sender: 'customer',
|
|
220
|
+
timestamp: at('15:04:00'),
|
|
221
|
+
},
|
|
222
|
+
{
|
|
223
|
+
id: 'fixture-doc-docx',
|
|
224
|
+
type: 'document',
|
|
225
|
+
uploadId: 'preview/documentos/contrato.docx',
|
|
226
|
+
filename: 'contrato.docx',
|
|
227
|
+
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
228
|
+
sizeBytes: 42_112,
|
|
229
|
+
direction: 'inbound',
|
|
230
|
+
sender: 'customer',
|
|
231
|
+
timestamp: at('15:05:00'),
|
|
232
|
+
},
|
|
233
|
+
{
|
|
234
|
+
id: 'fixture-doc-doc',
|
|
235
|
+
type: 'document',
|
|
236
|
+
uploadId: 'preview/documentos/procuracao.doc',
|
|
237
|
+
filename: 'procuracao.doc',
|
|
238
|
+
mimeType: 'application/msword',
|
|
239
|
+
sizeBytes: 31_744,
|
|
240
|
+
direction: 'inbound',
|
|
241
|
+
sender: 'customer',
|
|
242
|
+
timestamp: at('15:06:00'),
|
|
243
|
+
},
|
|
244
|
+
{
|
|
245
|
+
id: 'fixture-doc-xlsx',
|
|
246
|
+
type: 'document',
|
|
247
|
+
uploadId: 'preview/documentos/pedido.xlsx',
|
|
248
|
+
filename: 'pedido.xlsx',
|
|
249
|
+
mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
250
|
+
sizeBytes: 15_872,
|
|
251
|
+
direction: 'inbound',
|
|
252
|
+
sender: 'customer',
|
|
253
|
+
timestamp: at('15:07:00'),
|
|
254
|
+
},
|
|
255
|
+
{
|
|
256
|
+
id: 'fixture-doc-xls',
|
|
257
|
+
type: 'document',
|
|
258
|
+
uploadId: 'preview/documentos/tabela-antiga.xls',
|
|
259
|
+
filename: 'tabela-antiga.xls',
|
|
260
|
+
mimeType: 'application/vnd.ms-excel',
|
|
261
|
+
sizeBytes: 9_216,
|
|
262
|
+
direction: 'inbound',
|
|
263
|
+
sender: 'customer',
|
|
264
|
+
timestamp: at('15:08:00'),
|
|
265
|
+
},
|
|
266
|
+
{
|
|
267
|
+
id: 'fixture-doc-zip',
|
|
268
|
+
type: 'document',
|
|
269
|
+
uploadId: 'preview/documentos/comprovantes.zip',
|
|
270
|
+
filename: 'comprovantes.zip',
|
|
271
|
+
mimeType: 'application/zip',
|
|
272
|
+
sizeBytes: 2_355_200,
|
|
273
|
+
direction: 'inbound',
|
|
274
|
+
sender: 'customer',
|
|
275
|
+
timestamp: at('15:09:00'),
|
|
276
|
+
},
|
|
277
|
+
{
|
|
278
|
+
id: 'fixture-doc-txt',
|
|
279
|
+
type: 'document',
|
|
280
|
+
uploadId: 'preview/documentos/lista-compras.txt',
|
|
281
|
+
filename: 'lista-compras.txt',
|
|
282
|
+
mimeType: 'text/plain',
|
|
283
|
+
sizeBytes: 1_024,
|
|
284
|
+
direction: 'inbound',
|
|
285
|
+
sender: 'customer',
|
|
286
|
+
timestamp: at('15:10:00'),
|
|
287
|
+
},
|
|
288
|
+
{
|
|
289
|
+
id: 'fixture-doc-csv',
|
|
290
|
+
type: 'document',
|
|
291
|
+
uploadId: 'preview/documentos/planilha-do-pedido.csv',
|
|
292
|
+
filename: 'planilha-do-pedido.csv',
|
|
293
|
+
mimeType: 'text/csv',
|
|
294
|
+
sizeBytes: 2_048,
|
|
295
|
+
direction: 'inbound',
|
|
296
|
+
sender: 'customer',
|
|
297
|
+
timestamp: at('15:11:00'),
|
|
298
|
+
},
|
|
299
|
+
{
|
|
300
|
+
id: 'fixture-doc-pptx',
|
|
301
|
+
type: 'document',
|
|
302
|
+
uploadId: 'preview/documentos/apresentacao.pptx',
|
|
303
|
+
filename: 'apresentacao.pptx',
|
|
304
|
+
mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
305
|
+
sizeBytes: 512_000,
|
|
306
|
+
direction: 'inbound',
|
|
307
|
+
sender: 'customer',
|
|
308
|
+
timestamp: at('15:12:00'),
|
|
309
|
+
},
|
|
310
|
+
{
|
|
311
|
+
id: 'fixture-doc-ppt',
|
|
312
|
+
type: 'document',
|
|
313
|
+
uploadId: 'preview/documentos/antiga.ppt',
|
|
314
|
+
filename: 'antiga.ppt',
|
|
315
|
+
mimeType: 'application/vnd.ms-powerpoint',
|
|
316
|
+
sizeBytes: 348_160,
|
|
317
|
+
direction: 'inbound',
|
|
318
|
+
sender: 'customer',
|
|
319
|
+
timestamp: at('15:13:00'),
|
|
320
|
+
},
|
|
321
|
+
// Mídia enviada COMO arquivo: aí a Meta manda o nome, então é onde a extensão de música e de
|
|
322
|
+
// vídeo aparece na lista. Mandada como `image`/`audio`/`video` (acima e abaixo) ela chega sem
|
|
323
|
+
// nome nenhum, e o rótulo vira o id da mídia — como em produção.
|
|
324
|
+
{
|
|
325
|
+
id: 'fixture-doc-mp3',
|
|
326
|
+
type: 'document',
|
|
327
|
+
uploadId: 'preview/documentos/musica-do-anuncio.mp3',
|
|
328
|
+
filename: 'musica-do-anuncio.mp3',
|
|
329
|
+
mimeType: 'audio/mpeg',
|
|
330
|
+
sizeBytes: 3_145_728,
|
|
331
|
+
direction: 'inbound',
|
|
332
|
+
sender: 'customer',
|
|
333
|
+
timestamp: at('15:14:00'),
|
|
334
|
+
},
|
|
335
|
+
{
|
|
336
|
+
id: 'fixture-doc-m4a',
|
|
337
|
+
type: 'document',
|
|
338
|
+
uploadId: 'preview/documentos/recado.m4a',
|
|
339
|
+
filename: 'recado.m4a',
|
|
340
|
+
mimeType: 'audio/mp4',
|
|
341
|
+
sizeBytes: 486_400,
|
|
342
|
+
direction: 'inbound',
|
|
343
|
+
sender: 'customer',
|
|
344
|
+
timestamp: at('15:15:00'),
|
|
345
|
+
},
|
|
346
|
+
{
|
|
347
|
+
id: 'fixture-doc-mp4-file',
|
|
348
|
+
type: 'document',
|
|
349
|
+
uploadId: 'preview/documentos/video-do-produto.mp4',
|
|
350
|
+
filename: 'video-do-produto.mp4',
|
|
351
|
+
mimeType: 'video/mp4',
|
|
352
|
+
sizeBytes: 8_388_608,
|
|
353
|
+
direction: 'inbound',
|
|
354
|
+
sender: 'customer',
|
|
355
|
+
timestamp: at('15:16:00'),
|
|
356
|
+
},
|
|
357
|
+
{
|
|
358
|
+
id: 'fixture-doc-jpg',
|
|
359
|
+
type: 'document',
|
|
360
|
+
uploadId: 'preview/documentos/foto-do-recibo.jpg',
|
|
361
|
+
filename: 'foto-do-recibo.jpg',
|
|
362
|
+
mimeType: 'image/jpeg',
|
|
363
|
+
sizeBytes: 262_144,
|
|
364
|
+
direction: 'inbound',
|
|
365
|
+
sender: 'customer',
|
|
366
|
+
timestamp: at('15:17:00'),
|
|
367
|
+
},
|
|
368
|
+
// As espécies restantes que a Meta aceita, sem nome de arquivo — fecham a lista de tipos
|
|
369
|
+
// aceitos e exercitam o fallback de ícone pela família do mimeType.
|
|
370
|
+
{
|
|
371
|
+
id: 'fixture-media-jpeg',
|
|
372
|
+
type: 'image',
|
|
373
|
+
mediaId: 'preview-image-jpeg',
|
|
374
|
+
mimeType: 'image/jpeg',
|
|
375
|
+
sizeBytes: 138_240,
|
|
376
|
+
direction: 'inbound',
|
|
377
|
+
sender: 'customer',
|
|
378
|
+
timestamp: at('15:18:00'),
|
|
379
|
+
},
|
|
380
|
+
{
|
|
381
|
+
id: 'fixture-media-3gp',
|
|
382
|
+
type: 'video',
|
|
383
|
+
mediaId: 'preview-video-3gp',
|
|
384
|
+
mimeType: 'video/3gp',
|
|
385
|
+
sizeBytes: 921_600,
|
|
386
|
+
direction: 'inbound',
|
|
387
|
+
sender: 'customer',
|
|
388
|
+
timestamp: at('15:19:00'),
|
|
389
|
+
},
|
|
390
|
+
{
|
|
391
|
+
id: 'fixture-media-aac',
|
|
392
|
+
type: 'audio',
|
|
393
|
+
mediaId: 'preview-audio-aac',
|
|
394
|
+
mimeType: 'audio/aac',
|
|
395
|
+
sizeBytes: 76_800,
|
|
396
|
+
direction: 'inbound',
|
|
397
|
+
sender: 'customer',
|
|
398
|
+
timestamp: at('15:20:00'),
|
|
399
|
+
},
|
|
400
|
+
{
|
|
401
|
+
id: 'fixture-media-amr',
|
|
402
|
+
type: 'audio',
|
|
403
|
+
mediaId: 'preview-audio-amr',
|
|
404
|
+
mimeType: 'audio/amr',
|
|
405
|
+
sizeBytes: 24_576,
|
|
406
|
+
direction: 'inbound',
|
|
407
|
+
sender: 'customer',
|
|
408
|
+
timestamp: at('15:21:00'),
|
|
409
|
+
},
|
|
410
|
+
],
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* A biblioteca de arquivos da conversa, como o backend a devolveria. Deriva das mensagens acima em
|
|
415
|
+
* vez de repetir os dados: fixture duplicada divergiria na primeira edição, e o painel passaria a
|
|
416
|
+
* mostrar arquivo que a thread não tem.
|
|
417
|
+
*
|
|
418
|
+
* Entram as CINCO espécies de mídia, na mesma lista de `extractMediaDescriptor` no backend — não só
|
|
419
|
+
* `document`. Filtrar por documento era infidelidade grave do preview: `IngestInboundMedia` linka
|
|
420
|
+
* foto, vídeo, áudio e sticker na mesma tabela, então na tela real eles aparecem na biblioteca e no
|
|
421
|
+
* preview não apareciam.
|
|
422
|
+
*/
|
|
423
|
+
const LIBRARY_MEDIA_TYPES = new Set(['document', 'image', 'video', 'audio', 'sticker'])
|
|
424
|
+
|
|
425
|
+
export const PREVIEW_DOCUMENTS: Readonly<Record<string, readonly ConversationDocument[]>> = {
|
|
426
|
+
'5511944443333': (PREVIEW_MESSAGES['5511944443333'] ?? [])
|
|
427
|
+
.filter((message) => LIBRARY_MEDIA_TYPES.has(message.type))
|
|
428
|
+
.map((message) => ({
|
|
429
|
+
// Mídia não tem `uploadId` na mensagem: o backend deriva a key do id da mídia na Meta, e o
|
|
430
|
+
// caminho abaixo imita esse formato para o download assinado receber algo do mesmo feitio.
|
|
431
|
+
id: message.uploadId ?? (message.mediaId ? `preview/inbound/${message.mediaId}` : message.id),
|
|
432
|
+
// Só documento chega nomeado. Para os outros o backend salva o id da mídia como rótulo —
|
|
433
|
+
// manter isso aqui é o que faz o ícone por família do mimeType ser exercitado de verdade.
|
|
434
|
+
filename: message.filename ?? message.mediaId ?? message.id,
|
|
435
|
+
mimeType: message.mimeType ?? 'application/octet-stream',
|
|
436
|
+
sizeBytes: message.sizeBytes ?? 0,
|
|
437
|
+
source: message.sender,
|
|
438
|
+
linkedAt: message.timestamp,
|
|
439
|
+
})),
|
|
153
440
|
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Guarda o resolvedor de mídia do preview.
|
|
3
|
+
*
|
|
4
|
+
* As asserções comparam com `previewFileUrl(tipo)` em vez de com a data URL da amostra: o bun também
|
|
5
|
+
* tem `URL.createObjectURL`, então o retorno é `blob:` aqui como no navegador, e blob URL não expõe
|
|
6
|
+
* o conteúdo para comparar. O que este teste trava é o MAPEAMENTO — mensagem → amostra do tipo certo
|
|
7
|
+
* —, enquanto os bytes de cada tipo são conferidos em `previewFileSamples.test.ts`.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { describe, expect, it } from 'bun:test'
|
|
11
|
+
|
|
12
|
+
import { createPreviewMediaResolver, previewFileUrl } from './previewMediaSource'
|
|
13
|
+
import type { MessagePayload } from '../types'
|
|
14
|
+
|
|
15
|
+
const resolve = createPreviewMediaResolver()
|
|
16
|
+
|
|
17
|
+
function message(partial: Partial<MessagePayload>): MessagePayload {
|
|
18
|
+
return {
|
|
19
|
+
id: 'msg-1',
|
|
20
|
+
type: 'image',
|
|
21
|
+
direction: 'inbound',
|
|
22
|
+
sender: 'customer',
|
|
23
|
+
timestamp: '2026-07-26T15:00:00.000Z',
|
|
24
|
+
...partial,
|
|
25
|
+
} as MessagePayload
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
describe('createPreviewMediaResolver', () => {
|
|
29
|
+
it('resolve mídia pelo mediaId, achando o tipo na biblioteca do fixture', async () => {
|
|
30
|
+
// preview-image-1 é a foto png da thread da Rita.
|
|
31
|
+
expect(await resolve(message({ mediaId: 'preview-image-1' }))).toBe(previewFileUrl('image/png'))
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('resolve documento pelo uploadId', async () => {
|
|
35
|
+
const resolved = await resolve(message({ type: 'document', uploadId: 'preview/documentos/nota-fiscal.pdf' }))
|
|
36
|
+
|
|
37
|
+
expect(resolved).toBe(previewFileUrl('application/pdf'))
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
// O sticker é webp e o áudio de voz é opus: dois tipos que o painel antes nem listava.
|
|
41
|
+
it('resolve sticker e áudio', async () => {
|
|
42
|
+
expect(await resolve(message({ mediaId: 'preview-sticker-1' }))).toBe(previewFileUrl('image/webp'))
|
|
43
|
+
expect(await resolve(message({ mediaId: 'preview-audio-2' }))).toBe(previewFileUrl('audio/ogg'))
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
// Mídia que não está na biblioteca ainda tem de abrir: cai no mimeType da própria mensagem.
|
|
47
|
+
it('usa o mimeType da mensagem quando o id é desconhecido', async () => {
|
|
48
|
+
const resolved = await resolve(message({ mediaId: 'nunca-visto', mimeType: 'image/jpeg' }))
|
|
49
|
+
|
|
50
|
+
expect(resolved).toBe(previewFileUrl('image/jpeg'))
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
// Sem referência nenhuma o MediaRenderer não deve receber URL — devolver algo aqui faria a bolha
|
|
54
|
+
// mostrar arquivo que a mensagem não tem.
|
|
55
|
+
it('devolve null para mensagem sem uploadId nem mediaId', async () => {
|
|
56
|
+
expect(await resolve(message({ type: 'text' }))).toBeNull()
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
it('reaproveita a mesma URL para o mesmo tipo', () => {
|
|
60
|
+
expect(previewFileUrl('application/pdf')).toBe(previewFileUrl('application/pdf'))
|
|
61
|
+
})
|
|
62
|
+
})
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Como o preview entrega mídia para a UI abrir.
|
|
3
|
+
*
|
|
4
|
+
* Separado de `previewFileSamples` (que é gerado) porque aqui está a parte que depende do navegador:
|
|
5
|
+
* **blob URL, não data URL**. O Chrome bloqueia navegação de topo para `data:` desde a v60, então
|
|
6
|
+
* `window.open(dataUrl)` — que é o que os botões "visualizar" e "baixar" fazem — abre aba em branco
|
|
7
|
+
* mesmo com bytes perfeitamente válidos. Em `src` de `<img>`/`<video>` a data URL funcionaria; no
|
|
8
|
+
* `window.open` não, e o mesmo `getDocumentUrl` alimenta os dois.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { MessagePayload } from '../types'
|
|
12
|
+
import type { ResolveMediaUrl } from '../MediaRenderer'
|
|
13
|
+
import { resolvePreviewFileSample } from './previewFileSamples'
|
|
14
|
+
import { PREVIEW_DOCUMENTS } from './previewFixtures'
|
|
15
|
+
|
|
16
|
+
// Uma blob URL por tipo, reaproveitada: cada `createObjectURL` retém o blob até um `revokeObjectURL`
|
|
17
|
+
// que ninguém chamaria, e a lista redesenha a cada filtro digitado.
|
|
18
|
+
const blobUrlCache = new Map<string, string>()
|
|
19
|
+
|
|
20
|
+
function toBlob(dataUrl: string): Blob {
|
|
21
|
+
const [head, payload] = dataUrl.split(',')
|
|
22
|
+
const mimeType = head!
|
|
23
|
+
.replace(/^data:/, '')
|
|
24
|
+
.replace(/;base64$/, '')
|
|
25
|
+
.replace(/;charset=.*$/, '')
|
|
26
|
+
|
|
27
|
+
if (!head!.endsWith(';base64')) {
|
|
28
|
+
return new Blob([decodeURIComponent(payload!)], { type: mimeType || 'text/plain' })
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const binary = atob(payload!)
|
|
32
|
+
const bytes = new Uint8Array(binary.length)
|
|
33
|
+
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)
|
|
34
|
+
return new Blob([bytes], { type: mimeType })
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** URL que o preview pode abrir em aba nova. Cai na data URL fora do navegador (teste, SSR). */
|
|
38
|
+
export function previewFileUrl(mimeType: string | undefined, filename?: string): string {
|
|
39
|
+
const dataUrl = resolvePreviewFileSample(mimeType, filename)
|
|
40
|
+
if (typeof URL === 'undefined' || typeof URL.createObjectURL !== 'function') return dataUrl
|
|
41
|
+
|
|
42
|
+
const cached = blobUrlCache.get(dataUrl)
|
|
43
|
+
if (cached) return cached
|
|
44
|
+
|
|
45
|
+
const blobUrl = URL.createObjectURL(toBlob(dataUrl))
|
|
46
|
+
blobUrlCache.set(dataUrl, blobUrl)
|
|
47
|
+
return blobUrl
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* A mesma amostra em base64 cru, como o proxy de mídia do backend a devolveria.
|
|
52
|
+
*
|
|
53
|
+
* Existe porque `getMediaProxyUrl` é o caminho da mídia AINDA NÃO ingerida (só existe o id na Meta),
|
|
54
|
+
* e o contrato pede `{ mimeType, data }` — não URL. Sem isto o mock devolvia o PNG 1x1 para
|
|
55
|
+
* qualquer id, e vídeo e áudio da thread apareciam quebrados apesar de haver amostra válida.
|
|
56
|
+
*/
|
|
57
|
+
export function previewFileBase64(mimeType: string | undefined, filename?: string): { mimeType: string; data: string } {
|
|
58
|
+
const dataUrl = resolvePreviewFileSample(mimeType, filename)
|
|
59
|
+
const [head, payload] = dataUrl.split(',')
|
|
60
|
+
const declared = head!
|
|
61
|
+
.replace(/^data:/, '')
|
|
62
|
+
.replace(/;base64$/, '')
|
|
63
|
+
.replace(/;charset=.*$/, '')
|
|
64
|
+
|
|
65
|
+
if (head!.endsWith(';base64')) return { mimeType: declared, data: payload! }
|
|
66
|
+
return { mimeType: declared, data: btoa(decodeURIComponent(payload!)) }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* O `onResolveMediaUrl` que o `MessageBubble` espera.
|
|
71
|
+
*
|
|
72
|
+
* Sem ele, foto, vídeo e áudio da thread ficam parados no placeholder para sempre — o
|
|
73
|
+
* `MediaRenderer` só resolve `uploadId`/`mediaId` por esta porta, de propósito, para o pacote nunca
|
|
74
|
+
* chamar endpoint fixo. O preview não tinha resolvedor nenhum, então nenhuma mídia carregava.
|
|
75
|
+
*/
|
|
76
|
+
export function createPreviewMediaResolver(): ResolveMediaUrl {
|
|
77
|
+
const byId = new Map<string, { mimeType: string; filename: string }>()
|
|
78
|
+
for (const documents of Object.values(PREVIEW_DOCUMENTS)) {
|
|
79
|
+
for (const document of documents) {
|
|
80
|
+
byId.set(document.id, { mimeType: document.mimeType, filename: document.filename })
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return async (message: MessagePayload): Promise<string | null> => {
|
|
85
|
+
const reference = message.uploadId ?? (message.mediaId ? `preview/inbound/${message.mediaId}` : undefined)
|
|
86
|
+
if (!reference) return null
|
|
87
|
+
|
|
88
|
+
const known = byId.get(reference)
|
|
89
|
+
return previewFileUrl(known?.mimeType ?? message.mimeType, known?.filename ?? message.filename)
|
|
90
|
+
}
|
|
91
|
+
}
|
package/src/providers/types.ts
CHANGED
|
@@ -1,28 +1,139 @@
|
|
|
1
1
|
import type { MessagePayload } from '../types'
|
|
2
2
|
import type { ConversationChannel } from '../conversationChannel'
|
|
3
3
|
|
|
4
|
+
export interface ListConversationsParams {
|
|
5
|
+
page?: number
|
|
6
|
+
limit?: number
|
|
7
|
+
waitingHuman?: boolean
|
|
8
|
+
search?: string
|
|
9
|
+
/**
|
|
10
|
+
* Recortes que só o produto conhece (tipo de financiamento, carteira, campanha) repassados
|
|
11
|
+
* crus ao backend dele. É o que evita o vocabulário de uma vertical virar campo fixo aqui:
|
|
12
|
+
* o pacote transporta o filtro sem saber o que ele significa.
|
|
13
|
+
*/
|
|
14
|
+
filters?: Record<string, string | undefined>
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Página com o total, para a UI conseguir desenhar controles de paginação.
|
|
19
|
+
*
|
|
20
|
+
* `fetchConversations` devolve isto **ou** o array puro de antes: implementações existentes
|
|
21
|
+
* continuam válidas sem mudar uma linha, e quem precisa paginar passa a ter o total. Sem a união
|
|
22
|
+
* seria impossível saber se um retorno curto é a última página ou uma página cheia por acaso.
|
|
23
|
+
*/
|
|
24
|
+
export interface ConversationPage {
|
|
25
|
+
conversations: ConversationSummary[]
|
|
26
|
+
total: number
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface ListDocumentsParams {
|
|
30
|
+
search?: string
|
|
31
|
+
page?: number
|
|
32
|
+
/** Tamanho da página. Sem ele, `page` sozinho não define fatia nenhuma. */
|
|
33
|
+
limit?: number
|
|
34
|
+
/** Origem do arquivo (`customer`, `agent`, `bot`…). O vocabulário é do host. */
|
|
35
|
+
source?: string
|
|
36
|
+
sortDirection?: 'asc' | 'desc'
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Arquivo na biblioteca da empresa: o mesmo da conversa, mais de qual conversa veio. */
|
|
40
|
+
export interface CompanyDocument extends ConversationDocument {
|
|
41
|
+
conversationId: string
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface CompanyDocumentPage {
|
|
45
|
+
documents: CompanyDocument[]
|
|
46
|
+
total: number
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface ConversationDocumentPage {
|
|
50
|
+
documents: ConversationDocument[]
|
|
51
|
+
total: number
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Template disponível para envio a partir da inbox. Distinto do `WhatsAppTemplateSummary` de
|
|
56
|
+
* `settings/`, e de propósito: aquele serve ao formulário que **edita** template e carrega o que
|
|
57
|
+
* a edição precisa (`shortId`, `variableCount`); este serve a quem só vai **escolher um para
|
|
58
|
+
* enviar**, e pedir os campos de edição obrigaria todo host a produzi-los sem uso.
|
|
59
|
+
*/
|
|
60
|
+
export interface ConversationTemplate {
|
|
61
|
+
name: string
|
|
62
|
+
language: string
|
|
63
|
+
status: string
|
|
64
|
+
category?: string
|
|
65
|
+
bodyText?: string | null
|
|
66
|
+
}
|
|
67
|
+
|
|
4
68
|
export interface ConversationsApi {
|
|
5
69
|
fetchMessages(conversationId: string, params?: { limit?: number; before?: string }): Promise<MessagePayload[]>
|
|
6
|
-
fetchConversations(params?:
|
|
7
|
-
page?: number
|
|
8
|
-
limit?: number
|
|
9
|
-
waitingHuman?: boolean
|
|
10
|
-
search?: string
|
|
11
|
-
}): Promise<ConversationSummary[]>
|
|
70
|
+
fetchConversations(params?: ListConversationsParams): Promise<ConversationSummary[] | ConversationPage>
|
|
12
71
|
sendMessage(conversationId: string, text: string): Promise<MessagePayload>
|
|
13
72
|
sendMedia(
|
|
14
73
|
conversationId: string,
|
|
15
74
|
data: { base64: string; mimeType: string; filename: string; caption?: string },
|
|
16
75
|
): Promise<MessagePayload>
|
|
76
|
+
/**
|
|
77
|
+
* `templateName` é opcional porque reabrir a janela é a operação, e escolher *qual* template a
|
|
78
|
+
* usa nem sempre é decisão da UI: backends que guardam um template padrão configurado só
|
|
79
|
+
* precisam do "reabra". Exigir o nome obrigaria toda inbox a listar templates antes de poder
|
|
80
|
+
* mandar o primeiro — e a listagem é `listTemplates?`, opcional.
|
|
81
|
+
*/
|
|
17
82
|
sendTemplate(
|
|
18
83
|
conversationId: string,
|
|
19
|
-
data: { templateName
|
|
84
|
+
data: { templateName?: string; languageCode?: string; bodyParams?: string[] },
|
|
20
85
|
): Promise<void>
|
|
21
86
|
markRead(conversationId: string): Promise<void>
|
|
22
87
|
getContext(conversationId: string): Promise<Record<string, unknown>>
|
|
23
|
-
getDocuments(
|
|
24
|
-
|
|
88
|
+
getDocuments(
|
|
89
|
+
conversationId: string,
|
|
90
|
+
params?: ListDocumentsParams,
|
|
91
|
+
): Promise<ConversationDocument[] | ConversationDocumentPage>
|
|
92
|
+
/**
|
|
93
|
+
* `disposition` decide entre abrir no navegador e baixar. É o backend que assina a URL e grava
|
|
94
|
+
* o `Content-Disposition` nela, então a escolha precisa viajar na chamada — depois de assinada
|
|
95
|
+
* não há como o cliente mudá-la. Ausente = o padrão do host.
|
|
96
|
+
*/
|
|
97
|
+
getDocumentUrl(uploadId: string, disposition?: 'inline' | 'attachment'): Promise<string>
|
|
98
|
+
/**
|
|
99
|
+
* Baixa vários arquivos num zip único.
|
|
100
|
+
*
|
|
101
|
+
* **Opcional por capacidade:** montar zip exige o host LER os bytes do storage, o que nem toda
|
|
102
|
+
* instalação faz — as que só assinam URL não conseguem. Ausente, o painel esconde a seleção em
|
|
103
|
+
* lote em vez de oferecer um botão que falha.
|
|
104
|
+
*/
|
|
105
|
+
downloadDocumentsArchive?(conversationId: string, uploadIds: readonly string[]): Promise<Blob>
|
|
106
|
+
/**
|
|
107
|
+
* Biblioteca de TODAS as conversas, para uma tela de Documentos fora do atendimento.
|
|
108
|
+
*
|
|
109
|
+
* Opcional por capacidade: host que só expõe anexo dentro da conversa não implementa, e o
|
|
110
|
+
* componente de biblioteca simplesmente não é usável — melhor que uma tela que sempre erra.
|
|
111
|
+
*/
|
|
112
|
+
getAllDocuments?(params?: ListDocumentsParams): Promise<CompanyDocumentPage>
|
|
25
113
|
getMediaProxyUrl(mediaId: string): Promise<{ mimeType: string; data: string }>
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Operações de atendimento humano. **Opcionais por capacidade, não por descuido:** nem toda
|
|
117
|
+
* inbox tem fila humana — um canal só-bot, ou um chat de site sem operador, não sabe o que é
|
|
118
|
+
* assumir conversa. Quem não implementa não ganha o botão, em vez de ganhar um botão que
|
|
119
|
+
* estoura no clique. Os hooks devolvem `undefined` para a ação ausente, e é isso que a UI
|
|
120
|
+
* consulta para decidir se desenha a afordância.
|
|
121
|
+
*/
|
|
122
|
+
takeover?(conversationId: string): Promise<void>
|
|
123
|
+
release?(conversationId: string): Promise<void>
|
|
124
|
+
/** Encerra o atendimento. Despedida, se houver, é decisão do host — o pacote não a inventa. */
|
|
125
|
+
finalize?(conversationId: string): Promise<void>
|
|
126
|
+
|
|
127
|
+
markAllRead?(): Promise<void>
|
|
128
|
+
listTemplates?(): Promise<ConversationTemplate[]>
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Transcrição completa gerada pelo servidor. Existe ao lado de `buildTranscriptText`, que monta
|
|
132
|
+
* a partir das mensagens já em memória: a tela costuma ter só a última página carregada, e
|
|
133
|
+
* exportar dali entregaria um recorte parcial com cara de histórico inteiro. Opcional porque
|
|
134
|
+
* nem todo backend expõe a rota — quem não tem continua usando o builder local.
|
|
135
|
+
*/
|
|
136
|
+
exportTranscript?(conversationId: string): Promise<{ transcript: string; filename: string }>
|
|
26
137
|
}
|
|
27
138
|
|
|
28
139
|
/**
|
|
@@ -76,6 +187,13 @@ export interface ConversationSummary {
|
|
|
76
187
|
waitingHuman: boolean
|
|
77
188
|
unread: number
|
|
78
189
|
currentState: string
|
|
190
|
+
/**
|
|
191
|
+
* Atributos que só o produto conhece e desenha (tipo de financiamento, carteira, campanha). É a
|
|
192
|
+
* contraparte de leitura do `filters` de `ListConversationsParams`: o pacote transporta e nunca
|
|
193
|
+
* interpreta. Sem isto, exibir um selo próprio na linha exigiria o host manter uma segunda
|
|
194
|
+
* consulta paralela à mesma listagem — a implementação duplicada que o pacote existe para evitar.
|
|
195
|
+
*/
|
|
196
|
+
attributes?: Record<string, string | undefined>
|
|
79
197
|
}
|
|
80
198
|
|
|
81
199
|
export interface ConversationDocument {
|
|
@@ -24,6 +24,7 @@ export interface WhatsAppCreateTemplateFormLabels {
|
|
|
24
24
|
sectionDescription: string
|
|
25
25
|
nameLabel: string
|
|
26
26
|
nameHint: string
|
|
27
|
+
namePlaceholder: string
|
|
27
28
|
categoryLabel: string
|
|
28
29
|
languageLabel: string
|
|
29
30
|
headerLabel: string
|
|
@@ -57,6 +58,7 @@ const DEFAULT_LABELS: WhatsAppCreateTemplateFormLabels = {
|
|
|
57
58
|
sectionDescription: 'Envia um template para aprovação da Meta.',
|
|
58
59
|
nameLabel: 'Nome do template',
|
|
59
60
|
nameHint: 'Somente letras minúsculas, números e underscore.',
|
|
61
|
+
namePlaceholder: 'reengajamento_cliente',
|
|
60
62
|
categoryLabel: 'Categoria',
|
|
61
63
|
languageLabel: 'Idioma',
|
|
62
64
|
headerLabel: 'Cabeçalho',
|
|
@@ -142,7 +144,7 @@ export function WhatsAppCreateTemplateForm({
|
|
|
142
144
|
type="text"
|
|
143
145
|
value={value.name}
|
|
144
146
|
onChange={(e) => set('name', e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, '_'))}
|
|
145
|
-
placeholder=
|
|
147
|
+
placeholder={labels.namePlaceholder}
|
|
146
148
|
className="w-full border border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100 rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent transition-all"
|
|
147
149
|
required
|
|
148
150
|
/>
|