@adatechnology/conversations-ui 0.15.1 → 0.17.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/{ConversationSimulatorPanel-P6eqTSAO.d.ts → ConversationSimulatorPanel-DSVIch04.d.ts} +3 -1
- 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 +90 -7
- package/dist/flows/index.js +1151 -455
- package/dist/index.d.ts +36 -5
- package/dist/index.js +88 -23
- package/dist/participant/index.js +1 -1
- package/dist/preview/index.d.ts +13 -29
- package/dist/preview/index.js +2 -2
- package/package.json +2 -2
- package/src/flows/FlowKeywordRoutesField.tsx +105 -0
- package/src/flows/FlowLegend.tsx +2 -2
- package/src/flows/FlowNodeCard.tsx +39 -10
- package/src/flows/FlowNodePanel.tsx +34 -10
- package/src/flows/FlowPalette.tsx +25 -2
- package/src/flows/FlowPossibleNextField.tsx +89 -0
- package/src/flows/FlowRunnerFields.tsx +321 -0
- package/src/flows/FlowWhatsAppPreview.tsx +39 -6
- package/src/flows/flowCanvasModel.test.ts +3 -2
- package/src/flows/flowCanvasModel.ts +28 -1
- package/src/flows/flowEditorOps.ts +41 -4
- package/src/flows/flowGraph.ts +124 -21
- package/src/flows/flowPanelStyles.ts +11 -0
- package/src/flows/flowPossibleNext.test.ts +70 -0
- package/src/flows/flowRunnerEditor.test.ts +116 -0
- package/src/flows/labels.ts +116 -2
- package/src/index.ts +2 -1
- package/src/lib/phone.test.ts +20 -0
- package/src/lib/phone.ts +13 -0
- package/src/preview/createPreviewBridgeClient.test.ts +23 -0
- package/src/preview/createPreviewBridgeClient.ts +13 -8
- package/src/preview/createPreviewWebhookClient.ts +2 -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/labels.ts
CHANGED
|
@@ -1,7 +1,57 @@
|
|
|
1
1
|
import type { FlowConditionOperator, FlowNodeType, FlowQuestionType } from './flowGraph'
|
|
2
2
|
|
|
3
|
+
/** Campos do runner de fluxo do módulo (validação, palavras-chave, descrições, escolha dinâmica). */
|
|
4
|
+
export interface FlowRunnerFieldLabels {
|
|
5
|
+
section: string
|
|
6
|
+
fallbackMessage: string
|
|
7
|
+
fallbackPlaceholder: string
|
|
8
|
+
maxInvalidAnswers: string
|
|
9
|
+
maxInvalidAnswersHint: string
|
|
10
|
+
minDateToday: string
|
|
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
|
|
22
|
+
minValue: string
|
|
23
|
+
maxValue: string
|
|
24
|
+
minLength: string
|
|
25
|
+
maxLength: string
|
|
26
|
+
skipKeywords: string
|
|
27
|
+
skipKeywordsHint: string
|
|
28
|
+
keywordRoutes: string
|
|
29
|
+
keywordRoutesHint: string
|
|
30
|
+
addKeywordRoute: string
|
|
31
|
+
removeKeywordRoute: string
|
|
32
|
+
keywordPlaceholder: string
|
|
33
|
+
optionDescription: string
|
|
34
|
+
optionSection: string
|
|
35
|
+
listButtonLabel: string
|
|
36
|
+
unmatchedChoice: string
|
|
37
|
+
unmatchedChoiceReask: string
|
|
38
|
+
unmatchedChoiceDefault: string
|
|
39
|
+
choiceProvider: string
|
|
40
|
+
choiceProviderHint: string
|
|
41
|
+
contextKey: string
|
|
42
|
+
placeholdersHint: string
|
|
43
|
+
paletteDynamicChoice: string
|
|
44
|
+
paletteDynamicChoiceHint: string
|
|
45
|
+
paletteMessage: string
|
|
46
|
+
paletteMessageHint: string
|
|
47
|
+
}
|
|
48
|
+
|
|
3
49
|
export interface FlowEditorLabels {
|
|
4
|
-
|
|
50
|
+
/**
|
|
51
|
+
* `dynamic_choice` é opcional para não quebrar quem já monta a legenda inteira à mão; ausente, vale
|
|
52
|
+
* o texto padrão.
|
|
53
|
+
*/
|
|
54
|
+
legend: Record<Exclude<FlowNodeType, 'dynamic_choice'>, string> & { dynamic_choice?: string }
|
|
5
55
|
startNodeTooltip: string
|
|
6
56
|
detachedNodeTooltip: string
|
|
7
57
|
liveCountTooltip: (count: number) => string
|
|
@@ -10,7 +60,10 @@ export interface FlowEditorLabels {
|
|
|
10
60
|
// (ex.: 'trigger_simulation') em vez do pacote assumir algum como padrão.
|
|
11
61
|
actionKindLabels: Record<string, string>
|
|
12
62
|
conditionOperatorLabels: Record<FlowConditionOperator, string>
|
|
13
|
-
|
|
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 }
|
|
65
|
+
/** Opcional para não quebrar quem monta os textos à mão; ausente, vale o padrão pt-BR. */
|
|
66
|
+
runnerFields?: FlowRunnerFieldLabels
|
|
14
67
|
nodePanel: {
|
|
15
68
|
title: string
|
|
16
69
|
contextKey: string
|
|
@@ -158,6 +211,59 @@ export interface FlowValidationLabels {
|
|
|
158
211
|
deadEndQuestion: (id: string) => string
|
|
159
212
|
conditionIncomplete: (id: string) => string
|
|
160
213
|
conditionBranchMissing: (id: string, branch: string) => string
|
|
214
|
+
descriptionTooLong?: (id: string, label: string) => string
|
|
215
|
+
dynamicChoiceWithoutProvider?: (id: string) => string
|
|
216
|
+
choiceDefaultIgnored?: (id: string) => string
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Padrões dos rótulos opcionais de `FlowRunnerFieldLabels` — o componente cai neles quando o host não passa. */
|
|
220
|
+
export const OPTIONAL_RUNNER_FIELD_LABEL_DEFAULTS = {
|
|
221
|
+
minTime: 'A partir de',
|
|
222
|
+
maxTime: 'Até',
|
|
223
|
+
timeWindowsContextKey: 'Faixas permitidas guardadas em',
|
|
224
|
+
timeWindowsContextKeyHint:
|
|
225
|
+
'Chave do contexto com as faixas (ex.: ["11:00-14:00"]), preenchida pelo sistema antes da pergunta.',
|
|
226
|
+
possibleNext: 'Destinos que a ação pode escolher',
|
|
227
|
+
possibleNextHint: 'A ação decide o caminho na hora. Liste aqui os destinos possíveis para eles aparecerem no mapa.',
|
|
228
|
+
addPossibleNext: 'Adicionar destino',
|
|
229
|
+
removePossibleNext: 'Remover destino',
|
|
230
|
+
possibleNextRowLabel: 'Pode seguir para',
|
|
231
|
+
} as const satisfies Partial<FlowRunnerFieldLabels>
|
|
232
|
+
|
|
233
|
+
export const DEFAULT_FLOW_RUNNER_FIELD_LABELS: FlowRunnerFieldLabels = {
|
|
234
|
+
section: 'Resposta do cliente',
|
|
235
|
+
fallbackMessage: 'Mensagem quando a resposta não serve',
|
|
236
|
+
fallbackPlaceholder: 'Ex.: Não entendi. Escolha uma das opções.',
|
|
237
|
+
maxInvalidAnswers: 'Tentativas antes de chamar uma pessoa',
|
|
238
|
+
maxInvalidAnswersHint: 'Vazio = padrão do bot (2).',
|
|
239
|
+
minDateToday: 'Só aceitar de hoje em diante',
|
|
240
|
+
afterContextKey: 'Depois da data guardada em',
|
|
241
|
+
...OPTIONAL_RUNNER_FIELD_LABEL_DEFAULTS,
|
|
242
|
+
minValue: 'Mínimo',
|
|
243
|
+
maxValue: 'Máximo',
|
|
244
|
+
minLength: 'Mínimo de caracteres',
|
|
245
|
+
maxLength: 'Máximo de caracteres',
|
|
246
|
+
skipKeywords: 'Palavras que pulam a pergunta',
|
|
247
|
+
skipKeywordsHint: 'Separadas por vírgula. Ex.: pular, não sei',
|
|
248
|
+
keywordRoutes: 'Palavras-chave (texto livre)',
|
|
249
|
+
keywordRoutesHint: 'Se a mensagem contiver a palavra, segue para o destino — sem acento e sem maiúscula.',
|
|
250
|
+
addKeywordRoute: 'Adicionar palavra-chave',
|
|
251
|
+
removeKeywordRoute: 'Remover palavra-chave',
|
|
252
|
+
keywordPlaceholder: 'horário',
|
|
253
|
+
optionDescription: 'Descrição (lista)',
|
|
254
|
+
optionSection: 'Seção',
|
|
255
|
+
listButtonLabel: 'Texto do botão da lista',
|
|
256
|
+
unmatchedChoice: 'Resposta fora das opções',
|
|
257
|
+
unmatchedChoiceReask: 'Perguntar de novo (padrão)',
|
|
258
|
+
unmatchedChoiceDefault: 'Seguir o "Caso contrário"',
|
|
259
|
+
choiceProvider: 'Provedor de opções',
|
|
260
|
+
choiceProviderHint: 'Chave registrada pelo sistema (registerDynamicChoiceProvider).',
|
|
261
|
+
contextKey: 'Guardar a escolha em',
|
|
262
|
+
placeholdersHint: 'Use {{chave}} para inserir respostas anteriores, ex.: {{contactFirstName}}.',
|
|
263
|
+
paletteDynamicChoice: 'Escolha dinâmica',
|
|
264
|
+
paletteDynamicChoiceHint: 'Opções calculadas na hora pelo sistema, com "ver mais"',
|
|
265
|
+
paletteMessage: 'Mensagem',
|
|
266
|
+
paletteMessageHint: 'Envia um texto e segue para o próximo passo',
|
|
161
267
|
}
|
|
162
268
|
|
|
163
269
|
// Paridade de texto com financiamento-imobiliario-bot/apps/web/src/locales/modules/flows.ts —
|
|
@@ -169,6 +275,7 @@ export const DEFAULT_FLOW_EDITOR_LABELS: FlowEditorLabels = {
|
|
|
169
275
|
action: 'Ação (simulação/atendimento)',
|
|
170
276
|
menu: 'Menu',
|
|
171
277
|
condition: 'Condição',
|
|
278
|
+
dynamic_choice: 'Escolha dinâmica',
|
|
172
279
|
},
|
|
173
280
|
startNodeTooltip: 'Início do fluxo',
|
|
174
281
|
detachedNodeTooltip: 'Sem ligação de entrada — o bot não chega neste nó. Puxe um fio de outro card até ele.',
|
|
@@ -193,10 +300,12 @@ export const DEFAULT_FLOW_EDITOR_LABELS: FlowEditorLabels = {
|
|
|
193
300
|
text: 'Texto livre',
|
|
194
301
|
money: 'Valor em R$',
|
|
195
302
|
date: 'Data',
|
|
303
|
+
time: 'Horário',
|
|
196
304
|
int: 'Número inteiro',
|
|
197
305
|
cpf: 'CPF',
|
|
198
306
|
choice: 'Escolha (botões/lista)',
|
|
199
307
|
},
|
|
308
|
+
runnerFields: DEFAULT_FLOW_RUNNER_FIELD_LABELS,
|
|
200
309
|
nodePanel: {
|
|
201
310
|
title: 'Editar nó',
|
|
202
311
|
contextKey: 'Chave (contexto)',
|
|
@@ -304,6 +413,10 @@ export const DEFAULT_FLOW_EDITOR_LABELS: FlowEditorLabels = {
|
|
|
304
413
|
conditionIncomplete: (id) => `Nó "${id}": condição incompleta — defina variável, operador e valor.`,
|
|
305
414
|
conditionBranchMissing: (id, branch) =>
|
|
306
415
|
`Nó "${id}": ramo "${branch === 'true' ? 'Verdadeiro' : 'Falso'}" sem destino definido.`,
|
|
416
|
+
descriptionTooLong: (id, label) => `Nó "${id}": a descrição de "${label}" passa de 72 caracteres.`,
|
|
417
|
+
dynamicChoiceWithoutProvider: (id) => `Nó "${id}": escolha dinâmica sem provedor de opções.`,
|
|
418
|
+
choiceDefaultIgnored: (id) =>
|
|
419
|
+
`Nó "${id}": o bot repergunta quando a resposta não casa com uma opção, então "Caso contrário" não é seguido. Para seguir, mude "Resposta fora das opções".`,
|
|
307
420
|
},
|
|
308
421
|
workspace: {
|
|
309
422
|
title: 'Fluxos do Bot',
|
|
@@ -352,6 +465,7 @@ export function mergeFlowEditorLabels(override?: Partial<FlowEditorLabels>): Flo
|
|
|
352
465
|
...override.conditionOperatorLabels,
|
|
353
466
|
},
|
|
354
467
|
questionTypeLabels: { ...DEFAULT_FLOW_EDITOR_LABELS.questionTypeLabels, ...override.questionTypeLabels },
|
|
468
|
+
runnerFields: { ...DEFAULT_FLOW_RUNNER_FIELD_LABELS, ...override.runnerFields },
|
|
355
469
|
nodePanel: { ...DEFAULT_FLOW_EDITOR_LABELS.nodePanel, ...override.nodePanel },
|
|
356
470
|
quickAdd: { ...DEFAULT_FLOW_EDITOR_LABELS.quickAdd, ...override.quickAdd },
|
|
357
471
|
legendPanel: { ...DEFAULT_FLOW_EDITOR_LABELS.legendPanel, ...override.legendPanel },
|
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'
|
|
@@ -299,6 +299,7 @@ export type {
|
|
|
299
299
|
ConversationsWorkspaceSimulator,
|
|
300
300
|
SimulatorTransportFactory,
|
|
301
301
|
SimulatorTransportParams,
|
|
302
|
+
SimulatorTestContact,
|
|
302
303
|
ConversationsWorkspaceLabels,
|
|
303
304
|
ConversationPaneProps,
|
|
304
305
|
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
|
}
|
|
@@ -8,6 +8,7 @@ import { describe, expect, it } from 'bun:test'
|
|
|
8
8
|
|
|
9
9
|
import { createPreviewBridgeClient, PreviewBridgeRejectedError } from './createPreviewBridgeClient'
|
|
10
10
|
import type { PreviewInboundCommand } from './createPreviewBridgeClient'
|
|
11
|
+
import { DEFAULT_PREVIEW_CONTACT } from '@adatechnology/meta-whatsapp-contracts'
|
|
11
12
|
|
|
12
13
|
const FROM = '5511999999999'
|
|
13
14
|
|
|
@@ -90,3 +91,25 @@ describe('createPreviewBridgeClient', () => {
|
|
|
90
91
|
expect(() => createPreviewBridgeClient({ from: FROM })).toThrow(/sendCommand.*endpointUrl/)
|
|
91
92
|
})
|
|
92
93
|
})
|
|
94
|
+
|
|
95
|
+
describe('createPreviewBridgeClient — contato simulado', () => {
|
|
96
|
+
it('usa o `from` exatamente como o host passou (sem trocar para o contato de simulador)', async () => {
|
|
97
|
+
const commands: PreviewInboundCommand[] = []
|
|
98
|
+
const client = createPreviewBridgeClient({
|
|
99
|
+
from: '5511999990000',
|
|
100
|
+
sendCommand: async (command) => void commands.push(command),
|
|
101
|
+
})
|
|
102
|
+
await client.sendText('oi')
|
|
103
|
+
expect(commands[0]?.from).toBe('5511999990000')
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
it('contato de simulador é opt-in: passar DEFAULT_PREVIEW_CONTACT', async () => {
|
|
107
|
+
const commands: PreviewInboundCommand[] = []
|
|
108
|
+
const client = createPreviewBridgeClient({
|
|
109
|
+
from: DEFAULT_PREVIEW_CONTACT,
|
|
110
|
+
sendCommand: async (command) => void commands.push(command),
|
|
111
|
+
})
|
|
112
|
+
await client.sendText('oi')
|
|
113
|
+
expect(commands[0]?.from).toBe(DEFAULT_PREVIEW_CONTACT)
|
|
114
|
+
})
|
|
115
|
+
})
|
|
@@ -15,12 +15,11 @@
|
|
|
15
15
|
* porque token, cookie e cabeçalho de sessão são do produto, não da biblioteca.
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
|
-
import type { InboundMediaType,
|
|
18
|
+
import type { InboundMediaType, PreviewInboundCommand } from '@adatechnology/meta-whatsapp-contracts/testing'
|
|
19
19
|
import {
|
|
20
20
|
createPreviewMediaPoster,
|
|
21
21
|
defaultMediaUploadUrl,
|
|
22
22
|
type PreviewWebhookClient,
|
|
23
|
-
type SendPreviewMediaParams,
|
|
24
23
|
} from './createPreviewWebhookClient'
|
|
25
24
|
import type { PreviewUploadedMedia } from './createPreviewMediaUploader'
|
|
26
25
|
|
|
@@ -28,13 +27,11 @@ import type { PreviewUploadedMedia } from './createPreviewMediaUploader'
|
|
|
28
27
|
* Comando semântico entregue ao host. É deliberadamente o QUE o cliente fez, não o payload da Meta:
|
|
29
28
|
* se o navegador mandasse o payload pronto, a rota viraria um injetor de webhook arbitrário para
|
|
30
29
|
* quem tivesse sessão. Mandando a intenção, o servidor é quem escolhe a forma.
|
|
30
|
+
*
|
|
31
|
+
* O tipo mora no contrato: o servidor monta o payload com `buildPreviewInboundPayload` (ou
|
|
32
|
+
* `webhook.buildPreviewPayload` do módulo, que já põe o `phone_number_id` certo).
|
|
31
33
|
*/
|
|
32
|
-
export type PreviewInboundCommand
|
|
33
|
-
| { readonly kind: 'text'; readonly from: string; readonly text: string }
|
|
34
|
-
| { readonly kind: 'buttonReply'; readonly from: string; readonly reply: InteractiveReplyOption }
|
|
35
|
-
| { readonly kind: 'listReply'; readonly from: string; readonly reply: InteractiveReplyOption }
|
|
36
|
-
| { readonly kind: 'audio'; readonly from: string; readonly mediaId: string }
|
|
37
|
-
| ({ readonly kind: 'media'; readonly from: string } & SendPreviewMediaParams)
|
|
34
|
+
export type { PreviewInboundCommand }
|
|
38
35
|
|
|
39
36
|
export type SendPreviewInboundCommand = (command: PreviewInboundCommand) => Promise<void>
|
|
40
37
|
|
|
@@ -46,6 +43,14 @@ export class PreviewBridgeRejectedError extends Error {
|
|
|
46
43
|
}
|
|
47
44
|
|
|
48
45
|
export type CreatePreviewBridgeClientParams = {
|
|
46
|
+
/**
|
|
47
|
+
* Número do contato simulado, usado como veio — trocar o número abre outra conversa.
|
|
48
|
+
*
|
|
49
|
+
* Contato de simulador sem chamar a Meta é opt-in nas DUAS pontas: aqui
|
|
50
|
+
* `from: DEFAULT_PREVIEW_CONTACT` (começa com `0`, que nenhum número real usa) e, no servidor,
|
|
51
|
+
* `features.previewContacts: true`. Só um dos lados ligado não serve: sem a flag, o servidor tentaria
|
|
52
|
+
* responder pela Meta a um número que não existe.
|
|
53
|
+
*/
|
|
49
54
|
readonly from: string
|
|
50
55
|
/**
|
|
51
56
|
* Entrega o comando. Use quando o host já tem um cliente HTTP com sessão, interceptors e refresh
|
|
@@ -64,7 +64,9 @@ export type SendPreviewMediaParams = {
|
|
|
64
64
|
export type CreatePreviewWebhookClientParams = {
|
|
65
65
|
readonly webhookUrl: string
|
|
66
66
|
readonly appSecret: string
|
|
67
|
+
/** Usado como veio. Para contato de simulador, ver `createPreviewBridgeClient` (`from` + `features.previewContacts`). */
|
|
67
68
|
readonly from: string
|
|
69
|
+
/** O `phone_number_id` do host. Sem ele o webhook descarta a entrega no filtro de número. */
|
|
68
70
|
readonly phoneNumberId?: string
|
|
69
71
|
/**
|
|
70
72
|
* Rota que guarda o áudio gravado. Por padrão, `/v1/preview/media` na mesma origem do webhook.
|
|
@@ -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
|
|
|
@@ -17,10 +17,10 @@
|
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
19
|
import { useEffect, useMemo, useState, type ReactNode } from 'react'
|
|
20
|
-
import { Check, CheckCheck, FlaskConical, Hourglass, Mail, MessagesSquare } from 'lucide-react'
|
|
20
|
+
import { Check, CheckCheck, FlaskConical, Hourglass, Mail, MessagesSquare, UserPlus } from 'lucide-react'
|
|
21
21
|
|
|
22
22
|
import { ICON_SIZE_ACTION, ICON_SIZE_INLINE } from '../icon.constant'
|
|
23
|
-
import type { ConversationContextEntry } from '../ConversationContextPanel'
|
|
23
|
+
import type { ConversationContextEntry, ConversationContextPanelLabels } from '../ConversationContextPanel'
|
|
24
24
|
import type { ConversationHeaderUtility } from '../ConversationHeader'
|
|
25
25
|
import type { QuickReply } from '../MessageComposer'
|
|
26
26
|
import type { RichComposerVariable } from '../RichMessageComposer'
|
|
@@ -57,6 +57,18 @@ export type SimulatorTransportParams = {
|
|
|
57
57
|
*/
|
|
58
58
|
export type SimulatorTransportFactory = (params: SimulatorTransportParams) => ConversationSimulatorClient
|
|
59
59
|
|
|
60
|
+
/**
|
|
61
|
+
* Contato de teste que o host cria para abrir o simulador sem conversa selecionada. `handle` é o
|
|
62
|
+
* identificador no canal (no WhatsApp, um número de teste começando com `0`, que nenhum país usa).
|
|
63
|
+
*/
|
|
64
|
+
export type SimulatorTestContact = {
|
|
65
|
+
readonly handle: string
|
|
66
|
+
/** Ausente = WhatsApp. */
|
|
67
|
+
readonly channel?: ConversationChannel
|
|
68
|
+
/** Id da conversa quando o host já o conhece. Ausente, usa `handle` e o transcript começa vazio. */
|
|
69
|
+
readonly conversationId?: string
|
|
70
|
+
}
|
|
71
|
+
|
|
60
72
|
export interface ConversationsWorkspaceSimulator {
|
|
61
73
|
/**
|
|
62
74
|
* Um transporte por canal — o workspace monta o painel com o da conversa selecionada.
|
|
@@ -84,6 +96,27 @@ export interface ConversationsWorkspaceSimulator {
|
|
|
84
96
|
readonly uploadMedia?: (file: File) => Promise<PreviewUploadedMedia>
|
|
85
97
|
/** Recarrega o transcript a cada N ms. Serve a host sem stream. */
|
|
86
98
|
readonly pollIntervalMs?: number
|
|
99
|
+
/**
|
|
100
|
+
* Liga "Novo contato de teste" no cabeçalho da página: o host devolve o contato e o simulador
|
|
101
|
+
* abre sem conversa selecionada. Quando a conversa dele aparece na lista, ela é selecionada.
|
|
102
|
+
* Ausente, o simulador só abre sobre uma conversa existente.
|
|
103
|
+
*/
|
|
104
|
+
readonly createTestContact?: () => SimulatorTestContact | Promise<SimulatorTestContact>
|
|
105
|
+
/** Rótulo do botão de novo contato. Padrão: "Novo contato de teste". */
|
|
106
|
+
readonly newContactLabel?: string
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
type SimulatorTarget = {
|
|
110
|
+
readonly key: string
|
|
111
|
+
readonly conversationId: string
|
|
112
|
+
readonly channel: ConversationChannel
|
|
113
|
+
readonly handle: string
|
|
114
|
+
/** `false` enquanto a conversa do contato de teste ainda não existe no servidor. */
|
|
115
|
+
readonly persisted: boolean
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function handleOf(conversation: ConversationSummary): string {
|
|
119
|
+
return conversation.contactId ?? conversation.whatsappNumber
|
|
87
120
|
}
|
|
88
121
|
|
|
89
122
|
export interface ConversationsWorkspaceProps {
|
|
@@ -141,6 +174,8 @@ export interface ConversationsWorkspaceProps {
|
|
|
141
174
|
/** Nota de voz. Ausente, o microfone não aparece. */
|
|
142
175
|
readonly onRecordAudio?: (conversation: ConversationSummary, file: File) => Promise<void>
|
|
143
176
|
readonly contextEntriesOf?: (context: Record<string, unknown> | undefined) => readonly ConversationContextEntry[]
|
|
177
|
+
/** Vocabulário do painel de contexto (`title`, `empty`, `notCollected`...). */
|
|
178
|
+
readonly contextLabels?: Partial<ConversationContextPanelLabels>
|
|
144
179
|
readonly onAttach?: (conversation: ConversationSummary, file: File) => Promise<void>
|
|
145
180
|
readonly extraUtilitiesFor?: (conversation: ConversationSummary) => readonly ConversationHeaderUtility[]
|
|
146
181
|
readonly renderFilters?: (inbox: UseConversationsInboxResult) => ReactNode
|
|
@@ -179,6 +214,7 @@ export function ConversationsWorkspace({
|
|
|
179
214
|
onSendAttachments,
|
|
180
215
|
onRecordAudio,
|
|
181
216
|
contextEntriesOf,
|
|
217
|
+
contextLabels,
|
|
182
218
|
onAttach,
|
|
183
219
|
extraUtilitiesFor,
|
|
184
220
|
renderFilters,
|
|
@@ -198,6 +234,7 @@ export function ConversationsWorkspace({
|
|
|
198
234
|
...(serverPaginated ? { serverPaginated } : {}),
|
|
199
235
|
})
|
|
200
236
|
const [simulatorOpen, setSimulatorOpen] = useState(false)
|
|
237
|
+
const [testContact, setTestContact] = useState<SimulatorTestContact | undefined>(undefined)
|
|
201
238
|
const [templateModalOpen, setTemplateModalOpen] = useState(false)
|
|
202
239
|
const [openedFromLink, setOpenedFromLink] = useState<string | undefined>(undefined)
|
|
203
240
|
|
|
@@ -216,23 +253,68 @@ export function ConversationsWorkspace({
|
|
|
216
253
|
}, [initialConversationId, initialWhatsappNumber, openedFromLink, inbox])
|
|
217
254
|
|
|
218
255
|
const selected = inbox.selectedConversation
|
|
256
|
+
|
|
257
|
+
// O contato de teste vira conversa de verdade no primeiro envio; achando-a na lista, ela passa a
|
|
258
|
+
// ser a selecionada e o painel segue sobre ela.
|
|
259
|
+
useEffect(() => {
|
|
260
|
+
if (!testContact) return
|
|
261
|
+
const created = inbox.conversations.find((conversation) => handleOf(conversation) === testContact.handle)
|
|
262
|
+
if (!created) return
|
|
263
|
+
inbox.selectConversation(created.id)
|
|
264
|
+
setTestContact(undefined)
|
|
265
|
+
}, [testContact, inbox])
|
|
266
|
+
|
|
219
267
|
const conversations = useConversations()
|
|
220
|
-
const
|
|
221
|
-
|
|
222
|
-
|
|
268
|
+
const target: SimulatorTarget | undefined = selected
|
|
269
|
+
? {
|
|
270
|
+
key: selected.id,
|
|
271
|
+
conversationId: selected.id,
|
|
272
|
+
channel: selected.channel ?? DEFAULT_CONVERSATION_CHANNEL,
|
|
273
|
+
handle: handleOf(selected),
|
|
274
|
+
persisted: true,
|
|
275
|
+
}
|
|
276
|
+
: testContact
|
|
277
|
+
? {
|
|
278
|
+
key: `test-contact:${testContact.handle}`,
|
|
279
|
+
// Sem id conhecido, o próprio identificador: é a chave do stream por conversa (`conv:<número>`).
|
|
280
|
+
conversationId: testContact.conversationId ?? testContact.handle,
|
|
281
|
+
channel: testContact.channel ?? DEFAULT_CONVERSATION_CHANNEL,
|
|
282
|
+
handle: testContact.handle,
|
|
283
|
+
persisted: testContact.conversationId !== undefined,
|
|
284
|
+
}
|
|
285
|
+
: undefined
|
|
286
|
+
const channel = target?.channel ?? DEFAULT_CONVERSATION_CHANNEL
|
|
287
|
+
const targetConversationId = target?.conversationId
|
|
288
|
+
const handle = target?.handle ?? ''
|
|
223
289
|
const transport = simulator?.transports?.[channel]
|
|
224
|
-
const
|
|
225
|
-
|
|
226
|
-
)
|
|
227
|
-
const
|
|
290
|
+
const simulatorAvailable = Boolean(simulator && (simulator.enabled ?? true))
|
|
291
|
+
const simulatorEnabled = simulatorAvailable && Boolean(simulator?.render ?? transport)
|
|
292
|
+
const showSimulator = simulatorEnabled && simulatorOpen && Boolean(target)
|
|
293
|
+
const canCreateTestContact = simulatorAvailable && Boolean(simulator?.createTestContact)
|
|
228
294
|
|
|
229
295
|
// O transporte é recriado só quando a conversa (ou o canal dela) muda: identidade nova a cada
|
|
230
296
|
// render reiniciaria a leitura do transcript dentro do painel a cada digitação.
|
|
231
297
|
const simulatorClient = useMemo(
|
|
232
|
-
() =>
|
|
233
|
-
|
|
298
|
+
() =>
|
|
299
|
+
transport && targetConversationId !== undefined
|
|
300
|
+
? transport({ conversationId: targetConversationId, channel, handle })
|
|
301
|
+
: undefined,
|
|
302
|
+
[transport, targetConversationId, channel, handle],
|
|
234
303
|
)
|
|
235
304
|
|
|
305
|
+
async function handleCreateTestContact(): Promise<void> {
|
|
306
|
+
const contact = await simulator?.createTestContact?.()
|
|
307
|
+
if (!contact) return
|
|
308
|
+
inbox.clearSelection()
|
|
309
|
+
setTestContact(contact)
|
|
310
|
+
setSimulatorOpen(true)
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function closeSimulator(): void {
|
|
314
|
+
setSimulatorOpen(false)
|
|
315
|
+
setTestContact(undefined)
|
|
316
|
+
}
|
|
317
|
+
|
|
236
318
|
const paneUtilities = useMemo(() => {
|
|
237
319
|
if (!selected) return undefined
|
|
238
320
|
const fromProduct = extraUtilitiesFor?.(selected) ?? []
|
|
@@ -313,6 +395,18 @@ export function ConversationsWorkspace({
|
|
|
313
395
|
<span className="cv-only-wide">{labels.markAllAsRead}</span>
|
|
314
396
|
</button>
|
|
315
397
|
) : null}
|
|
398
|
+
{canCreateTestContact ? (
|
|
399
|
+
<button
|
|
400
|
+
type="button"
|
|
401
|
+
onClick={() => void handleCreateTestContact()}
|
|
402
|
+
data-cv-tooltip={simulator?.newContactLabel ?? labels.newTestContact}
|
|
403
|
+
aria-label={simulator?.newContactLabel ?? labels.newTestContact}
|
|
404
|
+
className="cv-workspace-toggle"
|
|
405
|
+
>
|
|
406
|
+
<UserPlus size={ICON_SIZE_ACTION} aria-hidden="true" />
|
|
407
|
+
<span className="cv-only-wide">{simulator?.newContactLabel ?? labels.newTestContact}</span>
|
|
408
|
+
</button>
|
|
409
|
+
) : null}
|
|
316
410
|
{renderHeaderActions?.(inbox)}
|
|
317
411
|
</div>
|
|
318
412
|
</header>
|
|
@@ -340,7 +434,7 @@ export function ConversationsWorkspace({
|
|
|
340
434
|
separação por espaço lê mais rápido que por borda. */}
|
|
341
435
|
<div
|
|
342
436
|
className={`cv-workspace-grid${showSimulator ? ' cv-workspace-grid--with-simulator' : ''}`}
|
|
343
|
-
data-detail={selected ? 'open' : 'closed'}
|
|
437
|
+
data-detail={selected || showSimulator ? 'open' : 'closed'}
|
|
344
438
|
>
|
|
345
439
|
<ConversationsInboxList
|
|
346
440
|
inbox={inbox}
|
|
@@ -385,6 +479,7 @@ export function ConversationsWorkspace({
|
|
|
385
479
|
onBack={inbox.clearSelection}
|
|
386
480
|
{...(paneUtilities ? { extraUtilities: paneUtilities } : {})}
|
|
387
481
|
{...(contextEntriesOf ? { contextEntriesOf } : {})}
|
|
482
|
+
{...(contextLabels ? { contextLabels } : {})}
|
|
388
483
|
{...(quickReplies ? { quickReplies } : {})}
|
|
389
484
|
{...(quickReplyVariablesFor ? { quickReplyVariablesFor } : {})}
|
|
390
485
|
{...(renderAboveTranscript ? { renderAboveTranscript } : {})}
|
|
@@ -395,24 +490,28 @@ export function ConversationsWorkspace({
|
|
|
395
490
|
)}
|
|
396
491
|
</section>
|
|
397
492
|
|
|
398
|
-
{showSimulator &&
|
|
493
|
+
{showSimulator && target ? (
|
|
399
494
|
// `min-height:0` junto do `min-width:0`: sem isso a linha do grid cresce com o conteúdo do
|
|
400
495
|
// painel, o scroll interno nunca ativa e quem rola passa a ser a página inteira.
|
|
401
496
|
<div className="cv-workspace-simulator">
|
|
402
497
|
{simulator?.render ? (
|
|
403
|
-
simulator.render({ conversationId:
|
|
498
|
+
simulator.render({ conversationId: target.conversationId, channel, close: closeSimulator })
|
|
404
499
|
) : simulatorClient && conversations ? (
|
|
405
500
|
// `key` pela conversa: trocar de contato sem remontar deixaria o transcript e o campo
|
|
406
501
|
// de texto do contato anterior na tela.
|
|
407
502
|
<ConversationSimulatorPanel
|
|
408
|
-
key={
|
|
503
|
+
key={target.key}
|
|
409
504
|
client={simulatorClient}
|
|
410
505
|
sse={conversations.sse}
|
|
411
|
-
conversationId={
|
|
506
|
+
conversationId={target.conversationId}
|
|
412
507
|
channel={channel}
|
|
413
508
|
displayHandle={formatContactHandle({ handle, channel })}
|
|
414
|
-
|
|
415
|
-
|
|
509
|
+
// Contato de teste sem conversa ainda: nada a ler. O eco local mostra o que foi
|
|
510
|
+
// enviado até a conversa aparecer na lista e o painel passar para ela.
|
|
511
|
+
loadMessages={(conversationId) =>
|
|
512
|
+
target.persisted ? conversations.api.fetchMessages(conversationId) : Promise.resolve([])
|
|
513
|
+
}
|
|
514
|
+
onClose={closeSimulator}
|
|
416
515
|
{...(simulator?.labels ? { labels: simulator.labels } : {})}
|
|
417
516
|
{...(simulator?.uploadMedia ? { uploadMedia: simulator.uploadMedia } : {})}
|
|
418
517
|
{...(simulator?.pollIntervalMs ? { pollIntervalMs: simulator.pollIntervalMs } : {})}
|
package/src/workspace/index.ts
CHANGED
|
@@ -4,6 +4,7 @@ export type {
|
|
|
4
4
|
ConversationsWorkspaceSimulator,
|
|
5
5
|
SimulatorTransportFactory,
|
|
6
6
|
SimulatorTransportParams,
|
|
7
|
+
SimulatorTestContact,
|
|
7
8
|
} from './ConversationsWorkspace'
|
|
8
9
|
export { ConversationPane } from './ConversationPane'
|
|
9
10
|
export type { ConversationPaneProps } from './ConversationPane'
|
package/src/workspace/labels.ts
CHANGED
|
@@ -16,6 +16,7 @@ export interface ConversationsWorkspaceLabels {
|
|
|
16
16
|
readonly selectAll: string
|
|
17
17
|
readonly emptyList: string
|
|
18
18
|
readonly emptyDetail: string
|
|
19
|
+
readonly newTestContact: string
|
|
19
20
|
readonly bulkSelected: (count: number) => string
|
|
20
21
|
readonly bulkClear: string
|
|
21
22
|
readonly bulkFinalize: string
|
|
@@ -67,6 +68,7 @@ export const DEFAULT_CONVERSATIONS_WORKSPACE_LABELS: ConversationsWorkspaceLabel
|
|
|
67
68
|
selectAll: 'Selecionar todas',
|
|
68
69
|
emptyList: 'Nenhuma conversa encontrada.',
|
|
69
70
|
emptyDetail: 'Selecione uma conversa.',
|
|
71
|
+
newTestContact: 'Novo contato de teste',
|
|
70
72
|
bulkSelected: (count) => `${count} selecionada${count === 1 ? '' : 's'}`,
|
|
71
73
|
bulkClear: 'Limpar seleção',
|
|
72
74
|
bulkFinalize: 'Finalizar',
|