@adatechnology/meta-whatsapp-module 0.8.1 → 0.9.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 +137 -0
- package/dist/index.cjs +341 -162
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +77 -23
- package/dist/index.d.ts +77 -23
- package/dist/index.js +304 -127
- package/dist/index.js.map +1 -1
- package/dist/migrations-journal/0000_freezing_switch.sql +41 -0
- package/dist/migrations-journal/0001_military_leper_queen.sql +15 -0
- package/dist/migrations-journal/0002_illegal_black_tarantula.sql +5 -0
- package/dist/migrations-journal/0003_normal_viper.sql +10 -0
- package/dist/migrations-journal/0004_widen_message_type.sql +1 -0
- package/dist/migrations-journal/0005_message_moderation.sql +3 -0
- package/dist/migrations-journal/0006_conversation_documents.sql +19 -0
- package/dist/migrations-journal/0007_flow_media.sql +18 -0
- package/dist/migrations-journal/0008_message_transcription.sql +5 -0
- package/dist/migrations-journal/0009_settings_transcription_policy.sql +2 -0
- package/dist/migrations-journal/0010_flow_media_meta_ids.sql +10 -0
- package/dist/migrations-journal/meta/_journal.json +83 -0
- package/package.json +2 -2
package/README.md
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# @adatechnology/meta-whatsapp-module
|
|
2
|
+
|
|
3
|
+
Módulo de conversa sobre WhatsApp Cloud API: schema e migrations próprios (`meta_whatsapp`),
|
|
4
|
+
repositórios, use cases (envio, transcript, atendimento humano, fluxos) e webhook — tudo atrás de
|
|
5
|
+
portas que o host injeta. Tipos e portas vivem em `@adatechnology/meta-whatsapp-contracts`.
|
|
6
|
+
|
|
7
|
+
O módulo não lê `process.env` nem abre conexão: `db`, credenciais, storage, cache e fila chegam por
|
|
8
|
+
parâmetro.
|
|
9
|
+
|
|
10
|
+
## Instalação
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
bun add @adatechnology/meta-whatsapp-module @adatechnology/meta-whatsapp-contracts drizzle-orm
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
`drizzle-orm` é peer dependency (`>=0.36 <2`): o módulo usa a conexão do host.
|
|
17
|
+
|
|
18
|
+
## Migrations
|
|
19
|
+
|
|
20
|
+
O pacote publica as mesmas migrations em dois formatos, porque os migrators do drizzle-orm não se
|
|
21
|
+
entendem:
|
|
22
|
+
|
|
23
|
+
| Formato | Pasta | Migrator |
|
|
24
|
+
|---|---|---|
|
|
25
|
+
| `v1` (padrão) | `dist/migrations/<timestamp>_<nome>/migration.sql` | drizzle-orm 1.x |
|
|
26
|
+
| `journal` | `dist/migrations-journal/` (`meta/_journal.json` + `NNNN_<nome>.sql`) | drizzle-orm 0.36–0.45 |
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { migrate } from 'drizzle-orm/postgres-js/migrator' // ou node-postgres, bun-sql…
|
|
30
|
+
import { runMetaWhatsAppMigrations } from '@adatechnology/meta-whatsapp-module'
|
|
31
|
+
|
|
32
|
+
await runMetaWhatsAppMigrations({ db, migrate, layout: 'journal' }) // drizzle-orm 0.x
|
|
33
|
+
await runMetaWhatsAppMigrations({ db, migrate }) // drizzle-orm 1.x (padrão)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Sem `layout`, o módulo tenta `v1` e cai para `journal` quando o migrator 0.x recusa a pasta (a recusa
|
|
37
|
+
acontece antes de qualquer SQL). O journal fica em `drizzle.meta_whatsapp_migrations`, separado do
|
|
38
|
+
journal do host. **Só se sobe: 0.x → 1.x, nunca de volta.** Os dois migrators gravam na mesma tabela
|
|
39
|
+
com critérios diferentes, e voltar ao 0.x depois de rodar com 1.x pode reaplicar migration já
|
|
40
|
+
aplicada. Para chamar o migrator por conta própria:
|
|
41
|
+
`metaWhatsAppMigrationsFolder({ layout: 'journal' })` + `META_WHATSAPP_MIGRATIONS_TABLE`.
|
|
42
|
+
|
|
43
|
+
Nos dois formatos o SQL é idêntico, e o `when` do journal é o timestamp do nome da pasta v1 — o mesmo
|
|
44
|
+
`created_at` que o migrator 1.x grava. Depois de `db:generate`, rode
|
|
45
|
+
`bun scripts/generate-journal-migrations.ts`; o `migrations.test.ts` reprova divergência.
|
|
46
|
+
|
|
47
|
+
## Montando o módulo
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { createMetaWhatsAppModule } from '@adatechnology/meta-whatsapp-module'
|
|
51
|
+
|
|
52
|
+
const whatsapp = createMetaWhatsAppModule({
|
|
53
|
+
db,
|
|
54
|
+
config: { phoneNumberId, accessToken, webhookVerifyToken, appSecret },
|
|
55
|
+
nonceStore, // anti-replay do webhook (Redis, Postgres…)
|
|
56
|
+
providers: { objectStorage, realtime, inboundQueue },
|
|
57
|
+
hooks: { onMessageReceived, onConversationModeChanged },
|
|
58
|
+
})
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
As conversas automáticas são grafos de fluxo editados no editor do `@adatechnology/conversations-ui`
|
|
62
|
+
e interpretados por `whatsapp.flows` (`FlowInterpreter`); ações do produto entram por
|
|
63
|
+
`whatsapp.flows.registerFlowAction`. O simulador de conversa do mesmo pacote
|
|
64
|
+
(`ConversationSimulatorPanel` + `createPreviewBridgeClient`) entrega pelo webhook real, assinado no
|
|
65
|
+
servidor.
|
|
66
|
+
|
|
67
|
+
Sem Redis: ver [`docs/postgres-only.md`](./docs/postgres-only.md) (nonce store e fila em tabela).
|
|
68
|
+
Durabilidade do webhook: [`docs/webhook-durability.md`](./docs/webhook-durability.md).
|
|
69
|
+
|
|
70
|
+
## Mensagens interativas
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
await whatsapp.conversations.send.sendInteractive({
|
|
74
|
+
companyId,
|
|
75
|
+
whatsappNumber,
|
|
76
|
+
sender: 'bot',
|
|
77
|
+
startState: 'start',
|
|
78
|
+
interactive: {
|
|
79
|
+
kind: 'list',
|
|
80
|
+
body: 'Qual horário?',
|
|
81
|
+
buttonLabel: 'Ver horários',
|
|
82
|
+
sections: [
|
|
83
|
+
{ title: 'Manhã', rows: [{ id: 'morning_9', title: '09:00', description: 'Unidade centro' }] },
|
|
84
|
+
{ title: 'Tarde', rows: [{ id: 'afternoon_14', title: '14:00' }] },
|
|
85
|
+
],
|
|
86
|
+
},
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
await whatsapp.conversations.send.sendInteractive({
|
|
90
|
+
companyId,
|
|
91
|
+
whatsappNumber,
|
|
92
|
+
sender: 'agent',
|
|
93
|
+
agentUserId,
|
|
94
|
+
startState: 'start',
|
|
95
|
+
interactive: { kind: 'buttons', body: 'Confirma?', buttons: [{ id: 'confirm', title: '✅ Confirmar' }] },
|
|
96
|
+
})
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Mesmo caminho do `sendText`: janela de 24h (`WindowExpiredError`), envio pelo canal e registro no
|
|
100
|
+
transcript (`type: 'interactive'`, `content` = corpo, `payload.interactive` = a mensagem com ids e
|
|
101
|
+
títulos), idempotente pelo `waMessageId`. Antes de tudo, os limites de `WHATSAPP_CHOICE_LIMIT` são
|
|
102
|
+
conferidos e a violação vira `InteractiveLimitExceededError` (422) com **todas** as violações em
|
|
103
|
+
`violations`:
|
|
104
|
+
|
|
105
|
+
| Campo | Limite |
|
|
106
|
+
|---|---|
|
|
107
|
+
| botões | 1 a 3, título ≤ 20 |
|
|
108
|
+
| linhas de lista | 1 a 10 no total, título ≤ 24, descrição ≤ 72 |
|
|
109
|
+
| seções | até 10; título ≤ 24, obrigatório com mais de uma |
|
|
110
|
+
| rótulo do botão da lista | ≤ 20 |
|
|
111
|
+
| corpo | ≤ 1024 |
|
|
112
|
+
| ids | únicos na mensagem |
|
|
113
|
+
|
|
114
|
+
Os caracteres são contados por code point (um emoji = 1). Para validar ao publicar um fluxo, use
|
|
115
|
+
`listInteractiveLimitViolations` dos contracts. Canal sem `sendInteractiveButtons` recebe os botões
|
|
116
|
+
como lista (`fallbackListLabel`, padrão `DEFAULT_FALLBACK_LIST_LABEL`).
|
|
117
|
+
|
|
118
|
+
## Atendimento humano e auditoria
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
await whatsapp.conversations.requestHuman.execute({ companyId, whatsappNumber }) // fila "aguardando"
|
|
122
|
+
await whatsapp.conversations.takeover.execute({ companyId, whatsappNumber, agentUserId }) // atendente assume
|
|
123
|
+
await whatsapp.conversations.release.execute({ companyId, whatsappNumber, actorId }) // volta ao bot
|
|
124
|
+
|
|
125
|
+
hooks: {
|
|
126
|
+
onConversationModeChanged: async (change) => {
|
|
127
|
+
// change: { companyId, whatsappNumber, kind: 'takeover' | 'release' | 'human-requested',
|
|
128
|
+
// mode, assignedUserId, actorId, occurredAt }
|
|
129
|
+
await auditTrail.record(change)
|
|
130
|
+
},
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
O hook roda depois de a mudança estar gravada; erro lançado nele sobe para quem chamou. `takeover`
|
|
135
|
+
aceita `actorId` quando quem executa não é o próprio atendente (padrão: `agentUserId`); em `release` e
|
|
136
|
+
`requestHuman`, `actorId` omitido é `null` (o sistema). `requestHuman` também dispara
|
|
137
|
+
`onHumanRequested`.
|