@adatechnology/conversations-ui 0.16.0 → 0.18.0
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/README.md +23 -0
- package/dist/{chunk-Y326LLEP.js → chunk-7OLYCCLX.js} +1 -1
- package/dist/{chunk-WCZNIJ3M.js → chunk-Z7U22M3K.js} +7 -0
- package/dist/flows/index.d.ts +52 -6
- package/dist/flows/index.js +470 -245
- package/dist/index.d.ts +77 -3
- package/dist/index.js +148 -23
- package/dist/participant/index.js +1 -1
- package/dist/preview/index.js +2 -2
- package/package.json +2 -2
- package/src/flows/FlowNodeCard.tsx +17 -7
- package/src/flows/FlowNodePanel.tsx +10 -0
- package/src/flows/FlowPossibleNextField.tsx +89 -0
- package/src/flows/FlowRunnerFields.tsx +70 -16
- package/src/flows/FlowsWorkspace.tsx +8 -2
- package/src/flows/flowCanvasModel.ts +16 -1
- package/src/flows/flowEditorOps.ts +19 -2
- package/src/flows/flowGraph.ts +108 -11
- package/src/flows/flowLabelValidation.test.ts +92 -0
- package/src/flows/flowPossibleNext.test.ts +70 -0
- package/src/flows/index.ts +3 -0
- package/src/flows/labels.ts +39 -1
- package/src/index.ts +11 -1
- package/src/lib/phone.test.ts +20 -0
- package/src/lib/phone.ts +13 -0
- package/src/quickReplies/createMetaWhatsAppQuickRepliesClient.test.ts +113 -0
- package/src/quickReplies/createMetaWhatsAppQuickRepliesClient.ts +111 -0
- package/src/workspace/ConversationPane.tsx +13 -2
- package/src/workspace/ConversationsWorkspace.tsx +117 -18
- package/src/workspace/index.ts +1 -0
- package/src/workspace/labels.ts +2 -0
- package/src/workspace/workspaceTestContactDom.test.tsx +96 -0
package/src/flows/index.ts
CHANGED
|
@@ -28,6 +28,7 @@ export {
|
|
|
28
28
|
rendersAsButtons,
|
|
29
29
|
targetsOf,
|
|
30
30
|
validateGraph,
|
|
31
|
+
measureLabel,
|
|
31
32
|
computeAutoLayout,
|
|
32
33
|
crossFlowTargetsOf,
|
|
33
34
|
computeFlowMapLayout,
|
|
@@ -44,6 +45,8 @@ export type {
|
|
|
44
45
|
FlowNodeData,
|
|
45
46
|
FlowGraphData,
|
|
46
47
|
GraphIssue,
|
|
48
|
+
MeasuredLabel,
|
|
49
|
+
ValidateGraphOptions,
|
|
47
50
|
CollectionChain,
|
|
48
51
|
} from './flowGraph'
|
|
49
52
|
|
package/src/flows/labels.ts
CHANGED
|
@@ -9,6 +9,16 @@ export interface FlowRunnerFieldLabels {
|
|
|
9
9
|
maxInvalidAnswersHint: string
|
|
10
10
|
minDateToday: string
|
|
11
11
|
afterContextKey: string
|
|
12
|
+
// Opcionais para não quebrar quem monta os textos à mão; ausentes, vale o padrão.
|
|
13
|
+
minTime?: string
|
|
14
|
+
maxTime?: string
|
|
15
|
+
timeWindowsContextKey?: string
|
|
16
|
+
timeWindowsContextKeyHint?: string
|
|
17
|
+
possibleNext?: string
|
|
18
|
+
possibleNextHint?: string
|
|
19
|
+
addPossibleNext?: string
|
|
20
|
+
removePossibleNext?: string
|
|
21
|
+
possibleNextRowLabel?: string
|
|
12
22
|
minValue: string
|
|
13
23
|
maxValue: string
|
|
14
24
|
minLength: string
|
|
@@ -50,7 +60,8 @@ export interface FlowEditorLabels {
|
|
|
50
60
|
// (ex.: 'trigger_simulation') em vez do pacote assumir algum como padrão.
|
|
51
61
|
actionKindLabels: Record<string, string>
|
|
52
62
|
conditionOperatorLabels: Record<FlowConditionOperator, string>
|
|
53
|
-
|
|
63
|
+
/** `time` opcional: quem já passava a lista inteira continua compilando; ausente, vale o padrão. */
|
|
64
|
+
questionTypeLabels: Record<Exclude<FlowQuestionType, 'time'>, string> & { time?: string }
|
|
54
65
|
/** Opcional para não quebrar quem monta os textos à mão; ausente, vale o padrão pt-BR. */
|
|
55
66
|
runnerFields?: FlowRunnerFieldLabels
|
|
56
67
|
nodePanel: {
|
|
@@ -203,8 +214,26 @@ export interface FlowValidationLabels {
|
|
|
203
214
|
descriptionTooLong?: (id: string, label: string) => string
|
|
204
215
|
dynamicChoiceWithoutProvider?: (id: string) => string
|
|
205
216
|
choiceDefaultIgnored?: (id: string) => string
|
|
217
|
+
buttonTitleMayBeTooLong?: (id: string, label: string) => string
|
|
218
|
+
listTitleMayBeTooLong?: (id: string, label: string) => string
|
|
219
|
+
listButtonLabelTooLong?: (id: string, label: string) => string
|
|
220
|
+
listButtonLabelMayBeTooLong?: (id: string, label: string) => string
|
|
206
221
|
}
|
|
207
222
|
|
|
223
|
+
/** Padrões dos rótulos opcionais de `FlowRunnerFieldLabels` — o componente cai neles quando o host não passa. */
|
|
224
|
+
export const OPTIONAL_RUNNER_FIELD_LABEL_DEFAULTS = {
|
|
225
|
+
minTime: 'A partir de',
|
|
226
|
+
maxTime: 'Até',
|
|
227
|
+
timeWindowsContextKey: 'Faixas permitidas guardadas em',
|
|
228
|
+
timeWindowsContextKeyHint:
|
|
229
|
+
'Chave do contexto com as faixas (ex.: ["11:00-14:00"]), preenchida pelo sistema antes da pergunta.',
|
|
230
|
+
possibleNext: 'Destinos que a ação pode escolher',
|
|
231
|
+
possibleNextHint: 'A ação decide o caminho na hora. Liste aqui os destinos possíveis para eles aparecerem no mapa.',
|
|
232
|
+
addPossibleNext: 'Adicionar destino',
|
|
233
|
+
removePossibleNext: 'Remover destino',
|
|
234
|
+
possibleNextRowLabel: 'Pode seguir para',
|
|
235
|
+
} as const satisfies Partial<FlowRunnerFieldLabels>
|
|
236
|
+
|
|
208
237
|
export const DEFAULT_FLOW_RUNNER_FIELD_LABELS: FlowRunnerFieldLabels = {
|
|
209
238
|
section: 'Resposta do cliente',
|
|
210
239
|
fallbackMessage: 'Mensagem quando a resposta não serve',
|
|
@@ -213,6 +242,7 @@ export const DEFAULT_FLOW_RUNNER_FIELD_LABELS: FlowRunnerFieldLabels = {
|
|
|
213
242
|
maxInvalidAnswersHint: 'Vazio = padrão do bot (2).',
|
|
214
243
|
minDateToday: 'Só aceitar de hoje em diante',
|
|
215
244
|
afterContextKey: 'Depois da data guardada em',
|
|
245
|
+
...OPTIONAL_RUNNER_FIELD_LABEL_DEFAULTS,
|
|
216
246
|
minValue: 'Mínimo',
|
|
217
247
|
maxValue: 'Máximo',
|
|
218
248
|
minLength: 'Mínimo de caracteres',
|
|
@@ -274,6 +304,7 @@ export const DEFAULT_FLOW_EDITOR_LABELS: FlowEditorLabels = {
|
|
|
274
304
|
text: 'Texto livre',
|
|
275
305
|
money: 'Valor em R$',
|
|
276
306
|
date: 'Data',
|
|
307
|
+
time: 'Horário',
|
|
277
308
|
int: 'Número inteiro',
|
|
278
309
|
cpf: 'CPF',
|
|
279
310
|
choice: 'Escolha (botões/lista)',
|
|
@@ -386,6 +417,13 @@ export const DEFAULT_FLOW_EDITOR_LABELS: FlowEditorLabels = {
|
|
|
386
417
|
conditionIncomplete: (id) => `Nó "${id}": condição incompleta — defina variável, operador e valor.`,
|
|
387
418
|
conditionBranchMissing: (id, branch) =>
|
|
388
419
|
`Nó "${id}": ramo "${branch === 'true' ? 'Verdadeiro' : 'Falso'}" sem destino definido.`,
|
|
420
|
+
buttonTitleMayBeTooLong: (id, label) =>
|
|
421
|
+
`Nó "${id}": botão "${label}" tem variável e pode passar de 20 caracteres; confira o valor real.`,
|
|
422
|
+
listTitleMayBeTooLong: (id, label) =>
|
|
423
|
+
`Nó "${id}": item de lista "${label}" tem variável e pode passar de 24 caracteres; confira o valor real.`,
|
|
424
|
+
listButtonLabelTooLong: (id, label) => `Nó "${id}": botão da lista "${label}" passa de 20 caracteres.`,
|
|
425
|
+
listButtonLabelMayBeTooLong: (id, label) =>
|
|
426
|
+
`Nó "${id}": botão da lista "${label}" tem variável e pode passar de 20 caracteres; confira o valor real.`,
|
|
389
427
|
descriptionTooLong: (id, label) => `Nó "${id}": a descrição de "${label}" passa de 72 caracteres.`,
|
|
390
428
|
dynamicChoiceWithoutProvider: (id) => `Nó "${id}": escolha dinâmica sem provedor de opções.`,
|
|
391
429
|
choiceDefaultIgnored: (id) =>
|
package/src/index.ts
CHANGED
|
@@ -181,7 +181,7 @@ export { parseWhatsAppFormatting, waToHTML, htmlToWA, waToHTMLInline } from './l
|
|
|
181
181
|
export { WhatsAppMessagePreview } from './lib/WhatsAppMessagePreview'
|
|
182
182
|
export type { WhatsAppMessagePreviewProps } from './lib/WhatsAppMessagePreview'
|
|
183
183
|
export { WHATSAPP_MARKER_BY_ACTION } from './lib/composer-formatting'
|
|
184
|
-
export { formatPhone, phoneInitials } from './lib/phone'
|
|
184
|
+
export { formatPhone, phoneInitials, isTestContactNumber, TEST_CONTACT_LABEL } from './lib/phone'
|
|
185
185
|
// `formatDateTime` e `isSameDay` já eram usados pelas bolhas e pelo divisor de data; exportá-los
|
|
186
186
|
// evita que cada host mantenha a própria cópia e acabe com timeline e transcript divergindo.
|
|
187
187
|
export { formatTimestamp, formatFileSize, formatDateTime, isSameDay } from './lib/format'
|
|
@@ -286,6 +286,15 @@ export { QuickRepliesWorkspace, QuickRepliesPicker } from './quickReplies'
|
|
|
286
286
|
export type { QuickRepliesWorkspaceProps, QuickRepliesPickerProps } from './quickReplies'
|
|
287
287
|
export { DEFAULT_QUICK_REPLIES_PICKER_LABELS, DEFAULT_QUICK_REPLIES_WORKSPACE_LABELS } from './quickReplies/labels'
|
|
288
288
|
export type { QuickRepliesPickerLabels, QuickRepliesWorkspaceLabels } from './quickReplies/labels'
|
|
289
|
+
export {
|
|
290
|
+
createMetaWhatsAppQuickRepliesClient,
|
|
291
|
+
QuickRepliesApiError,
|
|
292
|
+
} from './quickReplies/createMetaWhatsAppQuickRepliesClient'
|
|
293
|
+
export type {
|
|
294
|
+
CreateMetaWhatsAppQuickRepliesClientParams,
|
|
295
|
+
MetaWhatsAppQuickRepliesClient,
|
|
296
|
+
QuickRepliesApiErrorDetail,
|
|
297
|
+
} from './quickReplies/createMetaWhatsAppQuickRepliesClient'
|
|
289
298
|
export { normalizeForSearch, filterQuickReplies, highlightMatch } from './quickReplies/quickReplySearch'
|
|
290
299
|
export type { FilterQuickRepliesParams, MatchSegment } from './quickReplies/quickReplySearch'
|
|
291
300
|
|
|
@@ -299,6 +308,7 @@ export type {
|
|
|
299
308
|
ConversationsWorkspaceSimulator,
|
|
300
309
|
SimulatorTransportFactory,
|
|
301
310
|
SimulatorTransportParams,
|
|
311
|
+
SimulatorTestContact,
|
|
302
312
|
ConversationsWorkspaceLabels,
|
|
303
313
|
ConversationPaneProps,
|
|
304
314
|
ConversationsInboxListProps,
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test'
|
|
2
|
+
|
|
3
|
+
import { formatPhone, isTestContactNumber, phoneCountryFlag } from './phone'
|
|
4
|
+
|
|
5
|
+
describe('número de teste do simulador', () => {
|
|
6
|
+
it('começando com 0 não vira telefone mascarado nem ganha bandeira', () => {
|
|
7
|
+
expect(isTestContactNumber('05511900001234')).toBe(true)
|
|
8
|
+
expect(formatPhone('05511900001234')).toBe('Contato de teste 1234')
|
|
9
|
+
expect(phoneCountryFlag('05511900001234')).toBe('')
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
it('telefone real continua formatado', () => {
|
|
13
|
+
expect(isTestContactNumber('5511900001234')).toBe(false)
|
|
14
|
+
expect(formatPhone('5511900001234')).toBe('+55 (11) 90000-1234')
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
it('id opaco com letras não é confundido com número de teste', () => {
|
|
18
|
+
expect(isTestContactNumber('0a1b2c3d-uuid')).toBe(false)
|
|
19
|
+
})
|
|
20
|
+
})
|
package/src/lib/phone.ts
CHANGED
|
@@ -1,6 +1,19 @@
|
|
|
1
|
+
/** Rótulo do número de teste do simulador, no lugar de uma máscara de telefone que não existe. */
|
|
2
|
+
export const TEST_CONTACT_LABEL = 'Contato de teste'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Nenhum código de país começa com 0, então um número só de dígitos começando com 0 não é telefone
|
|
6
|
+
* de verdade: é o contato de teste do simulador. Formatá-lo como telefone inventa um DDD.
|
|
7
|
+
*/
|
|
8
|
+
export function isTestContactNumber(number: string): boolean {
|
|
9
|
+
return /^0\d{3,}$/.test(number.replace(/[\s()+-]/g, ''))
|
|
10
|
+
}
|
|
11
|
+
|
|
1
12
|
export function formatPhone(number: string): string {
|
|
2
13
|
const digits = number.replace(/\D/g, '')
|
|
3
14
|
|
|
15
|
+
if (isTestContactNumber(number)) return `${TEST_CONTACT_LABEL} ${digits.slice(-4)}`
|
|
16
|
+
|
|
4
17
|
if (digits.length === 13) {
|
|
5
18
|
return `+${digits.slice(0, 2)} (${digits.slice(2, 4)}) ${digits.slice(4, 9)}-${digits.slice(9, 13)}`
|
|
6
19
|
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test'
|
|
2
|
+
|
|
3
|
+
import type { QuickRepliesWorkspaceApi } from './useQuickRepliesWorkspace'
|
|
4
|
+
import { QuickRepliesApiError, createMetaWhatsAppQuickRepliesClient } from './createMetaWhatsAppQuickRepliesClient'
|
|
5
|
+
|
|
6
|
+
type Call = { url: string; init: RequestInit }
|
|
7
|
+
|
|
8
|
+
function fakeFetch(respond: (call: Call) => Response) {
|
|
9
|
+
const calls: Call[] = []
|
|
10
|
+
const fetchImpl = (async (url: string, init: RequestInit) => {
|
|
11
|
+
const call = { url, init }
|
|
12
|
+
calls.push(call)
|
|
13
|
+
return respond(call)
|
|
14
|
+
}) as unknown as typeof fetch
|
|
15
|
+
return { calls, fetchImpl }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const json = (body: unknown, status = 200) =>
|
|
19
|
+
new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
|
|
20
|
+
|
|
21
|
+
const stored = { id: 'q1', title: 'Olá', shortcut: 'ola', body: 'Olá!', sortOrder: 0, createdAt: '', updatedAt: '' }
|
|
22
|
+
|
|
23
|
+
describe('createMetaWhatsAppQuickRepliesClient', () => {
|
|
24
|
+
it('lista desembrulhando { data } e manda o cabeçalho do host e a busca', async () => {
|
|
25
|
+
const { calls, fetchImpl } = fakeFetch(() => json({ data: [stored] }))
|
|
26
|
+
const client = createMetaWhatsAppQuickRepliesClient({
|
|
27
|
+
baseUrl: '/v1/whatsapp',
|
|
28
|
+
fetch: fetchImpl,
|
|
29
|
+
getHeaders: async () => ({ authorization: 'Bearer t' }),
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
expect(await client.listQuickReplies({ search: ' olá & x ' })).toEqual([stored])
|
|
33
|
+
expect(calls[0]?.url).toBe('/v1/whatsapp/quick-replies?search=ol%C3%A1+%26+x')
|
|
34
|
+
expect(calls[0]?.init.method).toBe('GET')
|
|
35
|
+
expect((calls[0]?.init.headers as Record<string, string>).authorization).toBe('Bearer t')
|
|
36
|
+
|
|
37
|
+
await client.listQuickReplies()
|
|
38
|
+
expect(calls[1]?.url).toBe('/v1/whatsapp/quick-replies')
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it('cria e edita mandando só título, atalho e texto', async () => {
|
|
42
|
+
const { calls, fetchImpl } = fakeFetch(() => json({ data: stored }, 200))
|
|
43
|
+
const client = createMetaWhatsAppQuickRepliesClient({ baseUrl: '/v1/whatsapp', fetch: fetchImpl })
|
|
44
|
+
const input = { title: 'Olá', shortcut: 'ola', body: 'Olá!', attachmentUploadIds: ['u1'] }
|
|
45
|
+
|
|
46
|
+
await client.createQuickReply(input)
|
|
47
|
+
await client.updateQuickReply('a/b', input)
|
|
48
|
+
|
|
49
|
+
expect(calls[0]?.init.method).toBe('POST')
|
|
50
|
+
expect(JSON.parse(String(calls[0]?.init.body))).toEqual({ title: 'Olá', shortcut: 'ola', body: 'Olá!' })
|
|
51
|
+
expect(calls[1]?.url).toBe('/v1/whatsapp/quick-replies/a%2Fb')
|
|
52
|
+
expect(calls[1]?.init.method).toBe('PUT')
|
|
53
|
+
expect((calls[1]?.init.headers as Record<string, string>)['content-type']).toBe('application/json')
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('apaga e aceita o 204 sem corpo', async () => {
|
|
57
|
+
const { calls, fetchImpl } = fakeFetch(() => new Response(null, { status: 204 }))
|
|
58
|
+
const client = createMetaWhatsAppQuickRepliesClient({ baseUrl: '/v1/whatsapp', fetch: fetchImpl })
|
|
59
|
+
|
|
60
|
+
await expect(client.deleteQuickReply('q1')).resolves.toBeUndefined()
|
|
61
|
+
expect(calls[0]?.init.method).toBe('DELETE')
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
it('erro de validação vira details { field, message } e o código estável chega à tela', async () => {
|
|
65
|
+
const { fetchImpl } = fakeFetch(() =>
|
|
66
|
+
json(
|
|
67
|
+
{
|
|
68
|
+
error: {
|
|
69
|
+
code: 'VALIDATION_ERROR',
|
|
70
|
+
message: 'Requisição inválida.',
|
|
71
|
+
issues: [{ path: 'shortcut', message: 'ruim' }],
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
400,
|
|
75
|
+
),
|
|
76
|
+
)
|
|
77
|
+
const client = createMetaWhatsAppQuickRepliesClient({ baseUrl: '/v1/whatsapp', fetch: fetchImpl })
|
|
78
|
+
|
|
79
|
+
const error = await client
|
|
80
|
+
.createQuickReply({ title: 'a', shortcut: 'A', body: 'b' })
|
|
81
|
+
.catch((caught: unknown) => caught)
|
|
82
|
+
expect(error).toBeInstanceOf(QuickRepliesApiError)
|
|
83
|
+
expect((error as QuickRepliesApiError).status).toBe(400)
|
|
84
|
+
expect((error as QuickRepliesApiError).details).toEqual([{ field: 'shortcut', message: 'ruim' }])
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
it('atalho em uso chega com o código que o QuickRepliesWorkspace reconhece', async () => {
|
|
88
|
+
const { fetchImpl } = fakeFetch(() =>
|
|
89
|
+
json({ error: { code: 'QUICK_REPLY_SHORTCUT_TAKEN', message: 'Esse atalho já está em uso.' } }, 409),
|
|
90
|
+
)
|
|
91
|
+
const client = createMetaWhatsAppQuickRepliesClient({ baseUrl: '/v1/whatsapp', fetch: fetchImpl })
|
|
92
|
+
|
|
93
|
+
const error = await client
|
|
94
|
+
.createQuickReply({ title: 'a', shortcut: 'a', body: 'b' })
|
|
95
|
+
.catch((caught: unknown) => caught)
|
|
96
|
+
expect((error as QuickRepliesApiError).code).toBe('QUICK_REPLY_SHORTCUT_TAKEN')
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
it('corpo de erro ilegível ainda vira QuickRepliesApiError com o status', async () => {
|
|
100
|
+
const { fetchImpl } = fakeFetch(() => new Response('<html>', { status: 502 }))
|
|
101
|
+
const client = createMetaWhatsAppQuickRepliesClient({ baseUrl: '/v1/whatsapp', fetch: fetchImpl })
|
|
102
|
+
|
|
103
|
+
const error = await client.listQuickReplies().catch((caught: unknown) => caught)
|
|
104
|
+
expect((error as QuickRepliesApiError).status).toBe(502)
|
|
105
|
+
expect((error as QuickRepliesApiError).code).toBe('HTTP_ERROR')
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
it('satisfaz a porta do QuickRepliesWorkspace', () => {
|
|
109
|
+
const client = createMetaWhatsAppQuickRepliesClient({ baseUrl: '/v1/whatsapp' })
|
|
110
|
+
const api: QuickRepliesWorkspaceApi = client
|
|
111
|
+
expect(typeof api.listQuickReplies).toBe('function')
|
|
112
|
+
})
|
|
113
|
+
})
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3
|
+
*
|
|
4
|
+
* Porta de respostas rápidas pronta para as rotas de `createMetaWhatsAppQuickReplyRoutes`
|
|
5
|
+
* (`@adatechnology/meta-whatsapp-module`). O resultado se espalha em `ConversationsApi` e satisfaz
|
|
6
|
+
* `QuickRepliesWorkspaceApi`; sem ele cada host reescrevia a mesma ponte — e errava o envelope.
|
|
7
|
+
*
|
|
8
|
+
* Só texto: anexos de resposta rápida não existem no módulo, então não há `uploadQuickReplyAttachment`
|
|
9
|
+
* e as telas não oferecem a seção de anexos.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { QuickReply, QuickReplyInput } from './quickReply.types'
|
|
13
|
+
|
|
14
|
+
export type CreateMetaWhatsAppQuickRepliesClientParams = {
|
|
15
|
+
/** Onde o host montou as rotas, ex.: `/v1/whatsapp`. Sem barra no fim; `/quick-replies` é acrescentado. */
|
|
16
|
+
readonly baseUrl: string
|
|
17
|
+
/** Cabeçalhos por requisição (o `Authorization` do host). Chamado a cada request. */
|
|
18
|
+
readonly getHeaders?: () => Record<string, string> | Promise<Record<string, string>>
|
|
19
|
+
readonly fetch?: typeof fetch
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type MetaWhatsAppQuickRepliesClient = {
|
|
23
|
+
readonly listQuickReplies: (params?: { search?: string }) => Promise<QuickReply[]>
|
|
24
|
+
readonly createQuickReply: (input: QuickReplyInput) => Promise<QuickReply>
|
|
25
|
+
readonly updateQuickReply: (id: string, input: QuickReplyInput) => Promise<QuickReply>
|
|
26
|
+
readonly deleteQuickReply: (id: string) => Promise<void>
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export type QuickRepliesApiErrorDetail = { readonly field: string; readonly message: string }
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Erro da API com `code` estável e `details` no formato que o `QuickRepliesWorkspace` lê
|
|
33
|
+
* (`{ field, message }`): a validação do módulo devolve `issues[{ path, message }]`, traduzido aqui
|
|
34
|
+
* para o erro aparecer no campo certo do formulário.
|
|
35
|
+
*/
|
|
36
|
+
export class QuickRepliesApiError extends Error {
|
|
37
|
+
constructor(
|
|
38
|
+
message: string,
|
|
39
|
+
readonly status: number,
|
|
40
|
+
readonly code: string,
|
|
41
|
+
readonly details: readonly QuickRepliesApiErrorDetail[] = [],
|
|
42
|
+
) {
|
|
43
|
+
super(message)
|
|
44
|
+
this.name = 'QuickRepliesApiError'
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
type ErrorBody = {
|
|
49
|
+
readonly error?: {
|
|
50
|
+
readonly code?: string
|
|
51
|
+
readonly message?: string
|
|
52
|
+
readonly issues?: readonly { readonly path?: string; readonly message?: string }[]
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function toApiError(response: Response): Promise<QuickRepliesApiError> {
|
|
57
|
+
const body = (await response.json().catch(() => undefined)) as ErrorBody | undefined
|
|
58
|
+
const details = (body?.error?.issues ?? []).flatMap((issue) =>
|
|
59
|
+
issue.path && issue.message ? [{ field: issue.path, message: issue.message }] : [],
|
|
60
|
+
)
|
|
61
|
+
return new QuickRepliesApiError(
|
|
62
|
+
body?.error?.message ?? `Falha na API de respostas rápidas (${response.status})`,
|
|
63
|
+
response.status,
|
|
64
|
+
body?.error?.code ?? 'HTTP_ERROR',
|
|
65
|
+
details,
|
|
66
|
+
)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Só o que o módulo aceita — `attachmentUploadIds` e afins ficam de fora do corpo.
|
|
70
|
+
function toBody(input: QuickReplyInput): Pick<QuickReplyInput, 'title' | 'shortcut' | 'body'> {
|
|
71
|
+
return { title: input.title, shortcut: input.shortcut, body: input.body }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function createMetaWhatsAppQuickRepliesClient(
|
|
75
|
+
params: CreateMetaWhatsAppQuickRepliesClientParams,
|
|
76
|
+
): MetaWhatsAppQuickRepliesClient {
|
|
77
|
+
const fetchImpl = params.fetch ?? globalThis.fetch.bind(globalThis)
|
|
78
|
+
const collectionUrl = `${params.baseUrl}/quick-replies`
|
|
79
|
+
|
|
80
|
+
async function request(url: string, method: string, json?: unknown): Promise<Response> {
|
|
81
|
+
const headers: Record<string, string> = { ...(await params.getHeaders?.()) }
|
|
82
|
+
if (json !== undefined) headers['content-type'] = 'application/json'
|
|
83
|
+
const response = await fetchImpl(url, {
|
|
84
|
+
method,
|
|
85
|
+
headers,
|
|
86
|
+
...(json === undefined ? {} : { body: JSON.stringify(json) }),
|
|
87
|
+
})
|
|
88
|
+
if (!response.ok) throw await toApiError(response)
|
|
89
|
+
return response
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function requestData<TResult>(url: string, method: string, json?: unknown): Promise<TResult> {
|
|
93
|
+
const response = await request(url, method, json)
|
|
94
|
+
return ((await response.json()) as { data: TResult }).data
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const itemUrl = (id: string): string => `${collectionUrl}/${encodeURIComponent(id)}`
|
|
98
|
+
|
|
99
|
+
return {
|
|
100
|
+
listQuickReplies: (listParams) => {
|
|
101
|
+
const search = listParams?.search?.trim()
|
|
102
|
+
const query = search ? `?${new URLSearchParams({ search }).toString()}` : ''
|
|
103
|
+
return requestData<QuickReply[]>(`${collectionUrl}${query}`, 'GET')
|
|
104
|
+
},
|
|
105
|
+
createQuickReply: (input) => requestData<QuickReply>(collectionUrl, 'POST', toBody(input)),
|
|
106
|
+
updateQuickReply: (id, input) => requestData<QuickReply>(itemUrl(id), 'PUT', toBody(input)),
|
|
107
|
+
deleteQuickReply: async (id) => {
|
|
108
|
+
await request(itemUrl(id), 'DELETE')
|
|
109
|
+
},
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -8,7 +8,11 @@
|
|
|
8
8
|
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
|
|
9
9
|
|
|
10
10
|
import { AudioRecorderButton } from '../AudioRecorderButton'
|
|
11
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
ConversationContextPanel,
|
|
13
|
+
type ConversationContextEntry,
|
|
14
|
+
type ConversationContextPanelLabels,
|
|
15
|
+
} from '../ConversationContextPanel'
|
|
12
16
|
import { ConversationDocumentsPanel } from '../ConversationDocumentsPanel'
|
|
13
17
|
import { ConversationHeader, type ConversationHeaderUtility } from '../ConversationHeader'
|
|
14
18
|
import { ConversationWallpaper } from '../Wallpaper'
|
|
@@ -50,6 +54,8 @@ export interface ConversationPaneProps {
|
|
|
50
54
|
readonly extraUtilities?: readonly ConversationHeaderUtility[]
|
|
51
55
|
/** Traduz o contexto cru do produto nas linhas do painel. Ausente, o painel não aparece. */
|
|
52
56
|
readonly contextEntriesOf?: (context: Record<string, unknown> | undefined) => readonly ConversationContextEntry[]
|
|
57
|
+
/** Vocabulário do painel de contexto (`title`, `empty`, `notCollected`...). */
|
|
58
|
+
readonly contextLabels?: Partial<ConversationContextPanelLabels>
|
|
53
59
|
readonly quickReplies?: readonly QuickReply[]
|
|
54
60
|
/**
|
|
55
61
|
* Recebe o contexto junto porque o dado que interessa à variável (o nome que o bot perguntou,
|
|
@@ -131,6 +137,7 @@ export function ConversationPane({
|
|
|
131
137
|
onBack,
|
|
132
138
|
extraUtilities,
|
|
133
139
|
contextEntriesOf,
|
|
140
|
+
contextLabels,
|
|
134
141
|
quickReplies,
|
|
135
142
|
quickReplyVariablesFor,
|
|
136
143
|
flowLabel,
|
|
@@ -355,7 +362,11 @@ export function ConversationPane({
|
|
|
355
362
|
/>
|
|
356
363
|
|
|
357
364
|
{(contextEntries && contextEntries.length > 0) || flowLabel ? (
|
|
358
|
-
<ConversationContextPanel
|
|
365
|
+
<ConversationContextPanel
|
|
366
|
+
entries={contextEntries ?? []}
|
|
367
|
+
{...(flowLabel ? { flowLabel } : {})}
|
|
368
|
+
{...(contextLabels ? { labels: contextLabels } : {})}
|
|
369
|
+
/>
|
|
359
370
|
) : null}
|
|
360
371
|
<ConversationDocumentsPanel conversationId={conversation.id} open={documentsOpen} />
|
|
361
372
|
|