@fayz-ai/plugin-conversations 0.34.1 → 0.35.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/dist/{ConversationsPage-HULLLSJZ.js → ConversationsPage-AV34J5DY.js} +48 -18
- package/dist/ConversationsPage-AV34J5DY.js.map +1 -0
- package/dist/chunk-NWH5AIUH.js +322 -0
- package/dist/chunk-NWH5AIUH.js.map +1 -0
- package/dist/index.js +3 -223
- package/dist/index.js.map +1 -1
- package/dist/migrations/index.d.ts +1 -0
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/migrations/main.browser.js +2 -1
- package/dist/migrations/main.browser.js.map +1 -1
- package/dist/migrations/main.js +33 -2
- package/dist/migrations/main.js.map +1 -1
- package/dist/store.d.ts +1 -0
- package/dist/store.d.ts.map +1 -1
- package/dist/views/ConversationList.d.ts.map +1 -1
- package/package.json +3 -3
- package/dist/ConversationsPage-HULLLSJZ.js.map +0 -1
- package/dist/chunk-OJ3Q4S5Y.js +0 -102
- package/dist/chunk-OJ3Q4S5Y.js.map +0 -1
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import { createStore } from 'zustand/vanilla';
|
|
2
|
+
import { getSupabaseClientOptional, useTranslation, getActiveTenantId } from '@fayz-ai/core';
|
|
3
|
+
import React from 'react';
|
|
4
|
+
import { useStore } from 'zustand';
|
|
5
|
+
import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
|
|
6
|
+
import { CircleHelp, User, MapPin, Sticker, FileText, Video, Camera, Mic } from 'lucide-react';
|
|
7
|
+
|
|
8
|
+
// src/types.ts
|
|
9
|
+
var CHANNEL_LABELS = {
|
|
10
|
+
sms: "SMS",
|
|
11
|
+
whatsapp: "WhatsApp",
|
|
12
|
+
instagram: "Instagram",
|
|
13
|
+
email: "Email",
|
|
14
|
+
webchat: "Web Chat",
|
|
15
|
+
support: "Suporte"
|
|
16
|
+
};
|
|
17
|
+
function isWaitingOnUs(conversation) {
|
|
18
|
+
if (conversation.status !== "open") return false;
|
|
19
|
+
if (conversation.acknowledgedAt && conversation.lastMessageAt && conversation.acknowledgedAt >= conversation.lastMessageAt) return false;
|
|
20
|
+
if (conversation.lastMessageDirection) return conversation.lastMessageDirection === "inbound";
|
|
21
|
+
return conversation.unreadCount > 0;
|
|
22
|
+
}
|
|
23
|
+
var MEDIA_LIMIT_MB = { media: 16, document: 100 };
|
|
24
|
+
function toBase64(blob) {
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const reader = new FileReader();
|
|
27
|
+
reader.onload = () => resolve(String(reader.result ?? "").replace(/^data:[^;]*;base64,/u, ""));
|
|
28
|
+
reader.onerror = () => reject(reader.error ?? new Error("N\xE3o foi poss\xEDvel ler o arquivo"));
|
|
29
|
+
reader.readAsDataURL(blob);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
async function sendMedia(input) {
|
|
33
|
+
const client = getSupabaseClientOptional();
|
|
34
|
+
const tenantId = getActiveTenantId();
|
|
35
|
+
if (!client || !tenantId) throw new Error("Sem conex\xE3o com a casa");
|
|
36
|
+
const mimetype = input.file.type || "application/octet-stream";
|
|
37
|
+
const isDoc = !/^(image|video|audio)\//u.test(mimetype);
|
|
38
|
+
const limit = (isDoc ? MEDIA_LIMIT_MB.document : MEDIA_LIMIT_MB.media) * 1024 * 1024;
|
|
39
|
+
if (input.file.size > limit) throw new Error(`Arquivo maior que ${isDoc ? MEDIA_LIMIT_MB.document : MEDIA_LIMIT_MB.media} MB, o limite do WhatsApp`);
|
|
40
|
+
const data = await toBase64(input.file);
|
|
41
|
+
const { data: out, error } = await client.functions.invoke("conversations-provider", {
|
|
42
|
+
body: {
|
|
43
|
+
tenantId,
|
|
44
|
+
action: "send_media",
|
|
45
|
+
conversationId: input.conversationId,
|
|
46
|
+
data,
|
|
47
|
+
mimetype,
|
|
48
|
+
fileName: input.fileName ?? input.file.name ?? null,
|
|
49
|
+
caption: input.caption ?? "",
|
|
50
|
+
ptt: input.ptt === true
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
if (error) {
|
|
54
|
+
const detail = await error.context?.json?.().catch(() => null);
|
|
55
|
+
throw new Error(detail?.message ?? error.message);
|
|
56
|
+
}
|
|
57
|
+
if (out?.error) throw new Error(out.message ?? out.error);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/store.ts
|
|
61
|
+
async function currentUserId() {
|
|
62
|
+
try {
|
|
63
|
+
const sb = getSupabaseClientOptional();
|
|
64
|
+
const { data } = await sb?.auth?.getSession?.() ?? {};
|
|
65
|
+
return data?.session?.user?.id ?? null;
|
|
66
|
+
} catch {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function handleKey(h) {
|
|
71
|
+
const v = (h ?? "").trim();
|
|
72
|
+
if (!v) return "";
|
|
73
|
+
return /[@a-z]/i.test(v) ? v.toLowerCase() : v.replace(/\D/g, "");
|
|
74
|
+
}
|
|
75
|
+
function createConversationsStore(provider) {
|
|
76
|
+
return createStore((set, get) => ({
|
|
77
|
+
conversations: [],
|
|
78
|
+
messages: [],
|
|
79
|
+
selectedId: null,
|
|
80
|
+
channelFilter: "all",
|
|
81
|
+
leadOwnerFilter: void 0,
|
|
82
|
+
search: "",
|
|
83
|
+
loading: false,
|
|
84
|
+
sending: false,
|
|
85
|
+
async load(opts) {
|
|
86
|
+
set({ loading: true });
|
|
87
|
+
const conversations = await provider.listConversations({
|
|
88
|
+
channel: get().channelFilter,
|
|
89
|
+
leadOwnerId: get().leadOwnerFilter,
|
|
90
|
+
search: get().search || void 0
|
|
91
|
+
});
|
|
92
|
+
const selectedId = get().selectedId ?? (opts?.autoSelect === false ? null : (conversations.find((c) => c.status !== "closed") ?? conversations[0])?.id ?? null);
|
|
93
|
+
set({ conversations, loading: false, selectedId });
|
|
94
|
+
if (selectedId) await get().select(selectedId);
|
|
95
|
+
},
|
|
96
|
+
/** Dar por vista sem abrir — o caso do "ok, obrigado" que não pede resposta. */
|
|
97
|
+
async markRead(id) {
|
|
98
|
+
await provider.markRead(id);
|
|
99
|
+
const agora = (/* @__PURE__ */ new Date()).toISOString();
|
|
100
|
+
set((s) => ({
|
|
101
|
+
conversations: s.conversations.map((c) => c.id === id ? { ...c, unreadCount: 0, acknowledgedAt: agora } : c)
|
|
102
|
+
}));
|
|
103
|
+
},
|
|
104
|
+
async select(id) {
|
|
105
|
+
set({ selectedId: id });
|
|
106
|
+
const messages = await provider.getMessages(id);
|
|
107
|
+
set({ messages });
|
|
108
|
+
const owner = get().conversations.find((c) => c.id === id)?.leadOwnerId;
|
|
109
|
+
if (owner && owner !== await currentUserId()) return;
|
|
110
|
+
await provider.markRead(id);
|
|
111
|
+
const agora = (/* @__PURE__ */ new Date()).toISOString();
|
|
112
|
+
set((s) => ({
|
|
113
|
+
conversations: s.conversations.map((c) => c.id === id ? { ...c, unreadCount: 0, acknowledgedAt: agora } : c)
|
|
114
|
+
}));
|
|
115
|
+
},
|
|
116
|
+
/** Relê as mensagens da conversa aberta, sem tocar em mais nada.
|
|
117
|
+
*
|
|
118
|
+
* O status de uma mensagem de WhatsApp muda DEPOIS do envio — entregue,
|
|
119
|
+
* lida, às vezes minutos depois — e quem avisa é o webhook, que escreve no
|
|
120
|
+
* banco sem a tela saber. Sem isto a caixa mostra para sempre o status do
|
|
121
|
+
* instante do envio: um tique só, numa mensagem que já foi lida.
|
|
122
|
+
*
|
|
123
|
+
* Não usa `select()` de propósito: aquele marca a conversa como lida e
|
|
124
|
+
* zera o contador, e uma releitura de fundo não é um gesto de ninguém. */
|
|
125
|
+
async refreshMessages() {
|
|
126
|
+
const id = get().selectedId;
|
|
127
|
+
if (!id) return;
|
|
128
|
+
try {
|
|
129
|
+
const messages = await provider.getMessages(id);
|
|
130
|
+
const before = get().messages;
|
|
131
|
+
const same = before.length === messages.length && before.every((m, i) => m.id === messages[i].id && m.deliveryStatus === messages[i].deliveryStatus);
|
|
132
|
+
if (!same) set({ messages });
|
|
133
|
+
} catch {
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
deselect() {
|
|
137
|
+
set({ selectedId: null, messages: [] });
|
|
138
|
+
},
|
|
139
|
+
async setLeadOwnerFilter(ownerId) {
|
|
140
|
+
set({ leadOwnerFilter: ownerId });
|
|
141
|
+
await get().load();
|
|
142
|
+
},
|
|
143
|
+
async setChannelFilter(channel) {
|
|
144
|
+
set({ channelFilter: channel });
|
|
145
|
+
await get().load();
|
|
146
|
+
},
|
|
147
|
+
async setSearch(search) {
|
|
148
|
+
set({ search });
|
|
149
|
+
await get().load();
|
|
150
|
+
},
|
|
151
|
+
async create(input) {
|
|
152
|
+
const created = await provider.createConversation(input);
|
|
153
|
+
set((s) => ({
|
|
154
|
+
channelFilter: "all",
|
|
155
|
+
search: "",
|
|
156
|
+
conversations: [created, ...s.conversations.filter((c) => c.id !== created.id)],
|
|
157
|
+
selectedId: created.id
|
|
158
|
+
}));
|
|
159
|
+
void (async () => {
|
|
160
|
+
try {
|
|
161
|
+
const conversations = await provider.listConversations({});
|
|
162
|
+
const merged = conversations.some((c) => c.id === created.id) ? conversations : [created, ...conversations];
|
|
163
|
+
set({ conversations: merged });
|
|
164
|
+
await get().select(created.id);
|
|
165
|
+
} catch {
|
|
166
|
+
}
|
|
167
|
+
})();
|
|
168
|
+
return created;
|
|
169
|
+
},
|
|
170
|
+
// Chegar aqui vindo de fora — da ficha de um lead, por exemplo — não pode
|
|
171
|
+
// criar uma segunda thread com alguém com quem a casa já conversa. Procura
|
|
172
|
+
// primeiro pela PESSOA, e só então pelo telefone: o vínculo é a verdade, e
|
|
173
|
+
// o handle é o que resgata threads criadas antes de o vínculo existir.
|
|
174
|
+
async openForPerson({ personId, name, handle, channel }) {
|
|
175
|
+
if (get().conversations.length === 0 && !get().loading) {
|
|
176
|
+
try {
|
|
177
|
+
await get().load();
|
|
178
|
+
} catch {
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const key = handleKey(handle);
|
|
182
|
+
const existing = get().conversations.find((c) => c.channel === channel && (personId && c.contactPersonId === personId || key !== "" && handleKey(c.contactHandle) === key));
|
|
183
|
+
if (existing) {
|
|
184
|
+
set({ channelFilter: "all", search: "" });
|
|
185
|
+
await get().select(existing.id);
|
|
186
|
+
return existing;
|
|
187
|
+
}
|
|
188
|
+
return get().create({
|
|
189
|
+
contactName: name,
|
|
190
|
+
contactPersonId: personId,
|
|
191
|
+
contactHandle: handle,
|
|
192
|
+
channel
|
|
193
|
+
});
|
|
194
|
+
},
|
|
195
|
+
async sendMedia(input) {
|
|
196
|
+
const id = get().selectedId;
|
|
197
|
+
if (!id) return;
|
|
198
|
+
set({ sending: true });
|
|
199
|
+
try {
|
|
200
|
+
await sendMedia({ conversationId: id, ...input });
|
|
201
|
+
} finally {
|
|
202
|
+
set({ sending: false });
|
|
203
|
+
await get().refreshMessages();
|
|
204
|
+
}
|
|
205
|
+
},
|
|
206
|
+
async send(body) {
|
|
207
|
+
const id = get().selectedId;
|
|
208
|
+
if (!id || !body.trim()) return;
|
|
209
|
+
set({ sending: true });
|
|
210
|
+
const created = await provider.sendMessage({ conversationId: id, body: body.trim() });
|
|
211
|
+
set((s) => ({
|
|
212
|
+
sending: false,
|
|
213
|
+
messages: [...s.messages, created],
|
|
214
|
+
conversations: s.conversations.map(
|
|
215
|
+
(c) => (
|
|
216
|
+
// `lastMessageDirection` acompanha a prévia, senão a fila mente. O
|
|
217
|
+
// gatilho da migration 001 carimba a coluna no banco, mas a lista só
|
|
218
|
+
// volta a ler no próximo `load()` — e até lá a thread que ACABOU de
|
|
219
|
+
// ser respondida continua em "esperando nós", que é exatamente a
|
|
220
|
+
// pergunta que essa coluna existe para responder.
|
|
221
|
+
//
|
|
222
|
+
// Antes da 001 isto não aparecia: a coluna vinha sempre indefinida e
|
|
223
|
+
// `isWaitingOnUs` caía no `unreadCount`. A migration não criou o
|
|
224
|
+
// defeito, tornou-o visível.
|
|
225
|
+
c.id === id ? { ...c, lastMessagePreview: created.body, lastMessageAt: created.at, lastMessageDirection: "outbound" } : c
|
|
226
|
+
)
|
|
227
|
+
)
|
|
228
|
+
}));
|
|
229
|
+
},
|
|
230
|
+
async setStatus(status) {
|
|
231
|
+
const id = get().selectedId;
|
|
232
|
+
if (!id) return;
|
|
233
|
+
const updated = await provider.setStatus(id, status);
|
|
234
|
+
set((s) => ({
|
|
235
|
+
conversations: s.conversations.map((c) => c.id === id ? updated : c),
|
|
236
|
+
// An archived conversation leaves the inbox, so it stops being the open one.
|
|
237
|
+
...status === "closed" ? { selectedId: null } : {}
|
|
238
|
+
}));
|
|
239
|
+
}
|
|
240
|
+
}));
|
|
241
|
+
}
|
|
242
|
+
var DEFAULT_CONVERSATIONS_CONFIG = {
|
|
243
|
+
contactKind: "contact"
|
|
244
|
+
};
|
|
245
|
+
var StoreContext = React.createContext(null);
|
|
246
|
+
var ConfigContext = React.createContext(DEFAULT_CONVERSATIONS_CONFIG);
|
|
247
|
+
function ConversationsContextProvider({
|
|
248
|
+
store,
|
|
249
|
+
config = DEFAULT_CONVERSATIONS_CONFIG,
|
|
250
|
+
children
|
|
251
|
+
}) {
|
|
252
|
+
return /* @__PURE__ */ jsx(StoreContext.Provider, { value: store, children: /* @__PURE__ */ jsx(ConfigContext.Provider, { value: config, children }) });
|
|
253
|
+
}
|
|
254
|
+
function useConversationsStore(selector) {
|
|
255
|
+
const store = React.useContext(StoreContext);
|
|
256
|
+
if (!store) throw new Error("useConversationsStore must be used within ConversationsPage");
|
|
257
|
+
return useStore(store, selector);
|
|
258
|
+
}
|
|
259
|
+
function useConversationsConfig() {
|
|
260
|
+
return React.useContext(ConfigContext);
|
|
261
|
+
}
|
|
262
|
+
var porConta = /* @__PURE__ */ new Map();
|
|
263
|
+
function assinarChegada(tenantId, ouvinte) {
|
|
264
|
+
const supabase = getSupabaseClientOptional();
|
|
265
|
+
if (!supabase?.channel || !tenantId) return () => {
|
|
266
|
+
};
|
|
267
|
+
let assinatura = porConta.get(tenantId);
|
|
268
|
+
if (!assinatura) {
|
|
269
|
+
const ouvintes = /* @__PURE__ */ new Set();
|
|
270
|
+
const canal = supabase.channel(`conversas:${tenantId}`).on("broadcast", { event: "inbound" }, (msg) => {
|
|
271
|
+
const carga = { conversationId: msg?.payload?.conversationId };
|
|
272
|
+
for (const f of [...ouvintes]) {
|
|
273
|
+
try {
|
|
274
|
+
f(carga);
|
|
275
|
+
} catch {
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}).subscribe();
|
|
279
|
+
assinatura = { canal, ouvintes };
|
|
280
|
+
porConta.set(tenantId, assinatura);
|
|
281
|
+
}
|
|
282
|
+
assinatura.ouvintes.add(ouvinte);
|
|
283
|
+
return () => {
|
|
284
|
+
const a = porConta.get(tenantId);
|
|
285
|
+
if (!a) return;
|
|
286
|
+
a.ouvintes.delete(ouvinte);
|
|
287
|
+
if (a.ouvintes.size === 0) {
|
|
288
|
+
porConta.delete(tenantId);
|
|
289
|
+
void getSupabaseClientOptional()?.removeChannel?.(a.canal);
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
var KINDS = {
|
|
294
|
+
"[\xE1udio]": { icon: Mic, key: "conversations.preview.audio" },
|
|
295
|
+
"[imagem]": { icon: Camera, key: "conversations.preview.image" },
|
|
296
|
+
"[v\xEDdeo]": { icon: Video, key: "conversations.preview.video" },
|
|
297
|
+
"[documento]": { icon: FileText, key: "conversations.preview.document" },
|
|
298
|
+
"[figurinha]": { icon: Sticker, key: "conversations.preview.sticker" },
|
|
299
|
+
"[localiza\xE7\xE3o]": { icon: MapPin, key: "conversations.preview.location" },
|
|
300
|
+
"[contato]": { icon: User, key: "conversations.preview.contact" },
|
|
301
|
+
"[mensagem n\xE3o suportada]": { icon: CircleHelp, key: "conversations.preview.unsupported" }
|
|
302
|
+
};
|
|
303
|
+
function mediaPreviewKind(text) {
|
|
304
|
+
return KINDS[String(text ?? "").trim()] ?? null;
|
|
305
|
+
}
|
|
306
|
+
function MessagePreview({ text, suffix, className }) {
|
|
307
|
+
const t = useTranslation();
|
|
308
|
+
const kind = mediaPreviewKind(text);
|
|
309
|
+
if (!kind) return /* @__PURE__ */ jsx(Fragment, { children: text });
|
|
310
|
+
const Icon = kind.icon;
|
|
311
|
+
return /* @__PURE__ */ jsxs("span", { className: `inline-flex min-w-0 items-center gap-1 ${className ?? ""}`, children: [
|
|
312
|
+
/* @__PURE__ */ jsx(Icon, { className: "h-3.5 w-3.5 shrink-0" }),
|
|
313
|
+
/* @__PURE__ */ jsxs("span", { className: "truncate", children: [
|
|
314
|
+
t(kind.key),
|
|
315
|
+
suffix ? ` (${suffix})` : ""
|
|
316
|
+
] })
|
|
317
|
+
] });
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export { CHANNEL_LABELS, ConversationsContextProvider, MessagePreview, assinarChegada, createConversationsStore, currentUserId, isWaitingOnUs, mediaPreviewKind, useConversationsConfig, useConversationsStore };
|
|
321
|
+
//# sourceMappingURL=chunk-NWH5AIUH.js.map
|
|
322
|
+
//# sourceMappingURL=chunk-NWH5AIUH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/data/media.ts","../src/store.ts","../src/context.tsx","../src/lib/campainha.ts","../src/components/MessagePreview.tsx"],"names":["getSupabaseClientOptional","jsx"],"mappings":";;;;;;;;AA8KO,IAAM,cAAA,GAA0C;AAAA,EACrD,GAAA,EAAK,KAAA;AAAA,EACL,QAAA,EAAU,UAAA;AAAA,EACV,SAAA,EAAW,WAAA;AAAA,EACX,KAAA,EAAO,OAAA;AAAA,EACP,OAAA,EAAS,UAAA;AAAA,EACT,OAAA,EAAS;AACX;AAeO,SAAS,cAAc,YAAA,EAAqC;AACjE,EAAA,IAAI,YAAA,CAAa,MAAA,KAAW,MAAA,EAAQ,OAAO,KAAA;AAO3C,EAAA,IAAI,YAAA,CAAa,kBAAkB,YAAA,CAAa,aAAA,IACzC,aAAa,cAAA,IAAkB,YAAA,CAAa,eAAe,OAAO,KAAA;AACzE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,EAAA;AAAA,MAAA,CAAA,CAAE,KAAK,GAAG,CAAA;AAAA,MAAG,MAAA,GAAS,CAAA,EAAA,EAAK,MAAM,CAAA,CAAA,CAAA,GAAM;AAAA,KAAA,EAAG;AAAA,GAAA,EACxE,CAAA;AAEJ","file":"chunk-NWH5AIUH.js","sourcesContent":["// ---------------------------------------------------------------------------\n// @fayz-ai/plugin-conversations — domain types for the unified omni-channel\n// inbox (the GoHighLevel \"Conversations\" equivalent). Provider-agnostic.\n// ---------------------------------------------------------------------------\n\n// `support` threads are help-desk tickets written into the same inbox.\nexport type Channel = 'sms' | 'whatsapp' | 'instagram' | 'email' | 'webchat' | 'support'\n\nexport type ConversationStatus = 'open' | 'snoozed' | 'closed'\n\nexport type MessageDirection = 'inbound' | 'outbound'\n\nexport interface Conversation {\n id: string\n contactName: string\n /** The WhatsApp number (provider) the thread lives on — replies leave from\n * it (019). `evolution` = the everyday number, `tyxter` = the official one. */\n provider?: string\n /**\n * `public.people` id when the thread is tied to a real contact record (the\n * compose modal resolves one via the shared ContactPicker). Absent for legacy\n * threads and for inbound messages from an unknown handle.\n */\n contactPersonId?: string\n /** Phone, @handle, or email depending on channel */\n contactHandle: string\n channel: Channel\n lastMessagePreview: string\n lastMessageAt: string\n /**\n * Who spoke last: `inbound` = the customer, `outbound` = the house.\n *\n * The field the queue is built on — \"waiting on us\" is `status === 'open'`\n * plus this being `inbound`. `unreadCount` is the older approximation and\n * gets the painful case wrong: a thread somebody opened, read, meant to\n * answer later and forgot has zero unread and a customer still waiting.\n *\n * Optional because a thread predating the column's backfill (or a provider\n * that does not report direction) genuinely does not know — see\n * `isWaitingOnUs`, which falls back rather than guessing.\n */\n lastMessageDirection?: MessageDirection\n unreadCount: number\n /** Quando alguém deu a conversa por vista.\n *\n * Vale enquanto for POSTERIOR a `lastMessageAt`: mensagem nova devolve a\n * conversa à fila sozinha, sem ninguém ter de lembrar de apagar nada. */\n acknowledgedAt?: string | null\n status: ConversationStatus\n /** Quem ATENDE esta conversa. */\n assignedTo?: string\n /** Quem é dono do LEAD — outra pergunta, e a que decide o follow-up.\n * Derivado de `v_leads` pela view `v_conversations`: copiar aqui faria uma\n * segunda verdade que envelhece quando alguém clica \"Assumir\" no funil. */\n leadOwnerId?: string\n leadOwnerName?: string\n /** Which team's inbox the thread is in (024): help-desk threads are\n * `support`, everything else `commercial`. The database only returns the\n * inboxes the reader may see. */\n inbox?: 'commercial' | 'support'\n /** Tailwind-ish accent for the avatar bubble */\n accent: string\n tags: string[]\n // Optional context shown in the contact panel.\n location?: string\n note?: string\n}\n\nexport interface Message {\n id: string\n conversationId: string\n channel: Channel\n direction: MessageDirection\n body: string\n at: string\n author: string\n /** O que aconteceu com ela depois que saiu. Nulo na entrada — ela chegou,\n * não foi entregue por nós. `failed` é o caso que a tela precisa gritar:\n * uma mensagem que nunca saiu não pode parecer uma mensagem enviada. */\n deliveryStatus?: string | null\n /** O id no provedor. Sem ele, não saiu — e é a chave para buscar o JSON cru. */\n providerMessageId?: string | null\n /**\n * What the provider sent, when it was not plain text. Absent on every row\n * written before migration 012 — absent is \"unknown\", never \"text\", because\n * the rows this exists for are exactly the ones that stored as empty text.\n */\n messageType?: MessageType | null\n /**\n * The part `body` cannot hold: parsed vCards, media metadata, coordinates.\n * Shape follows `messageType`; see functions/_shared/evolution-runtime.js.\n */\n payload?: MessagePayload | null\n /**\n * Where the bytes are, in the private `attachments` bucket — or null, which\n * means one of three ordinary things: the message is text, the row predates\n * 013, or the upload did not happen. Never a URL: the bucket is private and\n * a link has to be signed per view, which `media_url` does against the row\n * rather than against a path the client supplies.\n */\n mediaPath?: string | null\n}\n\nexport type MessageType =\n | 'text' | 'contact' | 'image' | 'video' | 'audio'\n | 'document' | 'sticker' | 'location' | 'reaction' | 'poll' | 'unknown'\n\n/** A contact card someone forwarded into the thread. The number in it is\n * routinely the reason the conversation is happening. */\nexport interface SharedContact {\n name: string\n /** `display` is what a human reads back; `digits` is what dials. */\n phones: Array<{ display: string; digits: string }>\n}\n\nexport interface MessagePayload {\n contacts?: SharedContact[]\n mimetype?: string | null\n fileName?: string | null\n fileLength?: number | null\n seconds?: number | null\n ptt?: boolean | null\n caption?: string | null\n latitude?: number | null\n longitude?: number | null\n name?: string | null\n address?: string | null\n /** Only on `unknown`: the provider keys nobody has mapped yet. */\n keys?: string[]\n /** Business templates and interactive cards: the buttons under the text. */\n kind?: 'template' | 'interactive' | 'buttons' | 'button_reply'\n buttons?: Array<{ text?: string | null; url?: string | null; phone?: string | null }>\n /** The message this one answers (WhatsApp's quoted block). */\n quoted?: { id: string; type?: string; body?: string }\n /** \"Encaminhada\" / \"Encaminhada com frequência\". */\n forwarded?: boolean | 'many'\n /** The preview card the sender's phone built for a link. */\n link?: { url?: string | null; title?: string | null; description?: string | null; thumbnail?: string | null }\n /** Poll options. */\n options?: string[]\n /** Reactions by side: what the contact and what we reacted with. */\n reactions?: { contact?: string; me?: string }\n edited?: boolean\n deleted?: boolean\n}\n\nexport interface ListConversationsQuery {\n channel?: Channel | 'all'\n status?: ConversationStatus | 'all'\n search?: string\n /** Recorta pelo DONO DO LEAD. `'none'` traz quem ainda não é lead de\n * ninguém — a fila que precisa de dono, e a pergunta que a caixa sozinha\n * não respondia. */\n leadOwnerId?: string | 'none'\n}\n\nexport interface SendMessageInput {\n conversationId: string\n body: string\n}\n\nexport interface CreateConversationInput {\n contactName: string\n /** `public.people` id, when the contact was resolved/created by the picker. */\n contactPersonId?: string\n /** Phone, @handle, or email depending on channel. */\n contactHandle?: string\n channel: Channel\n /** Optional first outbound message; stamps preview + last_message_at. */\n firstMessage?: string\n /** Optional free-text note surfaced in the contact panel. */\n note?: string\n}\n\nexport const CHANNEL_LABELS: Record<Channel, string> = {\n sms: 'SMS',\n whatsapp: 'WhatsApp',\n instagram: 'Instagram',\n email: 'Email',\n webchat: 'Web Chat',\n support: 'Suporte',\n}\n\n/**\n * Is this thread waiting on US?\n *\n * One definition, in one place, because the KPI, the queue table and anything\n * that later filters the inbox have to agree — a dashboard that says three and\n * a list that shows one is worse than neither.\n *\n * `lastMessageDirection` is the real answer. `unreadCount` is the fallback for\n * a thread that genuinely does not know its direction (older than migration\n * 001, or a provider that does not report one) — it under-reports rather than\n * over-reports, which is the right way round: a queue that invents work loses\n * trust faster than one that misses an old row.\n */\nexport function isWaitingOnUs(conversation: Conversation): boolean {\n if (conversation.status !== 'open') return false\n // DAR POR VISTA vence a direção — e só enquanto for mais recente que a\n // última mensagem. Alguém leu, decidiu que não cabe resposta, e tirou da\n // fila; se chegar mensagem depois disso, a comparação se inverte sozinha e a\n // conversa volta. É por isso que é um instante e não um booleano: um\n // booleano precisaria de alguém para apagá-lo, e o dia do esquecimento é o\n // dia em que um cliente fica esperando sem aparecer para ninguém.\n if (conversation.acknowledgedAt && conversation.lastMessageAt\n && conversation.acknowledgedAt >= conversation.lastMessageAt) return false\n if (conversation.lastMessageDirection) return conversation.lastMessageDirection === 'inbound'\n return conversation.unreadCount > 0\n}\n","// ---------------------------------------------------------------------------\n// A file or a voice note leaving the inbox.\n//\n// The screen only hands the file over: the integration service stores the\n// bytes, writes the message and sends it from the number the thread lives on\n// (`send_media`). Base64 because the door is JSON; WhatsApp's own caps (16 MB\n// media, 100 MB documents) keep that reasonable.\n// ---------------------------------------------------------------------------\nimport { getSupabaseClientOptional, getActiveTenantId } from '@fayz-ai/core'\n\nexport const MEDIA_LIMIT_MB = { media: 16, document: 100 }\n\nfunction toBase64(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader()\n reader.onload = () => resolve(String(reader.result ?? '').replace(/^data:[^;]*;base64,/u, ''))\n reader.onerror = () => reject(reader.error ?? new Error('Não foi possível ler o arquivo'))\n reader.readAsDataURL(blob)\n })\n}\n\nexport async function sendMedia(input: {\n conversationId: string\n file: Blob\n fileName?: string\n caption?: string\n /** A voice note recorded in the inbox (sent as WhatsApp \"gravado agora\"). */\n ptt?: boolean\n}): Promise<void> {\n const client = getSupabaseClientOptional() as any\n const tenantId = getActiveTenantId()\n if (!client || !tenantId) throw new Error('Sem conexão com a casa')\n const mimetype = input.file.type || 'application/octet-stream'\n const isDoc = !/^(image|video|audio)\\//u.test(mimetype)\n const limit = (isDoc ? MEDIA_LIMIT_MB.document : MEDIA_LIMIT_MB.media) * 1024 * 1024\n if (input.file.size > limit) throw new Error(`Arquivo maior que ${isDoc ? MEDIA_LIMIT_MB.document : MEDIA_LIMIT_MB.media} MB, o limite do WhatsApp`)\n const data = await toBase64(input.file)\n const { data: out, error } = await client.functions.invoke('conversations-provider', {\n body: {\n tenantId, action: 'send_media', conversationId: input.conversationId, data, mimetype,\n fileName: input.fileName ?? (input.file as File).name ?? null, caption: input.caption ?? '', ptt: input.ptt === true,\n },\n })\n if (error) {\n const detail = (await error.context?.json?.().catch(() => null)) as { message?: string } | null\n throw new Error(detail?.message ?? error.message)\n }\n if ((out as any)?.error) throw new Error((out as any).message ?? (out as any).error)\n}\n","import { createStore, type StoreApi } from 'zustand/vanilla'\nimport { getSupabaseClientOptional } from '@fayz-ai/core'\nimport { sendMedia as sendMediaToService } from './data/media'\nimport type { ConversationsProvider } from './data/types'\nimport type {\n Conversation,\n Message,\n Channel,\n ConversationStatus,\n CreateConversationInput,\n} from './types'\n\nexport async function currentUserId(): Promise<string | null> {\n try {\n const sb = getSupabaseClientOptional() as any\n const { data } = await sb?.auth?.getSession?.() ?? {}\n return data?.session?.user?.id ?? null\n } catch {\n return null\n }\n}\n\n/** Quem, por onde, e como chamá-lo. Vem de outro módulo — hoje a ficha do lead\n * no CRM — que sabe a pessoa e não sabe nada sobre conversas. */\nexport interface OpenForPersonInput {\n /** `public.people` id. É por ele que a conversa é reconhecida; o telefone é\n * o desempate para threads antigas, criadas antes de haver vínculo. */\n personId?: string\n name: string\n handle: string\n channel: Channel\n}\n\n/** Só os dígitos. `+55 11 99999-0000` e `5511999990000` são o mesmo telefone, e\n * comparar como texto cru abriria uma segunda thread para a mesma pessoa. */\nfunction handleKey(h: string | undefined | null): string {\n const v = (h ?? '').trim()\n if (!v) return ''\n return /[@a-z]/i.test(v) ? v.toLowerCase() : v.replace(/\\D/g, '')\n}\n\nexport interface ConversationsUIState {\n conversations: Conversation[]\n messages: Message[]\n selectedId: string | null\n refreshMessages: () => Promise<void>\n channelFilter: Channel | 'all'\n /** Recorte por DONO DO LEAD. `'none'` é a fila sem dono. */\n leadOwnerFilter?: string | 'none'\n search: string\n loading: boolean\n sending: boolean\n\n /** `autoSelect: false` lists without opening (and marking read) the first\n * conversation — the compact floating inbox starts on the list. */\n load(opts?: { autoSelect?: boolean }): Promise<void>\n select(id: string): Promise<void>\n /** Dar por vista SEM abrir — o \"ok, obrigado\" que não pede resposta. */\n markRead(id: string): Promise<void>\n deselect(): void\n setChannelFilter(channel: Channel | 'all'): Promise<void>\n setLeadOwnerFilter(ownerId?: string | 'none'): Promise<void>\n setSearch(search: string): Promise<void>\n create(input: CreateConversationInput): Promise<Conversation>\n /** Abrir a conversa DESTA pessoa neste canal, criando-a se ainda não houver. */\n openForPerson(input: OpenForPersonInput): Promise<Conversation>\n send(body: string): Promise<void>\n /** A file or a voice note to the selected conversation (integration service `send_media`). */\n sendMedia(input: { file: Blob; fileName?: string; caption?: string; ptt?: boolean }): Promise<void>\n setStatus(status: ConversationStatus): Promise<void>\n}\n\nexport function createConversationsStore(\n provider: ConversationsProvider,\n): StoreApi<ConversationsUIState> {\n return createStore<ConversationsUIState>((set, get) => ({\n conversations: [],\n messages: [],\n selectedId: null,\n channelFilter: 'all',\n leadOwnerFilter: undefined,\n search: '',\n loading: false,\n sending: false,\n\n async load(opts) {\n set({ loading: true })\n const conversations = await provider.listConversations({\n channel: get().channelFilter,\n leadOwnerId: get().leadOwnerFilter,\n search: get().search || undefined,\n })\n const selectedId = get().selectedId ?? (opts?.autoSelect === false ? null : (conversations.find((c) => c.status !== 'closed') ?? conversations[0])?.id ?? null)\n set({ conversations, loading: false, selectedId })\n if (selectedId) await get().select(selectedId)\n },\n\n /** Dar por vista sem abrir — o caso do \"ok, obrigado\" que não pede resposta. */\n async markRead(id: string) {\n await provider.markRead(id)\n const agora = new Date().toISOString()\n set((s) => ({\n conversations: s.conversations.map((c) => (\n c.id === id ? { ...c, unreadCount: 0, acknowledgedAt: agora } : c\n )),\n }))\n },\n\n async select(id: string) {\n set({ selectedId: id })\n const messages = await provider.getMessages(id)\n set({ messages })\n // Opening reads it only for the lead's owner. A manager (or anyone else)\n // looking leaves the thread red, so the seller still sees the contact to\n // make; \"Marcar como lida\" and a reply still clear it for anyone.\n const owner = get().conversations.find((c) => c.id === id)?.leadOwnerId\n if (owner && owner !== (await currentUserId())) return\n await provider.markRead(id)\n // `acknowledgedAt` junto, e não só o contador: é ele que tira a conversa\n // da fila. Sem isto a bolinha continuava acesa depois de abrir e ler.\n const agora = new Date().toISOString()\n set((s) => ({\n conversations: s.conversations.map((c) => (\n c.id === id ? { ...c, unreadCount: 0, acknowledgedAt: agora } : c\n )),\n }))\n },\n\n /** Relê as mensagens da conversa aberta, sem tocar em mais nada.\n *\n * O status de uma mensagem de WhatsApp muda DEPOIS do envio — entregue,\n * lida, às vezes minutos depois — e quem avisa é o webhook, que escreve no\n * banco sem a tela saber. Sem isto a caixa mostra para sempre o status do\n * instante do envio: um tique só, numa mensagem que já foi lida.\n *\n * Não usa `select()` de propósito: aquele marca a conversa como lida e\n * zera o contador, e uma releitura de fundo não é um gesto de ninguém. */\n async refreshMessages() {\n const id = get().selectedId\n if (!id) return\n try {\n const messages = await provider.getMessages(id)\n // Só escreve se mudou algo. `set` a cada dez segundos redesenharia a\n // thread inteira e roubaria a seleção de texto de quem está lendo.\n const before = get().messages\n const same = before.length === messages.length &&\n before.every((m, i) => m.id === messages[i].id && m.deliveryStatus === messages[i].deliveryStatus)\n if (!same) set({ messages })\n } catch { /* a caixa continua com o que tem; a próxima volta tenta de novo */ }\n },\n\n deselect() {\n set({ selectedId: null, messages: [] })\n },\n\n async setLeadOwnerFilter(ownerId) {\n set({ leadOwnerFilter: ownerId })\n await get().load()\n },\n\n async setChannelFilter(channel) {\n set({ channelFilter: channel })\n await get().load()\n },\n\n async setSearch(search) {\n set({ search })\n await get().load()\n },\n\n async create(input) {\n const created = await provider.createConversation(input)\n // The thread EXISTS the moment the insert returns, so resolve on that and\n // show it optimistically. Clear filters that would hide it, prepend it,\n // select it — all local.\n set((s) => ({\n channelFilter: 'all',\n search: '',\n conversations: [created, ...s.conversations.filter((c) => c.id !== created.id)],\n selectedId: created.id,\n }))\n\n // Reconciliation (authoritative list + the thread's messages) runs in the\n // BACKGROUND. It used to be awaited here, which made the caller — the\n // compose modal — hostage to two extra round-trips: on a slow pool the\n // conversation was already in the database while the modal sat open\n // looking broken, inviting a second click and a duplicate thread.\n // Failures are non-fatal: the optimistic row above already renders.\n void (async () => {\n try {\n const conversations = await provider.listConversations({})\n // Read-after-write guard: a refetch that races the insert may not\n // return the new row yet — keep the local one rather than dropping it.\n const merged = conversations.some((c) => c.id === created.id)\n ? conversations\n : [created, ...conversations]\n set({ conversations: merged })\n await get().select(created.id)\n } catch {\n /* optimistic state stands; the next load() reconciles */\n }\n })()\n\n return created\n },\n\n // Chegar aqui vindo de fora — da ficha de um lead, por exemplo — não pode\n // criar uma segunda thread com alguém com quem a casa já conversa. Procura\n // primeiro pela PESSOA, e só então pelo telefone: o vínculo é a verdade, e\n // o handle é o que resgata threads criadas antes de o vínculo existir.\n async openForPerson({ personId, name, handle, channel }) {\n // Uma caixa ainda não carregada não tem como saber que a thread existe.\n if (get().conversations.length === 0 && !get().loading) {\n try { await get().load() } catch { /* segue para a criação */ }\n }\n const key = handleKey(handle)\n const existing = get().conversations.find((c) =>\n c.channel === channel &&\n ((personId && c.contactPersonId === personId) ||\n (key !== '' && handleKey(c.contactHandle) === key)))\n\n if (existing) {\n // Limpa o que esconderia a thread: chegar por link e cair numa lista\n // filtrada é indistinguível de a conversa não existir.\n set({ channelFilter: 'all', search: '' })\n await get().select(existing.id)\n return existing\n }\n\n return get().create({\n contactName: name,\n contactPersonId: personId,\n contactHandle: handle,\n channel,\n })\n },\n\n async sendMedia(input) {\n const id = get().selectedId\n if (!id) return\n set({ sending: true })\n try {\n await sendMediaToService({ conversationId: id, ...input })\n } finally {\n set({ sending: false })\n await get().refreshMessages()\n }\n },\n\n async send(body: string) {\n const id = get().selectedId\n if (!id || !body.trim()) return\n set({ sending: true })\n const created = await provider.sendMessage({ conversationId: id, body: body.trim() })\n set((s) => ({\n sending: false,\n messages: [...s.messages, created],\n conversations: s.conversations.map((c) =>\n // `lastMessageDirection` acompanha a prévia, senão a fila mente. O\n // gatilho da migration 001 carimba a coluna no banco, mas a lista só\n // volta a ler no próximo `load()` — e até lá a thread que ACABOU de\n // ser respondida continua em \"esperando nós\", que é exatamente a\n // pergunta que essa coluna existe para responder.\n //\n // Antes da 001 isto não aparecia: a coluna vinha sempre indefinida e\n // `isWaitingOnUs` caía no `unreadCount`. A migration não criou o\n // defeito, tornou-o visível.\n c.id === id\n ? { ...c, lastMessagePreview: created.body, lastMessageAt: created.at, lastMessageDirection: 'outbound' as const }\n : c,\n ),\n }))\n },\n\n async setStatus(status) {\n const id = get().selectedId\n if (!id) return\n const updated = await provider.setStatus(id, status)\n set((s) => ({\n conversations: s.conversations.map((c) => (c.id === id ? updated : c)),\n // An archived conversation leaves the inbox, so it stops being the open one.\n ...(status === 'closed' ? { selectedId: null } : {}),\n }))\n },\n }))\n}\n","import React from 'react'\nimport { useStore, type StoreApi } from 'zustand'\nimport type { EntityLookup } from '@fayz-ai/admin'\nimport type { EntityDef } from '@fayz-ai/core'\nimport type { ConversationsUIState } from './store'\n\n/**\n * App-tunable knobs the inbox UI reads. Kept tiny on purpose: everything here\n * describes the APP's data shape (which people are \"contacts\" in this vertical),\n * never product policy.\n */\nexport interface ResolvedConversationsConfig {\n /** `people.kind` the picker searches. */\n contactKind: string\n /** Search source for the contact picker. Defaults to the person archetype. */\n contactLookup?: EntityLookup\n /** The app's own contact entity — \"Create\" opens ITS form. Agenda's twin is `clientEntityDef`. */\n contactEntityDef?: EntityDef\n}\n\nexport const DEFAULT_CONVERSATIONS_CONFIG: ResolvedConversationsConfig = {\n contactKind: 'contact',\n}\n\nconst StoreContext = React.createContext<StoreApi<ConversationsUIState> | null>(null)\nconst ConfigContext = React.createContext<ResolvedConversationsConfig>(DEFAULT_CONVERSATIONS_CONFIG)\n\nexport function ConversationsContextProvider({\n store,\n config = DEFAULT_CONVERSATIONS_CONFIG,\n children,\n}: {\n store: StoreApi<ConversationsUIState>\n config?: ResolvedConversationsConfig\n children?: React.ReactNode\n}) {\n return (\n <StoreContext.Provider value={store}>\n <ConfigContext.Provider value={config}>{children}</ConfigContext.Provider>\n </StoreContext.Provider>\n )\n}\n\nexport function useConversationsStore<T>(selector: (state: ConversationsUIState) => T): T {\n const store = React.useContext(StoreContext)\n if (!store) throw new Error('useConversationsStore must be used within ConversationsPage')\n return useStore(store, selector)\n}\n\nexport function useConversationsConfig(): ResolvedConversationsConfig {\n return React.useContext(ConfigContext)\n}\n","import { getSupabaseClientOptional } from '@fayz-ai/core'\n\n/**\n * UMA assinatura do tópico da conta, partilhada por quem precisar.\n *\n * ── por que não cada um a sua ───────────────────────────────────────────\n *\n * Dois consumidores querem o mesmo sinal: o vigia global (som, contagem,\n * notificação do sistema) e a caixa aberta (lista e thread ao vivo). O jeito\n * óbvio é cada um chamar `supabase.channel('conversas:<tenant>')` — e é o que\n * eu fiz, e está errado.\n *\n * Dois canais com o MESMO tópico no mesmo cliente não recebem os dois: um\n * vence. Testados em separado, ambos funcionam; juntos, um emudece. Em\n * produção quem venceu foi a tela — a mensagem aparecia sozinha e a notificação\n * do sistema não saía, sem erro nenhum para explicar.\n *\n * É o tipo de defeito que só aparece com as duas peças no ar ao mesmo tempo, e\n * por isso passou por dois testes verdes.\n *\n * ── o desenho ───────────────────────────────────────────────────────────\n *\n * Um canal por conta, contado por referências. O primeiro a chegar abre, o\n * último a sair fecha, e todos recebem a mesma campainha.\n */\n\nexport interface Chegada {\n conversationId?: string\n}\n\ntype Ouvinte = (c: Chegada) => void\n\ninterface Assinatura {\n canal: unknown\n ouvintes: Set<Ouvinte>\n}\n\nconst porConta = new Map<string, Assinatura>()\n\n/** Escuta a chegada de mensagem nesta conta. Devolve como deixar de escutar. */\nexport function assinarChegada(tenantId: string, ouvinte: Ouvinte): () => void {\n const supabase = getSupabaseClientOptional() as any\n if (!supabase?.channel || !tenantId) return () => {}\n\n let assinatura = porConta.get(tenantId)\n if (!assinatura) {\n const ouvintes = new Set<Ouvinte>()\n const canal = supabase\n .channel(`conversas:${tenantId}`)\n .on('broadcast', { event: 'inbound' }, (msg: any) => {\n const carga: Chegada = { conversationId: msg?.payload?.conversationId }\n // Cópia antes de percorrer: um ouvinte que se desinscreve ao receber\n // (a tela fechando no mesmo tique) mutaria o Set durante a iteração.\n for (const f of [...ouvintes]) {\n try { f(carga) } catch { /* um ouvinte que falha não cala os outros */ }\n }\n })\n .subscribe()\n assinatura = { canal, ouvintes }\n porConta.set(tenantId, assinatura)\n }\n\n assinatura.ouvintes.add(ouvinte)\n return () => {\n const a = porConta.get(tenantId)\n if (!a) return\n a.ouvintes.delete(ouvinte)\n // O último a sair fecha a porta. Deixar o canal aberto sem ouvintes seria\n // pagar uma conexão por conta que a pessoa visitou e abandonou.\n if (a.ouvintes.size === 0) {\n porConta.delete(tenantId)\n void (getSupabaseClientOptional() as any)?.removeChannel?.(a.canal)\n }\n }\n}\n","import * as React from 'react'\nimport { Camera, CircleHelp, FileText, MapPin, Mic, Sticker, User, Video, type LucideIcon } from 'lucide-react'\nimport { useTranslation } from '@fayz-ai/core'\n\n// ---------------------------------------------------------------------------\n// A message with no text of its own, the way WhatsApp shows it: an icon and a\n// word (\"🎤 Mensagem de voz\"), not \"[áudio]\".\n//\n// The bracketed labels are what the backend stores in `body` and in\n// `last_message_preview` for media without a caption (MEDIA_LABELS in the\n// integration service's evolution-runtime). They stay the stored value — a\n// notification or an export still reads as something — and the screen swaps\n// them for an icon here.\n// ---------------------------------------------------------------------------\n\nconst KINDS: Record<string, { icon: LucideIcon; key: string }> = {\n '[áudio]': { icon: Mic, key: 'conversations.preview.audio' },\n '[imagem]': { icon: Camera, key: 'conversations.preview.image' },\n '[vídeo]': { icon: Video, key: 'conversations.preview.video' },\n '[documento]': { icon: FileText, key: 'conversations.preview.document' },\n '[figurinha]': { icon: Sticker, key: 'conversations.preview.sticker' },\n '[localização]': { icon: MapPin, key: 'conversations.preview.location' },\n '[contato]': { icon: User, key: 'conversations.preview.contact' },\n '[mensagem não suportada]': { icon: CircleHelp, key: 'conversations.preview.unsupported' },\n}\n\n/** The icon and translation key for a stored media label, or null for text. */\nexport function mediaPreviewKind(text: string | null | undefined): { icon: LucideIcon; key: string } | null {\n return KINDS[String(text ?? '').trim()] ?? null\n}\n\n/** One line: the icon and its word for a media label, the text otherwise. */\nexport function MessagePreview({ text, suffix, className }: { text: string | null | undefined; suffix?: string; className?: string }) {\n const t = useTranslation()\n const kind = mediaPreviewKind(text)\n if (!kind) return <>{text}</>\n const Icon = kind.icon\n return (\n <span className={`inline-flex min-w-0 items-center gap-1 ${className ?? ''}`}>\n <Icon className=\"h-3.5 w-3.5 shrink-0\" />\n <span className=\"truncate\">{t(kind.key)}{suffix ? ` (${suffix})` : ''}</span>\n </span>\n )\n}\n"]}
|