@synchat/webchat 0.0.19 → 0.0.20

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 CHANGED
@@ -1,3 +1,7 @@
1
+ <p align="center">
2
+ <img src="docs/synchat-logo.svg" alt="Synchat" width="280" />
3
+ </p>
4
+
1
5
  # @synchat/webchat
2
6
 
3
7
  Componente de chat para sites, integrado à plataforma **Synchat**. Exibe um botão flutuante que abre um painel com formulário (nome, e-mail, telefone, mensagem) ou mensagem de fora do horário de atendimento, conforme a configuração do canal no portal.
@@ -18,7 +22,7 @@ Para mais informações sobre a Synchat, acesse [synchat.com.br](https://synchat
18
22
 
19
23
  ---
20
24
 
21
- ## Criar um canal WebChat e obter o secret
25
+ ## Criar um canal WebChat e obter o token
22
26
 
23
27
  1. No **portal**, vá em **Canais** (ou **Configurações** → **Canais**).
24
28
  2. Clique em **Novo canal** e escolha **WebChat**.
@@ -29,9 +33,9 @@ Para mais informações sobre a Synchat, acesse [synchat.com.br](https://synchat
29
33
  - Horários de atendimento (dias úteis e fim de semana), se usar restrição
30
34
  - **Quando inativo, enviar para a fila** (opcional)
31
35
  4. Clique em **Criar canal WebChat**.
32
- 5. Após a criação, o portal exibe o **secret** do canal. **Copie e guarde** esse valor — ele será usado no componente no seu site.
36
+ 5. Após a criação, o portal exibe o **token** do canal. **Copie e guarde** esse valor — ele será usado no componente no seu site.
33
37
 
34
- O **secret** identifica o canal na API e no widget; não o compartilhe publicamente.
38
+ O **token** identifica o canal na API e no widget; não o compartilhe publicamente.
35
39
 
36
40
  ---
37
41
 
@@ -51,29 +55,40 @@ npm install react react-dom @mui/material @mui/icons-material @emotion/react @em
51
55
 
52
56
  ## Uso básico
53
57
 
54
- Importe o componente e informe o **secret** (obtido no portal) e a **URL base da API** da Synchat:
58
+ Importe o componente e informe o **token** (obtido no portal). A URL da API é opcional e tem valor padrão:
55
59
 
56
60
  ```tsx
57
61
  import { WebChat } from "@synchat/webchat";
58
62
 
59
63
  function App() {
60
64
  return (
61
- <WebChat
62
- secret="SEU_SECRET_DO_PORTAL"
63
- apiBaseUrl="https://api.synchat.com.br"
64
- />
65
+ <WebChat token="SEU_TOKEN_DO_PORTAL" />
65
66
  );
66
67
  }
67
68
  ```
68
69
 
69
- - **secret:** valor exibido ao criar o canal WebChat no portal.
70
- - **apiBaseUrl:** URL base da API (ex.: `https://api.synchat.com.br` em produção).
70
+ - **token:** valor exibido ao criar o canal WebChat no portal (obrigatório).
71
+ - **apiBaseUrl:** opcional. Se não informado, usa `https://api.synchat.com.br`. Só informe se sua API estiver em outra URL.
72
+ - **primaryColor:** opcional. Cor do botão flutuante e do bloco "fora do horário". Padrão: cor Synchat (`#0D9488`). Ex.: `primaryColor="#007bff"` para azul.
71
73
 
72
74
  O widget exibe um **botão flutuante** no canto inferior direito. Ao clicar:
73
75
 
74
76
  - Se o canal estiver **ativo** e **dentro do horário** (ou sem restrição): mostra o formulário (nome, e-mail, telefone, mensagem) e o botão **Iniciar chat**.
75
77
  - Se estiver **fora do horário** (com restrição configurada): mostra a mensagem de horário de atendimento.
76
- - Se o canal estiver inativo ou o secret for inválido: mostra mensagem de indisponibilidade.
78
+ - Se o canal estiver inativo ou o token for inválido: mostra mensagem de indisponibilidade.
79
+
80
+ ---
81
+
82
+ ## Mesmo WebSocket por negócio (businessId)
83
+
84
+ O WebSocket da Synchat é **único por negócio**: `/ws/business/{businessId}`. Tanto o portal quanto o widget do webchat conectam no mesmo endpoint usando o `businessId`.
85
+
86
+ A configuração do canal (retornada por `GET /channel/webchat/{token}`) inclui **businessId**. Assim, quem tem apenas o token do webchat pode:
87
+ 1. Chamar a API para obter a config (nome, status, horário, **businessId**).
88
+ 2. Conectar no mesmo WebSocket: `ws://.../ws/business/{businessId}`.
89
+ 3. Enviar/receber mensagens tipadas (ex.: `type: "webchat"` ou `type: "whatsapp"`) no mesmo canal.
90
+
91
+ O componente recebe a config (com `businessId`) após o fetch; em `onStartChat` você pode usar `config.businessId` para abrir a conexão WebSocket se estiver guardando a config no estado.
77
92
 
78
93
  ---
79
94
 
@@ -81,15 +96,16 @@ O widget exibe um **botão flutuante** no canto inferior direito. Ao clicar:
81
96
 
82
97
  O **início da conversa** não é feito por API; será feito via **WebSocket**. Por isso, o componente espera que você implemente o callback **onStartChat** e, nele, conecte ao WebSocket da Synchat e envie os dados do visitante.
83
98
 
84
- Exemplo de uso com **onStartChat**:
99
+ Exemplo de uso com **onStartChat** (conecte em `/ws/business/{businessId}` usando o `businessId` retornado na config):
85
100
 
86
101
  ```tsx
87
102
  <WebChat
88
- secret="SEU_SECRET_DO_PORTAL"
103
+ token="SEU_TOKEN_DO_PORTAL"
89
104
  apiBaseUrl="https://api.synchat.com.br"
90
105
  onStartChat={async (data) => {
91
- // Conectar ao WebSocket usando o secret e enviar
92
- // name, email, phone, message conforme documentação da API/WebSocket
106
+ // config.businessId está disponível após fetch da config
107
+ // Conectar ao WebSocket: wsBase/ws/business/${config.businessId}
108
+ // e enviar name, email, phone, message conforme documentação
93
109
  await minhaConexaoWebSocket.iniciarChat(data);
94
110
  }}
95
111
  />
@@ -103,37 +119,70 @@ Se **onStartChat** não for passado, o widget exibe uma mensagem orientando a co
103
119
 
104
120
  | Prop | Tipo | Obrigatório | Descrição |
105
121
  |-----------------|----------|-------------|-----------|
106
- | **secret** | `string` | Sim | Secret do canal WebChat (portal → Canais → criar WebChat → copiar secret). |
107
- | **apiBaseUrl** | `string` | Sim | URL base da API (ex.: `https://api.synchat.com.br`). |
108
- | **onStartChat** | `(data) => void \| Promise<void>` | Não | Callback ao clicar em "Iniciar chat". Recebe `{ name, email, phone, message }`. Implemente aqui a conexão WebSocket. |
122
+ | **token** | `string` | Sim | Token do canal WebChat (portal → Canais → criar WebChat → copiar token). |
123
+ | **apiBaseUrl** | `string` | Não | URL base da API. Padrão: `https://api.synchat.com.br`. Só informe se a API estiver em outra URL. |
124
+ | **primaryColor**| `string` | Não | Cor do botão flutuante e do bloco "fora do horário". Padrão: cor Synchat (`#0D9488`). Aceita hex (ex.: `#007bff`) ou valor CSS. |
125
+ | **onStartChat** | `(data) => void \| Promise<void>` | Não | Callback ao clicar em "Iniciar chat". Recebe `{ name, email, phone, message, businessId? }`. Implemente aqui a conexão WebSocket. |
109
126
  | **outOfHoursMessage** | `string` | Não | Mensagem customizada quando estiver fora do horário. Se não informado, usa o texto padrão com o horário configurado no canal. |
110
127
 
111
128
  ---
112
129
 
130
+ ## Estrutura do código (Atomic Design)
131
+
132
+ O WebChat segue **Atomic Design**: átomos → moléculas → organismos → templates → páginas. O componente principal exportado é a página (`WebChat`). Para customização avançada, o pacote também exporta partes reutilizáveis (`FabTrigger`, `ChatPanel`, `WebChatLayout`, etc.). Detalhes em [docs/ATOMIC-DESIGN.md](docs/ATOMIC-DESIGN.md).
133
+
134
+ ---
135
+
113
136
  ## Variáveis de ambiente (sugestão)
114
137
 
115
- Em produção, evite deixar o secret no código. Use variáveis de ambiente:
138
+ Em produção, evite deixar o token no código. Use variáveis de ambiente:
116
139
 
117
140
  ```env
118
- VITE_WEBCHAT_SECRET=seu_secret_aqui
119
- VITE_SYNCHAT_API_URL=https://api.synchat.com.br
141
+ VITE_WEBCHAT_TOKEN=seu_token_aqui
142
+ ```
143
+
144
+ ```tsx
145
+ <WebChat
146
+ token={import.meta.env.VITE_WEBCHAT_TOKEN ?? ""}
147
+ onStartChat={handleStartChat}
148
+ />
120
149
  ```
121
150
 
151
+ Se a API estiver em outra URL, passe `apiBaseUrl`. Para customizar a cor do botão:
152
+
122
153
  ```tsx
123
154
  <WebChat
124
- secret={import.meta.env.VITE_WEBCHAT_SECRET ?? ""}
125
- apiBaseUrl={import.meta.env.VITE_SYNCHAT_API_URL ?? "https://api.synchat.com.br"}
155
+ token="..."
156
+ primaryColor="#007bff"
126
157
  onStartChat={handleStartChat}
127
158
  />
128
159
  ```
129
160
 
130
161
  ---
131
162
 
163
+ ## Pacote com URL da API fixa
164
+
165
+ Se você **distribuir um build** do widget com a URL da API já embutida (para o cliente não precisar informar `apiBaseUrl`), faça o build do pacote com a variável de ambiente **SYNCHAT_API_URL**:
166
+
167
+ ```bash
168
+ SYNCHAT_API_URL=https://api.synchat.com.br npm run build
169
+ ```
170
+
171
+ Ou, para um ambiente próprio:
172
+
173
+ ```bash
174
+ SYNCHAT_API_URL=https://api.empresa.com/synchat npm run build
175
+ ```
176
+
177
+ O valor é injetado no código no momento do build. O cliente que instalar esse pacote (ou usar o bundle gerado) não precisa passar `apiBaseUrl` — o padrão será a URL que você definiu no build.
178
+
179
+ ---
180
+
132
181
  ## Resumo do fluxo
133
182
 
134
183
  1. **Cadastro:** [portal.synchat.com.br](https://portal.synchat.com.br) → Cadastre-se.
135
- 2. **Canal WebChat:** Portal → Canais → Novo canal → WebChat → preencher → Criar → **copiar o secret**.
136
- 3. **No site:** `npm install @synchat/webchat` e usar `<WebChat secret="..." apiBaseUrl="..." />`.
184
+ 2. **Canal WebChat:** Portal → Canais → Novo canal → WebChat → preencher → Criar → **copiar o token**.
185
+ 3. **No site:** `npm install @synchat/webchat` e usar `<WebChat token="..." />` (ou informar `apiBaseUrl` e `primaryColor` se quiser).
137
186
  4. **Conversa:** Implementar **onStartChat** para conectar ao WebSocket e enviar a primeira mensagem quando o recurso estiver disponível.
138
187
 
139
188
  ---
package/dist/index.d.mts CHANGED
@@ -24,6 +24,8 @@ interface WebChatSchedule {
24
24
  weekendEnd?: string;
25
25
  }
26
26
  interface WebChatConfig {
27
+ /** Business ID; use it to connect to the same WebSocket as the portal: ws://.../ws/business/{businessId} */
28
+ businessId: string;
27
29
  name: string;
28
30
  status: string;
29
31
  restrictBySchedule?: boolean;
@@ -31,16 +33,26 @@ interface WebChatConfig {
31
33
  sendToQueueWhenInactive?: boolean;
32
34
  }
33
35
  interface WebChatProps {
34
- /** Channel secret (from portal when creating webchat channel). */
35
- secret: string;
36
- /** Base URL of the Synchat API (e.g. https://api.synchat.com.br). */
37
- apiBaseUrl: string;
38
- /** Called when user clicks "Iniciar chat". The app should connect via WebSocket and send the message (conversation start is not via API). */
36
+ /** Channel token (from portal when creating webchat channel). */
37
+ token: string;
38
+ /**
39
+ * Base URL of the Synchat API.
40
+ * Opcional: se não informado, usa o padrão (https://api.synchat.com.br).
41
+ * Em builds do pacote, a URL padrão pode ser fixada via SYNCHAT_API_URL (veja README).
42
+ */
43
+ apiBaseUrl?: string;
44
+ /**
45
+ * Cor principal do botão flutuante e do bloco "fora do horário" (ex.: "#0D9488").
46
+ * Se não informado, usa a cor padrão da Synchat.
47
+ */
48
+ primaryColor?: string;
49
+ /** Called when user clicks "Iniciar chat". The app should connect via WebSocket and send the message. businessId is provided so you can connect to /ws/business/{businessId}. */
39
50
  onStartChat?: (data: {
40
51
  name: string;
41
52
  email: string;
42
53
  phone: string;
43
54
  message: string;
55
+ businessId?: string;
44
56
  }) => void | Promise<void>;
45
57
  /** Optional: custom out-of-hours message. If not set, uses schedule from config. */
46
58
  outOfHoursMessage?: string;
@@ -52,6 +64,6 @@ interface WebChatFormData {
52
64
  message: string;
53
65
  }
54
66
 
55
- declare const WebChat: React__default.FC<WebChatProps>;
67
+ declare const WebChatPage: React__default.FC<WebChatProps>;
56
68
 
57
- export { ChatButton, type ChatButtonProps, WebChat, type WebChatConfig, type WebChatFormData, type WebChatProps };
69
+ export { ChatButton, type ChatButtonProps, WebChatPage as WebChat, type WebChatConfig, type WebChatFormData, type WebChatProps };
package/dist/index.d.ts CHANGED
@@ -24,6 +24,8 @@ interface WebChatSchedule {
24
24
  weekendEnd?: string;
25
25
  }
26
26
  interface WebChatConfig {
27
+ /** Business ID; use it to connect to the same WebSocket as the portal: ws://.../ws/business/{businessId} */
28
+ businessId: string;
27
29
  name: string;
28
30
  status: string;
29
31
  restrictBySchedule?: boolean;
@@ -31,16 +33,26 @@ interface WebChatConfig {
31
33
  sendToQueueWhenInactive?: boolean;
32
34
  }
33
35
  interface WebChatProps {
34
- /** Channel secret (from portal when creating webchat channel). */
35
- secret: string;
36
- /** Base URL of the Synchat API (e.g. https://api.synchat.com.br). */
37
- apiBaseUrl: string;
38
- /** Called when user clicks "Iniciar chat". The app should connect via WebSocket and send the message (conversation start is not via API). */
36
+ /** Channel token (from portal when creating webchat channel). */
37
+ token: string;
38
+ /**
39
+ * Base URL of the Synchat API.
40
+ * Opcional: se não informado, usa o padrão (https://api.synchat.com.br).
41
+ * Em builds do pacote, a URL padrão pode ser fixada via SYNCHAT_API_URL (veja README).
42
+ */
43
+ apiBaseUrl?: string;
44
+ /**
45
+ * Cor principal do botão flutuante e do bloco "fora do horário" (ex.: "#0D9488").
46
+ * Se não informado, usa a cor padrão da Synchat.
47
+ */
48
+ primaryColor?: string;
49
+ /** Called when user clicks "Iniciar chat". The app should connect via WebSocket and send the message. businessId is provided so you can connect to /ws/business/{businessId}. */
39
50
  onStartChat?: (data: {
40
51
  name: string;
41
52
  email: string;
42
53
  phone: string;
43
54
  message: string;
55
+ businessId?: string;
44
56
  }) => void | Promise<void>;
45
57
  /** Optional: custom out-of-hours message. If not set, uses schedule from config. */
46
58
  outOfHoursMessage?: string;
@@ -52,6 +64,6 @@ interface WebChatFormData {
52
64
  message: string;
53
65
  }
54
66
 
55
- declare const WebChat: React__default.FC<WebChatProps>;
67
+ declare const WebChatPage: React__default.FC<WebChatProps>;
56
68
 
57
- export { ChatButton, type ChatButtonProps, WebChat, type WebChatConfig, type WebChatFormData, type WebChatProps };
69
+ export { ChatButton, type ChatButtonProps, WebChatPage as WebChat, type WebChatConfig, type WebChatFormData, type WebChatProps };