@adatechnology/conversations-ui 0.15.0 → 0.16.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.
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Copyright (c) 2026 Ada Technology. MIT License.
3
+ */
4
+
5
+ import { describe, expect, it } from 'bun:test'
6
+ import { WHATSAPP_CHOICE_LIMIT } from '@adatechnology/meta-whatsapp-contracts'
7
+ import {
8
+ countCharacters,
9
+ rendersAsButtons,
10
+ targetsOf,
11
+ validateGraph,
12
+ WHATSAPP_LIMITS,
13
+ type FlowGraphData,
14
+ } from './flowGraph'
15
+ import { applyConnection, clearConnection } from './flowEditorOps'
16
+ import { DEFAULT_FLOW_EDITOR_LABELS, mergeFlowEditorLabels } from './labels'
17
+
18
+ describe('editor limits come from the contract', () => {
19
+ it('mirrors WHATSAPP_CHOICE_LIMIT', () => {
20
+ expect(WHATSAPP_LIMITS.MAX_BUTTONS).toBe(WHATSAPP_CHOICE_LIMIT.BUTTONS)
21
+ expect(WHATSAPP_LIMITS.LIST_ROW_DESCRIPTION_MAX).toBe(WHATSAPP_CHOICE_LIMIT.LIST_ROW_DESCRIPTION_LENGTH)
22
+ })
23
+
24
+ it('counts an emoji as one character, like the contract', () => {
25
+ expect(countCharacters('🙋 Atendente')).toBe(11)
26
+ })
27
+
28
+ it('renders a list when an option has a description or section', () => {
29
+ const options: [string, string][] = [['a', 'A']]
30
+ expect(rendersAsButtons(options)).toBe(true)
31
+ expect(rendersAsButtons(options, { a: { description: 'detalhe' } })).toBe(false)
32
+ })
33
+ })
34
+
35
+ describe('keyword routes in the editor', () => {
36
+ const node = {
37
+ id: 'menu',
38
+ type: 'menu' as const,
39
+ options: [['a', 'A']] as [string, string][],
40
+ next: { byAnswer: { a: 'x' }, byKeyword: { horario: 'hours' }, default: 'menu' },
41
+ }
42
+
43
+ it('lists keyword targets', () => {
44
+ expect(targetsOf(node)).toContainEqual({ target: 'hours', keyword: 'horario' })
45
+ })
46
+
47
+ it('keeps keyword routes when connecting an option and edits them through kw: handles', () => {
48
+ const connected = applyConnection(node, { flowKey: 'main', nodeId: 'menu', handle: 'a', targetValue: 'y' })
49
+ expect(connected.next).toMatchObject({ byKeyword: { horario: 'hours' }, byAnswer: { a: 'y' } })
50
+ const rerouted = applyConnection(node, { flowKey: 'main', nodeId: 'menu', handle: 'kw:horario', targetValue: 'z' })
51
+ expect(rerouted.next).toMatchObject({ byKeyword: { horario: 'z' }, byAnswer: { a: 'x' } })
52
+ expect(clearConnection(node, 'kw:horario').next).toMatchObject({ byKeyword: { horario: '' } })
53
+ })
54
+ })
55
+
56
+ describe('validateGraph — runner fields', () => {
57
+ it('flags long descriptions and dynamic choices without provider', () => {
58
+ const graph: FlowGraphData = {
59
+ key: 'main',
60
+ label: 'main',
61
+ startNodeId: 'menu',
62
+ version: 1,
63
+ nodes: {
64
+ menu: {
65
+ id: 'menu',
66
+ type: 'menu',
67
+ options: [['a', 'A']],
68
+ optionDetails: { a: { description: 'x'.repeat(73) } },
69
+ next: { byAnswer: { a: 'slot' }, default: 'menu' },
70
+ },
71
+ slot: { id: 'slot', type: 'dynamic_choice' },
72
+ },
73
+ }
74
+ const messages = validateGraph(graph, DEFAULT_FLOW_EDITOR_LABELS.validation).map((issue) => issue.message)
75
+ expect(messages).toContain('Nó "menu": a descrição de "A" passa de 72 caracteres.')
76
+ expect(messages).toContain('Nó "slot": escolha dinâmica sem provedor de opções.')
77
+ })
78
+ })
79
+
80
+ describe('validateGraph — unmatched choice', () => {
81
+ const base = (unmatchedChoice?: 'reask' | 'default'): FlowGraphData => ({
82
+ key: 'main',
83
+ label: 'main',
84
+ startNodeId: 'menu',
85
+ version: 1,
86
+ nodes: {
87
+ menu: {
88
+ id: 'menu',
89
+ type: 'menu',
90
+ options: [['a', 'A']],
91
+ ...(unmatchedChoice ? { unmatchedChoice } : {}),
92
+ next: { byAnswer: { a: 'other' }, default: 'other' },
93
+ },
94
+ other: { id: 'other', type: 'action' },
95
+ },
96
+ })
97
+
98
+ it('warns when a choice default would be ignored by the runner', () => {
99
+ const issues = validateGraph(base(), DEFAULT_FLOW_EDITOR_LABELS.validation)
100
+ expect(issues.some((issue) => issue.severity === 'warning' && issue.message.includes('Caso contrário'))).toBe(true)
101
+ })
102
+
103
+ it('does not warn when the node follows default', () => {
104
+ const issues = validateGraph(base('default'), DEFAULT_FLOW_EDITOR_LABELS.validation)
105
+ expect(issues.some((issue) => issue.message.includes('Caso contrário'))).toBe(false)
106
+ })
107
+ })
108
+
109
+ describe('labels — hosts that build the legend by hand', () => {
110
+ it('accepts a legend without dynamic_choice and merges the default', () => {
111
+ const legend = { question: 'Q', entrada_choice: 'E', action: 'A', menu: 'M', condition: 'C' }
112
+ const merged = mergeFlowEditorLabels({ legend })
113
+ expect(merged.legend.dynamic_choice).toBe(DEFAULT_FLOW_EDITOR_LABELS.legend.dynamic_choice)
114
+ expect(merged.legend.menu).toBe('M')
115
+ })
116
+ })
@@ -1,7 +1,47 @@
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
+ minValue: string
13
+ maxValue: string
14
+ minLength: string
15
+ maxLength: string
16
+ skipKeywords: string
17
+ skipKeywordsHint: string
18
+ keywordRoutes: string
19
+ keywordRoutesHint: string
20
+ addKeywordRoute: string
21
+ removeKeywordRoute: string
22
+ keywordPlaceholder: string
23
+ optionDescription: string
24
+ optionSection: string
25
+ listButtonLabel: string
26
+ unmatchedChoice: string
27
+ unmatchedChoiceReask: string
28
+ unmatchedChoiceDefault: string
29
+ choiceProvider: string
30
+ choiceProviderHint: string
31
+ contextKey: string
32
+ placeholdersHint: string
33
+ paletteDynamicChoice: string
34
+ paletteDynamicChoiceHint: string
35
+ paletteMessage: string
36
+ paletteMessageHint: string
37
+ }
38
+
3
39
  export interface FlowEditorLabels {
4
- legend: Record<FlowNodeType, string>
40
+ /**
41
+ * `dynamic_choice` é opcional para não quebrar quem já monta a legenda inteira à mão; ausente, vale
42
+ * o texto padrão.
43
+ */
44
+ legend: Record<Exclude<FlowNodeType, 'dynamic_choice'>, string> & { dynamic_choice?: string }
5
45
  startNodeTooltip: string
6
46
  detachedNodeTooltip: string
7
47
  liveCountTooltip: (count: number) => string
@@ -11,6 +51,8 @@ export interface FlowEditorLabels {
11
51
  actionKindLabels: Record<string, string>
12
52
  conditionOperatorLabels: Record<FlowConditionOperator, string>
13
53
  questionTypeLabels: Record<FlowQuestionType, string>
54
+ /** Opcional para não quebrar quem monta os textos à mão; ausente, vale o padrão pt-BR. */
55
+ runnerFields?: FlowRunnerFieldLabels
14
56
  nodePanel: {
15
57
  title: string
16
58
  contextKey: string
@@ -158,6 +200,44 @@ export interface FlowValidationLabels {
158
200
  deadEndQuestion: (id: string) => string
159
201
  conditionIncomplete: (id: string) => string
160
202
  conditionBranchMissing: (id: string, branch: string) => string
203
+ descriptionTooLong?: (id: string, label: string) => string
204
+ dynamicChoiceWithoutProvider?: (id: string) => string
205
+ choiceDefaultIgnored?: (id: string) => string
206
+ }
207
+
208
+ export const DEFAULT_FLOW_RUNNER_FIELD_LABELS: FlowRunnerFieldLabels = {
209
+ section: 'Resposta do cliente',
210
+ fallbackMessage: 'Mensagem quando a resposta não serve',
211
+ fallbackPlaceholder: 'Ex.: Não entendi. Escolha uma das opções.',
212
+ maxInvalidAnswers: 'Tentativas antes de chamar uma pessoa',
213
+ maxInvalidAnswersHint: 'Vazio = padrão do bot (2).',
214
+ minDateToday: 'Só aceitar de hoje em diante',
215
+ afterContextKey: 'Depois da data guardada em',
216
+ minValue: 'Mínimo',
217
+ maxValue: 'Máximo',
218
+ minLength: 'Mínimo de caracteres',
219
+ maxLength: 'Máximo de caracteres',
220
+ skipKeywords: 'Palavras que pulam a pergunta',
221
+ skipKeywordsHint: 'Separadas por vírgula. Ex.: pular, não sei',
222
+ keywordRoutes: 'Palavras-chave (texto livre)',
223
+ keywordRoutesHint: 'Se a mensagem contiver a palavra, segue para o destino — sem acento e sem maiúscula.',
224
+ addKeywordRoute: 'Adicionar palavra-chave',
225
+ removeKeywordRoute: 'Remover palavra-chave',
226
+ keywordPlaceholder: 'horário',
227
+ optionDescription: 'Descrição (lista)',
228
+ optionSection: 'Seção',
229
+ listButtonLabel: 'Texto do botão da lista',
230
+ unmatchedChoice: 'Resposta fora das opções',
231
+ unmatchedChoiceReask: 'Perguntar de novo (padrão)',
232
+ unmatchedChoiceDefault: 'Seguir o "Caso contrário"',
233
+ choiceProvider: 'Provedor de opções',
234
+ choiceProviderHint: 'Chave registrada pelo sistema (registerDynamicChoiceProvider).',
235
+ contextKey: 'Guardar a escolha em',
236
+ placeholdersHint: 'Use {{chave}} para inserir respostas anteriores, ex.: {{contactFirstName}}.',
237
+ paletteDynamicChoice: 'Escolha dinâmica',
238
+ paletteDynamicChoiceHint: 'Opções calculadas na hora pelo sistema, com "ver mais"',
239
+ paletteMessage: 'Mensagem',
240
+ paletteMessageHint: 'Envia um texto e segue para o próximo passo',
161
241
  }
162
242
 
163
243
  // Paridade de texto com financiamento-imobiliario-bot/apps/web/src/locales/modules/flows.ts —
@@ -169,6 +249,7 @@ export const DEFAULT_FLOW_EDITOR_LABELS: FlowEditorLabels = {
169
249
  action: 'Ação (simulação/atendimento)',
170
250
  menu: 'Menu',
171
251
  condition: 'Condição',
252
+ dynamic_choice: 'Escolha dinâmica',
172
253
  },
173
254
  startNodeTooltip: 'Início do fluxo',
174
255
  detachedNodeTooltip: 'Sem ligação de entrada — o bot não chega neste nó. Puxe um fio de outro card até ele.',
@@ -197,6 +278,7 @@ export const DEFAULT_FLOW_EDITOR_LABELS: FlowEditorLabels = {
197
278
  cpf: 'CPF',
198
279
  choice: 'Escolha (botões/lista)',
199
280
  },
281
+ runnerFields: DEFAULT_FLOW_RUNNER_FIELD_LABELS,
200
282
  nodePanel: {
201
283
  title: 'Editar nó',
202
284
  contextKey: 'Chave (contexto)',
@@ -304,6 +386,10 @@ export const DEFAULT_FLOW_EDITOR_LABELS: FlowEditorLabels = {
304
386
  conditionIncomplete: (id) => `Nó "${id}": condição incompleta — defina variável, operador e valor.`,
305
387
  conditionBranchMissing: (id, branch) =>
306
388
  `Nó "${id}": ramo "${branch === 'true' ? 'Verdadeiro' : 'Falso'}" sem destino definido.`,
389
+ descriptionTooLong: (id, label) => `Nó "${id}": a descrição de "${label}" passa de 72 caracteres.`,
390
+ dynamicChoiceWithoutProvider: (id) => `Nó "${id}": escolha dinâmica sem provedor de opções.`,
391
+ choiceDefaultIgnored: (id) =>
392
+ `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
393
  },
308
394
  workspace: {
309
395
  title: 'Fluxos do Bot',
@@ -352,6 +438,7 @@ export function mergeFlowEditorLabels(override?: Partial<FlowEditorLabels>): Flo
352
438
  ...override.conditionOperatorLabels,
353
439
  },
354
440
  questionTypeLabels: { ...DEFAULT_FLOW_EDITOR_LABELS.questionTypeLabels, ...override.questionTypeLabels },
441
+ runnerFields: { ...DEFAULT_FLOW_RUNNER_FIELD_LABELS, ...override.runnerFields },
355
442
  nodePanel: { ...DEFAULT_FLOW_EDITOR_LABELS.nodePanel, ...override.nodePanel },
356
443
  quickAdd: { ...DEFAULT_FLOW_EDITOR_LABELS.quickAdd, ...override.quickAdd },
357
444
  legendPanel: { ...DEFAULT_FLOW_EDITOR_LABELS.legendPanel, ...override.legendPanel },
@@ -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, InteractiveReplyOption } from '@adatechnology/meta-whatsapp-contracts/testing'
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.