@fayz-ai/plugin-conversations 0.26.0 → 0.27.1

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.
Files changed (47) hide show
  1. package/dist/CampaignsSurface-75POQIRI.js +860 -0
  2. package/dist/CampaignsSurface-75POQIRI.js.map +1 -0
  3. package/dist/{ConversationsPage-7W7LDH2H.js → ConversationsPage-RYEND3MG.js} +345 -170
  4. package/dist/ConversationsPage-RYEND3MG.js.map +1 -0
  5. package/dist/TemplatesSurface-QNTRYYTX.js +281 -0
  6. package/dist/TemplatesSurface-QNTRYYTX.js.map +1 -0
  7. package/dist/chunk-4OWC3V53.js +323 -0
  8. package/dist/chunk-4OWC3V53.js.map +1 -0
  9. package/dist/chunk-HMWUU5O7.js +75 -0
  10. package/dist/chunk-HMWUU5O7.js.map +1 -0
  11. package/dist/{chunk-6EZLUC62.js → chunk-VZLFELO6.js} +4 -74
  12. package/dist/chunk-VZLFELO6.js.map +1 -0
  13. package/dist/data/journeys.d.ts +198 -0
  14. package/dist/data/journeys.d.ts.map +1 -0
  15. package/dist/index.d.ts +6 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +106 -10
  18. package/dist/index.js.map +1 -1
  19. package/dist/locales/en.d.ts.map +1 -1
  20. package/dist/locales/pt-BR.d.ts.map +1 -1
  21. package/dist/migrations/index.d.ts +2 -0
  22. package/dist/migrations/index.d.ts.map +1 -1
  23. package/dist/migrations/main.browser.js +3 -1
  24. package/dist/migrations/main.browser.js.map +1 -1
  25. package/dist/migrations/main.js +260 -2
  26. package/dist/migrations/main.js.map +1 -1
  27. package/dist/store.d.ts.map +1 -1
  28. package/dist/views/ContactPanel.d.ts.map +1 -1
  29. package/dist/views/ConversationList.d.ts.map +1 -1
  30. package/dist/views/ConversationsPage.d.ts +2 -0
  31. package/dist/views/ConversationsPage.d.ts.map +1 -1
  32. package/dist/views/MessageThread.d.ts.map +1 -1
  33. package/dist/views/campaigns/CampaignWizard.d.ts +8 -0
  34. package/dist/views/campaigns/CampaignWizard.d.ts.map +1 -0
  35. package/dist/views/campaigns/CampaignsSurface.d.ts +4 -0
  36. package/dist/views/campaigns/CampaignsSurface.d.ts.map +1 -0
  37. package/dist/views/campaigns/NumberProtection.d.ts +5 -0
  38. package/dist/views/campaigns/NumberProtection.d.ts.map +1 -0
  39. package/dist/views/campaigns/TemplatesSurface.d.ts +3 -0
  40. package/dist/views/campaigns/TemplatesSurface.d.ts.map +1 -0
  41. package/dist/views/contact-profile.d.ts +58 -0
  42. package/dist/views/contact-profile.d.ts.map +1 -0
  43. package/package.json +3 -3
  44. package/dist/ConversationsPage-7W7LDH2H.js.map +0 -1
  45. package/dist/chunk-6EZLUC62.js.map +0 -1
  46. package/dist/views/LeadCard.d.ts +0 -6
  47. package/dist/views/LeadCard.d.ts.map +0 -1
@@ -0,0 +1,860 @@
1
+ import { providersApi } from './chunk-HMWUU5O7.js';
2
+ import { journeysApi, previewBody } from './chunk-4OWC3V53.js';
3
+ import React2 from 'react';
4
+ import { Plus, Loader2, Megaphone, AlertTriangle, ChevronLeft, RefreshCw, Pause, Play, Pencil, Trash2, ClipboardList, Mail, MessageCircle, ArrowUp, ArrowDown, ChevronRight, CheckCircle2, Briefcase, Users, UserRound, ShieldCheck, ShieldAlert } from 'lucide-react';
5
+ import { toast, Button, Card, StatTiles, ConfirmDialog, StepProgress, Input, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, Textarea, Switch } from '@fayz-ai/ui';
6
+ import { getSupabaseClientOptional } from '@fayz-ai/core';
7
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
8
+
9
+ function NumberProtection({ provider }) {
10
+ const official = provider === "tyxter";
11
+ return /* @__PURE__ */ jsxs(Card, { className: `space-y-2 p-4 ${official ? "border-success/40" : "border-warning/40"}`, children: [
12
+ /* @__PURE__ */ jsxs("p", { className: "flex items-center gap-2 text-sm font-medium", children: [
13
+ official ? /* @__PURE__ */ jsx(ShieldCheck, { className: "h-4 w-4 text-success" }) : /* @__PURE__ */ jsx(ShieldAlert, { className: "h-4 w-4 text-warning" }),
14
+ official ? "API oficial do WhatsApp" : "N\xFAmero conectado pelo QR (Evolution)"
15
+ ] }),
16
+ official ? /* @__PURE__ */ jsxs("ul", { className: "list-disc space-y-1 pl-5 text-xs text-muted-foreground", children: [
17
+ /* @__PURE__ */ jsx("li", { children: "S\xF3 sai modelo aprovado pela Meta no primeiro contato. Depois que a pessoa responde, a conversa \xE9 livre por 24 horas." }),
18
+ /* @__PURE__ */ jsx("li", { children: "Custa por mensagem entregue (marketing \u2248 R$ 0,32). N\xE3o h\xE1 risco de banir o n\xFAmero por volume." }),
19
+ /* @__PURE__ */ jsx("li", { children: "Come\xE7a com 250 contatos novos por dia, e o limite sobe sozinho conforme a qualidade." }),
20
+ /* @__PURE__ */ jsx("li", { children: "Bloqueios e den\xFAncias baixam a qualidade do n\xFAmero. Mensagem relevante continua sendo a regra." })
21
+ ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
22
+ /* @__PURE__ */ jsxs("ul", { className: "list-disc space-y-1 pl-5 text-xs text-muted-foreground", children: [
23
+ /* @__PURE__ */ jsxs("li", { children: [
24
+ /* @__PURE__ */ jsx("b", { children: "Ritmo humano:" }),
25
+ ' no m\xE1ximo 40 contatos novos por dia e 10 por hora, com 2 a 5 minutos aleat\xF3rios entre mensagens e "digitando\u2026" antes de cada uma.'
26
+ ] }),
27
+ /* @__PURE__ */ jsxs("li", { children: [
28
+ /* @__PURE__ */ jsx("b", { children: "Hor\xE1rio comercial:" }),
29
+ " dias \xFAteis, das 9h \xE0s 18h. Fora disso a campanha espera."
30
+ ] }),
31
+ /* @__PURE__ */ jsxs("li", { children: [
32
+ /* @__PURE__ */ jsx("b", { children: "Primeira mensagem:" }),
33
+ ' curta, sem link e sem m\xEDdia, dizendo de onde voc\xEAs se conhecem, terminando com uma pergunta e com "responda SAIR".'
34
+ ] }),
35
+ /* @__PURE__ */ jsxs("li", { children: [
36
+ /* @__PURE__ */ jsx("b", { children: "Sem textos iguais:" }),
37
+ " cada contato recebe uma varia\xE7\xE3o do modelo."
38
+ ] }),
39
+ /* @__PURE__ */ jsxs("li", { children: [
40
+ /* @__PURE__ */ jsx("b", { children: "Para sozinha" }),
41
+ " quando algu\xE9m responde, quando a pessoa pede para sair, e pausa a campanha inteira se 3 envios seguidos falharem, se menos de 5% responderem depois de 50 envios ou se mais de 5% pedirem para sair."
42
+ ] })
43
+ ] }),
44
+ /* @__PURE__ */ jsx("p", { className: "rounded-md bg-warning-soft px-3 py-2 text-[11px] text-warning-soft-foreground", children: "Conectar pelo QR n\xE3o \xE9 permitido pelos termos do WhatsApp \u2014 estes cuidados diminuem o risco, n\xE3o zeram. Use um n\xFAmero antigo, com conversas reais, e nunca um chip novo. A Meta est\xE1 testando um limite de mensagens sem resposta por m\xEAs." })
45
+ ] })
46
+ ] });
47
+ }
48
+ var STEPS = ["P\xFAblico", "Canal", "Jornada", "Ritmo e prote\xE7\xF5es", "Revis\xE3o"];
49
+ var DAY = 1440;
50
+ var DEFAULT_JOURNEY = [
51
+ { position: 1, waitMinutes: 0, channel: "whatsapp", templateId: null, taskTitle: null, contactRoute: "next" },
52
+ { position: 2, waitMinutes: 3 * DAY, channel: "whatsapp", templateId: null, taskTitle: null, contactRoute: "next" },
53
+ { position: 3, waitMinutes: 4 * DAY, channel: "task", templateId: null, taskTitle: "Ligar para {{nome_completo}} ({{empresa}}) \u2014 n\xE3o respondeu \xE0 campanha", contactRoute: "same" }
54
+ ];
55
+ var CHANNEL_UI = {
56
+ whatsapp: { label: "WhatsApp", icon: MessageCircle },
57
+ email: { label: "E-mail", icon: Mail },
58
+ task: { label: "Tarefa para o vendedor", icon: ClipboardList }
59
+ };
60
+ function CampaignWizard({ campaign, onClose, onSaved }) {
61
+ const [step, setStep] = React2.useState(0);
62
+ const [segments, setSegments] = React2.useState([]);
63
+ const [templates, setTemplates] = React2.useState([]);
64
+ const [providers, setProviders] = React2.useState([]);
65
+ const [saving, setSaving] = React2.useState(false);
66
+ const [audience, setAudience] = React2.useState(null);
67
+ const [loadingAudience, setLoadingAudience] = React2.useState(false);
68
+ const [draft, setDraft] = React2.useState(() => campaign ? { ...campaign } : {
69
+ name: "",
70
+ description: null,
71
+ provider: "evolution",
72
+ segmentId: null,
73
+ audience: "deals",
74
+ unitId: null,
75
+ stopOnReply: true,
76
+ pacing: {},
77
+ settings: {},
78
+ steps: DEFAULT_JOURNEY
79
+ });
80
+ React2.useEffect(() => {
81
+ void journeysApi.segments().then(setSegments).catch(() => setSegments([]));
82
+ void journeysApi.templates().then(setTemplates).catch(() => setTemplates([]));
83
+ void providersApi.list().then(setProviders).catch(() => setProviders([]));
84
+ }, []);
85
+ React2.useEffect(() => {
86
+ if (Object.keys(draft.pacing ?? {}).length) return;
87
+ void journeysApi.defaultPacing(draft.provider).then((p) => setDraft((d) => Object.keys(d.pacing ?? {}).length ? d : { ...d, pacing: p }));
88
+ }, [draft.provider, draft.pacing]);
89
+ React2.useEffect(() => {
90
+ if (!draft.segmentId) {
91
+ setAudience(null);
92
+ return;
93
+ }
94
+ setLoadingAudience(true);
95
+ void journeysApi.audience(draft.segmentId, draft.audience).then(setAudience).catch(() => setAudience(null)).finally(() => setLoadingAudience(false));
96
+ }, [draft.segmentId, draft.audience]);
97
+ const patch = (p) => setDraft((d) => ({ ...d, ...p }));
98
+ const patchStep = (i, p) => patch({ steps: draft.steps.map((s, j) => j === i ? { ...s, ...p } : s) });
99
+ const patchPacing = (p) => patch({ pacing: { ...draft.pacing, ...p } });
100
+ const tplOf = (id) => templates.find((t) => t.id === id);
101
+ const firstWhatsapp = draft.steps.find((s) => s.channel === "whatsapp");
102
+ const firstTpl = tplOf(firstWhatsapp?.templateId ?? null);
103
+ const problems = {
104
+ 0: !draft.name.trim() ? "D\xEA um nome \xE0 campanha." : !draft.segmentId ? "Escolha um segmento." : null,
105
+ 1: !draft.provider ? "Escolha o n\xFAmero." : null,
106
+ 2: draft.steps.length === 0 ? "A jornada precisa de pelo menos um toque." : draft.steps.some((s) => s.channel !== "task" && !s.templateId) ? "Todo toque de WhatsApp ou e-mail precisa de um modelo." : draft.steps.some((s) => s.channel === "email" && tplOf(s.templateId)?.channel !== "email") ? "Toque de e-mail precisa de um modelo de e-mail." : draft.steps.some((s) => s.channel === "whatsapp" && tplOf(s.templateId)?.channel === "email") ? "Toque de WhatsApp precisa de um modelo de WhatsApp." : null,
107
+ 3: null,
108
+ 4: null
109
+ };
110
+ async function save(start) {
111
+ const firstProblem = Object.values(problems).find(Boolean);
112
+ if (firstProblem) {
113
+ toast.error(firstProblem);
114
+ return;
115
+ }
116
+ setSaving(true);
117
+ try {
118
+ const seg = segments.find((s) => s.id === draft.segmentId);
119
+ const saved = await journeysApi.saveCampaign({ ...draft, audience: seg?.audience ?? draft.audience });
120
+ if (start) await journeysApi.setStatus(saved.id, "running");
121
+ toast.success(start ? "Campanha iniciada \u2014 o envio come\xE7a no pr\xF3ximo minuto, dentro do hor\xE1rio." : "Rascunho salvo");
122
+ onSaved(saved, start);
123
+ } catch (e) {
124
+ toast.error(e.message);
125
+ } finally {
126
+ setSaving(false);
127
+ }
128
+ }
129
+ const perDay = Number(draft.pacing?.per_day ?? 0);
130
+ const enrolled = audience?.count ?? 0;
131
+ const daysToFirstTouch = perDay > 0 ? Math.ceil(enrolled / perDay) : null;
132
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
133
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [
134
+ /* @__PURE__ */ jsxs(Button, { variant: "ghost", size: "sm", onClick: onClose, children: [
135
+ /* @__PURE__ */ jsx(ChevronLeft, { className: "h-4 w-4" }),
136
+ " Campanhas"
137
+ ] }),
138
+ /* @__PURE__ */ jsx(StepProgress, { total: STEPS.length, current: step, onSelect: setStep })
139
+ ] }),
140
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs("h2", { className: "text-base font-semibold", children: [
141
+ campaign ? "Editar campanha" : "Nova campanha",
142
+ " \xB7 ",
143
+ STEPS[step]
144
+ ] }) }),
145
+ step === 0 && /* @__PURE__ */ jsxs(Card, { className: "space-y-4 p-4", children: [
146
+ /* @__PURE__ */ jsxs("div", { className: "grid gap-3 sm:grid-cols-2", children: [
147
+ /* @__PURE__ */ jsxs("div", { children: [
148
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium", children: "Nome da campanha" }),
149
+ /* @__PURE__ */ jsx(Input, { value: draft.name, onChange: (e) => patch({ name: e.target.value }), placeholder: "Reengajar feira Abrasel \u2014 sem resposta" })
150
+ ] }),
151
+ /* @__PURE__ */ jsxs("div", { children: [
152
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium", children: "Segmento" }),
153
+ /* @__PURE__ */ jsxs(Select, { value: draft.segmentId ?? "", onValueChange: (v) => {
154
+ const seg = segments.find((s) => s.id === v);
155
+ patch({ segmentId: v, audience: seg?.audience ?? "deals" });
156
+ }, children: [
157
+ /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Escolha quem recebe" }) }),
158
+ /* @__PURE__ */ jsx(SelectContent, { children: segments.map((s) => /* @__PURE__ */ jsxs(SelectItem, { value: s.id, children: [
159
+ s.audience === "deals" ? "\u{1F4BC} " : "\u{1F464} ",
160
+ s.name
161
+ ] }, s.id)) })
162
+ ] }),
163
+ /* @__PURE__ */ jsxs("p", { className: "mt-1 text-[11px] text-muted-foreground", children: [
164
+ "Segmentos ficam em Marketing \u203A Segmentos. Um segmento de ",
165
+ /* @__PURE__ */ jsx("b", { children: "neg\xF3cios" }),
166
+ " deixa a campanha tentar os outros contatos de cada neg\xF3cio."
167
+ ] })
168
+ ] })
169
+ ] }),
170
+ /* @__PURE__ */ jsxs("div", { children: [
171
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium", children: "Descri\xE7\xE3o (opcional)" }),
172
+ /* @__PURE__ */ jsx(Input, { value: draft.description ?? "", onChange: (e) => patch({ description: e.target.value || null }), placeholder: "Para quem \xE9, e por qu\xEA" })
173
+ ] }),
174
+ /* @__PURE__ */ jsx(AudienceSummary, { loading: loadingAudience, audience, kind: draft.audience })
175
+ ] }),
176
+ step === 1 && /* @__PURE__ */ jsxs("div", { className: "grid gap-3 md:grid-cols-2", children: [
177
+ ["evolution", "tyxter"].map((p) => {
178
+ const row = providers.find((r) => r.provider === p);
179
+ const on = draft.provider === p;
180
+ return /* @__PURE__ */ jsxs(
181
+ Button,
182
+ {
183
+ type: "button",
184
+ variant: "bare",
185
+ size: "bare",
186
+ onClick: () => patch({ provider: p, pacing: {} }),
187
+ className: `flex h-auto flex-col items-start gap-1 whitespace-normal rounded-card border p-4 text-left ${on ? "border-primary ring-2 ring-primary/30" : "border-border hover:bg-muted/40"}`,
188
+ children: [
189
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold", children: p === "evolution" ? "WhatsApp do dia a dia (QR)" : "WhatsApp oficial (Tyxter)" }),
190
+ /* @__PURE__ */ jsx("span", { className: "text-xs font-normal text-muted-foreground", children: p === "evolution" ? "O mesmo n\xFAmero do Conversas. Gr\xE1tis, ritmo lento e risco de restri\xE7\xE3o." : "Modelos aprovados pela Meta, cobran\xE7a por mensagem, sem risco de banir." }),
191
+ /* @__PURE__ */ jsxs("span", { className: `mt-1 rounded-full px-2 py-0.5 text-[10px] ${row?.status === "connected" ? "bg-success-soft text-success-soft-foreground" : "bg-muted text-muted-foreground"}`, children: [
192
+ row ? row.status === "connected" ? "conectado" : row.status : "n\xE3o configurado",
193
+ row?.isActive ? " \xB7 ativo no Conversas" : ""
194
+ ] })
195
+ ]
196
+ },
197
+ p
198
+ );
199
+ }),
200
+ /* @__PURE__ */ jsx("div", { className: "md:col-span-2", children: /* @__PURE__ */ jsx(NumberProtection, { provider: draft.provider }) })
201
+ ] }),
202
+ step === 2 && /* @__PURE__ */ jsxs(Card, { className: "space-y-3 p-4", children: [
203
+ /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
204
+ "Cada toque espera o anterior. Quem responder em qualquer canal sai da jornada",
205
+ draft.stopOnReply ? "" : " (desligado)",
206
+ "; quem pedir SAIR n\xE3o recebe mais nada."
207
+ ] }),
208
+ draft.steps.map((s, i) => {
209
+ const Icon = CHANNEL_UI[s.channel].icon;
210
+ const options = templates.filter((t) => s.channel === "email" ? t.channel === "email" : t.channel === "whatsapp");
211
+ return /* @__PURE__ */ jsxs("div", { className: "rounded-card border p-3", children: [
212
+ /* @__PURE__ */ jsxs("div", { className: "mb-2 flex items-center justify-between gap-2", children: [
213
+ /* @__PURE__ */ jsxs("p", { className: "flex items-center gap-2 text-sm font-medium", children: [
214
+ /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4" }),
215
+ " Toque ",
216
+ i + 1
217
+ ] }),
218
+ /* @__PURE__ */ jsxs("div", { className: "flex gap-1", children: [
219
+ /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "icon", className: "h-7 w-7", disabled: i === 0, onClick: () => {
220
+ const next = [...draft.steps];
221
+ [next[i - 1], next[i]] = [next[i], next[i - 1]];
222
+ patch({ steps: next });
223
+ }, "aria-label": "Subir", children: /* @__PURE__ */ jsx(ArrowUp, { className: "h-3.5 w-3.5" }) }),
224
+ /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "icon", className: "h-7 w-7", disabled: i === draft.steps.length - 1, onClick: () => {
225
+ const next = [...draft.steps];
226
+ [next[i + 1], next[i]] = [next[i], next[i + 1]];
227
+ patch({ steps: next });
228
+ }, "aria-label": "Descer", children: /* @__PURE__ */ jsx(ArrowDown, { className: "h-3.5 w-3.5" }) }),
229
+ /* @__PURE__ */ jsx(
230
+ Button,
231
+ {
232
+ variant: "ghost",
233
+ size: "icon",
234
+ className: "h-7 w-7",
235
+ disabled: draft.steps.length === 1,
236
+ onClick: () => patch({ steps: draft.steps.filter((_, j) => j !== i) }),
237
+ "aria-label": "Remover",
238
+ children: /* @__PURE__ */ jsx(Trash2, { className: "h-3.5 w-3.5" })
239
+ }
240
+ )
241
+ ] })
242
+ ] }),
243
+ /* @__PURE__ */ jsxs("div", { className: "grid gap-2 md:grid-cols-[150px_180px_1fr_200px]", children: [
244
+ /* @__PURE__ */ jsxs("div", { children: [
245
+ /* @__PURE__ */ jsx("label", { className: "text-[11px] text-muted-foreground", children: i === 0 ? "Come\xE7a" : "Espera depois do anterior" }),
246
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
247
+ /* @__PURE__ */ jsx(
248
+ Input,
249
+ {
250
+ type: "number",
251
+ min: 0,
252
+ className: "h-8 w-16 text-xs",
253
+ value: Math.round(s.waitMinutes / DAY * 10) / 10,
254
+ onChange: (e) => patchStep(i, { waitMinutes: Math.max(0, Number(e.target.value)) * DAY })
255
+ }
256
+ ),
257
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "dias" })
258
+ ] })
259
+ ] }),
260
+ /* @__PURE__ */ jsxs("div", { children: [
261
+ /* @__PURE__ */ jsx("label", { className: "text-[11px] text-muted-foreground", children: "Canal" }),
262
+ /* @__PURE__ */ jsxs(Select, { value: s.channel, onValueChange: (v) => patchStep(i, { channel: v, templateId: null }), children: [
263
+ /* @__PURE__ */ jsx(SelectTrigger, { className: "h-8 text-xs", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
264
+ /* @__PURE__ */ jsx(SelectContent, { children: Object.keys(CHANNEL_UI).map((c) => /* @__PURE__ */ jsx(SelectItem, { value: c, children: CHANNEL_UI[c].label }, c)) })
265
+ ] })
266
+ ] }),
267
+ /* @__PURE__ */ jsx("div", { children: s.channel === "task" ? /* @__PURE__ */ jsxs(Fragment, { children: [
268
+ /* @__PURE__ */ jsx("label", { className: "text-[11px] text-muted-foreground", children: "Tarefa (vai para o vendedor do neg\xF3cio)" }),
269
+ /* @__PURE__ */ jsx(Textarea, { rows: 2, className: "text-xs", value: s.taskTitle ?? "", onChange: (e) => patchStep(i, { taskTitle: e.target.value }) })
270
+ ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
271
+ /* @__PURE__ */ jsx("label", { className: "text-[11px] text-muted-foreground", children: "Modelo" }),
272
+ /* @__PURE__ */ jsxs(Select, { value: s.templateId ?? "", onValueChange: (v) => patchStep(i, { templateId: v }), children: [
273
+ /* @__PURE__ */ jsx(SelectTrigger, { className: "h-8 text-xs", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: options.length ? "Escolha o modelo" : "Crie um modelo em Modelos de mensagem" }) }),
274
+ /* @__PURE__ */ jsx(SelectContent, { children: options.map((t) => /* @__PURE__ */ jsxs(SelectItem, { value: t.id, children: [
275
+ t.name,
276
+ " \xB7 ",
277
+ 1 + t.variants.length,
278
+ " vers\xF5es"
279
+ ] }, t.id)) })
280
+ ] })
281
+ ] }) }),
282
+ /* @__PURE__ */ jsxs("div", { children: [
283
+ /* @__PURE__ */ jsx("label", { className: "text-[11px] text-muted-foreground", children: "Para quem" }),
284
+ /* @__PURE__ */ jsxs(Select, { value: i === 0 ? "same" : s.contactRoute, onValueChange: (v) => patchStep(i, { contactRoute: v }), disabled: i === 0, children: [
285
+ /* @__PURE__ */ jsx(SelectTrigger, { className: "h-8 text-xs", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
286
+ /* @__PURE__ */ jsxs(SelectContent, { children: [
287
+ /* @__PURE__ */ jsx(SelectItem, { value: "same", children: i === 0 ? "O contato principal" : "O mesmo contato do toque anterior" }),
288
+ /* @__PURE__ */ jsx(SelectItem, { value: "next", children: "Pr\xF3ximo contato do neg\xF3cio" })
289
+ ] })
290
+ ] })
291
+ ] })
292
+ ] })
293
+ ] }, i);
294
+ }),
295
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [
296
+ /* @__PURE__ */ jsxs(Button, { variant: "outline", size: "sm", onClick: () => patch({
297
+ steps: [...draft.steps, { position: draft.steps.length + 1, waitMinutes: 3 * DAY, channel: "whatsapp", templateId: null, taskTitle: null, contactRoute: "next" }]
298
+ }), children: [
299
+ /* @__PURE__ */ jsx(Plus, { className: "h-3.5 w-3.5" }),
300
+ " Adicionar toque"
301
+ ] }),
302
+ /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-xs", children: [
303
+ /* @__PURE__ */ jsx(Switch, { checked: draft.stopOnReply, onCheckedChange: (v) => patch({ stopOnReply: v }) }),
304
+ " Parar quando a pessoa responder"
305
+ ] })
306
+ ] }),
307
+ /* @__PURE__ */ jsx("p", { className: "text-[11px] text-muted-foreground", children: '"Pr\xF3ximo contato" segue a ordem: outro telefone da pessoa \u2192 outra pessoa da empresa \u2192 algu\xE9m do grupo. Se n\xE3o houver, repete o \xFAltimo.' })
308
+ ] }),
309
+ step === 3 && /* @__PURE__ */ jsxs("div", { className: "grid gap-3 md:grid-cols-[1fr_1fr]", children: [
310
+ /* @__PURE__ */ jsxs(Card, { className: "space-y-3 p-4", children: [
311
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: "Ritmo do n\xFAmero" }),
312
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-2", children: [
313
+ /* @__PURE__ */ jsx(NumberField, { label: "Contatos por dia", value: draft.pacing.per_day, onChange: (v) => patchPacing({ per_day: v }) }),
314
+ /* @__PURE__ */ jsx(NumberField, { label: "Por hora", value: draft.pacing.per_hour, onChange: (v) => patchPacing({ per_hour: v }) }),
315
+ /* @__PURE__ */ jsx(NumberField, { label: "Intervalo m\xEDnimo (s)", value: draft.pacing.delay_seconds?.[0], onChange: (v) => patchPacing({ delay_seconds: [v ?? 0, draft.pacing.delay_seconds?.[1] ?? v ?? 0] }) }),
316
+ /* @__PURE__ */ jsx(NumberField, { label: "Intervalo m\xE1ximo (s)", value: draft.pacing.delay_seconds?.[1], onChange: (v) => patchPacing({ delay_seconds: [draft.pacing.delay_seconds?.[0] ?? 0, v ?? 0] }) })
317
+ ] }),
318
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-2", children: [
319
+ /* @__PURE__ */ jsxs("div", { children: [
320
+ /* @__PURE__ */ jsx("label", { className: "text-[11px] text-muted-foreground", children: "Come\xE7a \xE0s" }),
321
+ /* @__PURE__ */ jsx(
322
+ Input,
323
+ {
324
+ className: "h-8 text-xs",
325
+ type: "time",
326
+ value: draft.pacing.hours?.start ?? "09:00",
327
+ onChange: (e) => patchPacing({ hours: { start: e.target.value, end: draft.pacing.hours?.end ?? "18:00", weekdays_only: draft.pacing.hours?.weekdays_only ?? true } })
328
+ }
329
+ )
330
+ ] }),
331
+ /* @__PURE__ */ jsxs("div", { children: [
332
+ /* @__PURE__ */ jsx("label", { className: "text-[11px] text-muted-foreground", children: "Termina \xE0s" }),
333
+ /* @__PURE__ */ jsx(
334
+ Input,
335
+ {
336
+ className: "h-8 text-xs",
337
+ type: "time",
338
+ value: draft.pacing.hours?.end ?? "18:00",
339
+ onChange: (e) => patchPacing({ hours: { start: draft.pacing.hours?.start ?? "09:00", end: e.target.value, weekdays_only: draft.pacing.hours?.weekdays_only ?? true } })
340
+ }
341
+ )
342
+ ] })
343
+ ] }),
344
+ /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-xs", children: [
345
+ /* @__PURE__ */ jsx(
346
+ Switch,
347
+ {
348
+ checked: draft.pacing.hours?.weekdays_only ?? true,
349
+ onCheckedChange: (v) => patchPacing({ hours: { start: draft.pacing.hours?.start ?? "09:00", end: draft.pacing.hours?.end ?? "18:00", weekdays_only: v } })
350
+ }
351
+ ),
352
+ "S\xF3 em dias \xFAteis"
353
+ ] }),
354
+ /* @__PURE__ */ jsx("p", { className: "text-[11px] text-muted-foreground", children: "O limite \xE9 do n\xFAmero: campanhas no mesmo n\xFAmero somam." })
355
+ ] }),
356
+ /* @__PURE__ */ jsxs(Card, { className: "space-y-3 p-4", children: [
357
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: "Pausa autom\xE1tica" }),
358
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-2", children: [
359
+ /* @__PURE__ */ jsx(NumberField, { label: "Falhas seguidas", value: draft.settings.pause_after_failures ?? 3, onChange: (v) => patch({ settings: { ...draft.settings, pause_after_failures: v ?? 3 } }) }),
360
+ /* @__PURE__ */ jsx(NumberField, { label: "Resposta m\xEDnima (%)", value: Math.round((draft.settings.min_reply_rate ?? 0.05) * 100), onChange: (v) => patch({ settings: { ...draft.settings, min_reply_rate: (v ?? 5) / 100 } }) }),
361
+ /* @__PURE__ */ jsx(NumberField, { label: "\u2026depois de N envios", value: draft.settings.min_reply_rate_after ?? 50, onChange: (v) => patch({ settings: { ...draft.settings, min_reply_rate_after: v ?? 50 } }) }),
362
+ /* @__PURE__ */ jsx(NumberField, { label: "Pedidos para sair (%)", value: Math.round((draft.settings.max_optout_rate ?? 0.05) * 100), onChange: (v) => patch({ settings: { ...draft.settings, max_optout_rate: (v ?? 5) / 100 } }) })
363
+ ] }),
364
+ /* @__PURE__ */ jsx("p", { className: "text-[11px] text-muted-foreground", children: "Quando pausa, o motivo aparece no acompanhamento e ningu\xE9m mais recebe at\xE9 algu\xE9m retomar." })
365
+ ] }),
366
+ /* @__PURE__ */ jsx("div", { className: "md:col-span-2", children: /* @__PURE__ */ jsx(NumberProtection, { provider: draft.provider }) })
367
+ ] }),
368
+ step === 4 && /* @__PURE__ */ jsxs("div", { className: "grid gap-3 md:grid-cols-[1fr_340px]", children: [
369
+ /* @__PURE__ */ jsxs(Card, { className: "space-y-3 p-4", children: [
370
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: draft.name || "Sem nome" }),
371
+ /* @__PURE__ */ jsxs("ul", { className: "space-y-1 text-xs text-muted-foreground", children: [
372
+ /* @__PURE__ */ jsxs("li", { children: [
373
+ "P\xFAblico: ",
374
+ /* @__PURE__ */ jsx("b", { className: "text-foreground", children: segments.find((s) => s.id === draft.segmentId)?.name ?? "\u2014" }),
375
+ " \u2014 ",
376
+ enrolled,
377
+ " ",
378
+ draft.audience === "deals" ? "neg\xF3cios" : "pessoas"
379
+ ] }),
380
+ /* @__PURE__ */ jsxs("li", { children: [
381
+ "N\xFAmero: ",
382
+ /* @__PURE__ */ jsx("b", { className: "text-foreground", children: draft.provider === "tyxter" ? "WhatsApp oficial" : "WhatsApp do dia a dia (QR)" })
383
+ ] }),
384
+ /* @__PURE__ */ jsxs("li", { children: [
385
+ "Jornada: ",
386
+ draft.steps.map((s, i) => `${i === 0 ? "dia 0" : `+${Math.round(s.waitMinutes / DAY * 10) / 10}d`} ${CHANNEL_UI[s.channel].label}`).join(" \u2192 ")
387
+ ] }),
388
+ /* @__PURE__ */ jsxs("li", { children: [
389
+ "Ritmo: at\xE9 ",
390
+ draft.pacing.per_day ?? "\u221E",
391
+ " por dia, ",
392
+ draft.pacing.per_hour ?? "\u221E",
393
+ " por hora, ",
394
+ draft.pacing.hours ? `${draft.pacing.hours.start}\u2013${draft.pacing.hours.end}${draft.pacing.hours.weekdays_only ? ", dias \xFAteis" : ""}` : "qualquer hor\xE1rio"
395
+ ] }),
396
+ daysToFirstTouch != null && /* @__PURE__ */ jsxs("li", { children: [
397
+ "O primeiro toque chega a todos em cerca de ",
398
+ /* @__PURE__ */ jsxs("b", { className: "text-foreground", children: [
399
+ daysToFirstTouch,
400
+ " dia(s) \xFAteis"
401
+ ] }),
402
+ "."
403
+ ] })
404
+ ] }),
405
+ audience?.sample?.length ? /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
406
+ /* @__PURE__ */ jsx("p", { className: "text-xs font-medium", children: "Como fica para os primeiros contatos" }),
407
+ audience.sample.map((s, i) => {
408
+ const r = s.routes[0];
409
+ const vars = { nome: (r?.name ?? "").split(" ")[0] ?? "", nome_completo: r?.name ?? "", empresa: s.company ?? "", vendedor: "o vendedor" };
410
+ return /* @__PURE__ */ jsxs("div", { className: "rounded-md border p-2", children: [
411
+ /* @__PURE__ */ jsxs("p", { className: "text-[11px] text-muted-foreground", children: [
412
+ s.company ?? s.title,
413
+ " \xB7 ",
414
+ s.routes.length,
415
+ " contato(s): ",
416
+ s.routes.map((x) => x.name).join(" \u2192 ")
417
+ ] }),
418
+ firstTpl && /* @__PURE__ */ jsx("p", { className: "mt-1 whitespace-pre-wrap text-xs", children: previewBody(firstTpl.body, vars, i) })
419
+ ] }, i);
420
+ })
421
+ ] }) : null
422
+ ] }),
423
+ /* @__PURE__ */ jsx(NumberProtection, { provider: draft.provider })
424
+ ] }),
425
+ problems[step] && /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: problems[step] }),
426
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2 border-t pt-3", children: [
427
+ /* @__PURE__ */ jsxs(Button, { variant: "ghost", onClick: () => step === 0 ? onClose() : setStep(step - 1), children: [
428
+ /* @__PURE__ */ jsx(ChevronLeft, { className: "h-4 w-4" }),
429
+ " ",
430
+ step === 0 ? "Cancelar" : "Voltar"
431
+ ] }),
432
+ /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
433
+ /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => void save(false), disabled: saving, children: "Salvar rascunho" }),
434
+ step < STEPS.length - 1 ? /* @__PURE__ */ jsxs(Button, { onClick: () => {
435
+ if (problems[step]) {
436
+ toast.error(problems[step]);
437
+ return;
438
+ }
439
+ setStep(step + 1);
440
+ }, children: [
441
+ "Continuar ",
442
+ /* @__PURE__ */ jsx(ChevronRight, { className: "h-4 w-4" })
443
+ ] }) : /* @__PURE__ */ jsxs(Button, { onClick: () => void save(true), disabled: saving, children: [
444
+ saving ? /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin" }) : /* @__PURE__ */ jsx(CheckCircle2, { className: "h-4 w-4" }),
445
+ " Iniciar campanha"
446
+ ] })
447
+ ] })
448
+ ] })
449
+ ] });
450
+ }
451
+ function NumberField({ label, value, onChange }) {
452
+ return /* @__PURE__ */ jsxs("div", { children: [
453
+ /* @__PURE__ */ jsx("label", { className: "text-[11px] text-muted-foreground", children: label }),
454
+ /* @__PURE__ */ jsx(
455
+ Input,
456
+ {
457
+ type: "number",
458
+ min: 0,
459
+ className: "h-8 text-xs",
460
+ value: value ?? "",
461
+ onChange: (e) => onChange(e.target.value === "" ? null : Number(e.target.value))
462
+ }
463
+ )
464
+ ] });
465
+ }
466
+ function AudienceSummary({ loading, audience, kind }) {
467
+ if (loading) return /* @__PURE__ */ jsxs("p", { className: "flex items-center gap-2 text-xs text-muted-foreground", children: [
468
+ /* @__PURE__ */ jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }),
469
+ " Contando\u2026"
470
+ ] });
471
+ if (!audience) return null;
472
+ return /* @__PURE__ */ jsxs("div", { className: "rounded-card border bg-muted/20 p-3", children: [
473
+ /* @__PURE__ */ jsxs("p", { className: "flex items-center gap-2 text-sm", children: [
474
+ kind === "deals" ? /* @__PURE__ */ jsx(Briefcase, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Users, { className: "h-4 w-4" }),
475
+ /* @__PURE__ */ jsx("b", { children: audience.count }),
476
+ " ",
477
+ kind === "deals" ? "neg\xF3cios entram na campanha" : "pessoas entram na campanha"
478
+ ] }),
479
+ audience.sample.length > 0 && /* @__PURE__ */ jsx("div", { className: "mt-2 space-y-1", children: audience.sample.map((s, i) => /* @__PURE__ */ jsxs("p", { className: "flex flex-wrap items-center gap-1 text-[11px] text-muted-foreground", children: [
480
+ /* @__PURE__ */ jsx("span", { className: "font-medium text-foreground", children: s.company ?? s.title }),
481
+ s.routes.map((r, j) => /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-0.5 rounded-full bg-card px-1.5", children: [
482
+ /* @__PURE__ */ jsx(UserRound, { className: "h-2.5 w-2.5" }),
483
+ " ",
484
+ r.name,
485
+ r.via !== "primary" ? ` (${VIA[r.via] ?? r.via})` : ""
486
+ ] }, j))
487
+ ] }, i)) })
488
+ ] });
489
+ }
490
+ var VIA = { other_phone: "outro telefone", company: "mesma empresa", group: "mesmo grupo" };
491
+ var STATUS = {
492
+ draft: { label: "rascunho", cls: "bg-muted text-muted-foreground" },
493
+ scheduled: { label: "agendada", cls: "bg-info-soft text-info-soft-foreground" },
494
+ running: { label: "rodando", cls: "bg-success-soft text-success-soft-foreground" },
495
+ paused: { label: "pausada", cls: "bg-warning-soft text-warning-soft-foreground" },
496
+ done: { label: "conclu\xEDda", cls: "bg-muted text-muted-foreground" },
497
+ cancelled: { label: "cancelada", cls: "bg-muted text-muted-foreground" }
498
+ };
499
+ var ENROLL_STATE = {
500
+ active: "na jornada",
501
+ replied: "respondeu",
502
+ opted_out: "pediu para sair",
503
+ completed: "jornada conclu\xEDda",
504
+ no_route: "sem contato",
505
+ failed: "falhou",
506
+ exited: "saiu"
507
+ };
508
+ function CampaignsSurface() {
509
+ const [view, setView] = React2.useState({ kind: "list" });
510
+ if (view.kind === "edit") {
511
+ return /* @__PURE__ */ jsx(
512
+ CampaignWizard,
513
+ {
514
+ campaign: view.campaign,
515
+ onClose: () => setView({ kind: "list" }),
516
+ onSaved: (c, started) => setView(started ? { kind: "monitor", id: c.id } : { kind: "list" })
517
+ }
518
+ );
519
+ }
520
+ if (view.kind === "monitor") {
521
+ return /* @__PURE__ */ jsx(CampaignMonitor, { id: view.id, onBack: () => setView({ kind: "list" }), onEdit: (c) => setView({ kind: "edit", campaign: c }) });
522
+ }
523
+ return /* @__PURE__ */ jsx(CampaignList, { onNew: () => setView({ kind: "edit", campaign: null }), onOpen: (c) => setView(c.status === "draft" ? { kind: "edit", campaign: c } : { kind: "monitor", id: c.id }) });
524
+ }
525
+ function CampaignList({ onNew, onOpen }) {
526
+ const [rows, setRows] = React2.useState(null);
527
+ const [stats, setStats] = React2.useState({});
528
+ const load = React2.useCallback(async () => {
529
+ try {
530
+ const list = (await journeysApi.campaigns()).filter((c) => c.steps.length > 0 || c.status === "draft");
531
+ setRows(list);
532
+ setStats(await journeysApi.stats(list.map((c) => c.id)));
533
+ } catch (e) {
534
+ toast.error(e.message);
535
+ setRows([]);
536
+ }
537
+ }, []);
538
+ React2.useEffect(() => {
539
+ void load();
540
+ }, [load]);
541
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
542
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [
543
+ /* @__PURE__ */ jsxs("div", { children: [
544
+ /* @__PURE__ */ jsx("h2", { className: "text-base font-semibold", children: "Campanhas" }),
545
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "Um segmento, uma jornada de toques e um ritmo que o n\xFAmero aguenta." })
546
+ ] }),
547
+ /* @__PURE__ */ jsxs(Button, { size: "sm", onClick: onNew, children: [
548
+ /* @__PURE__ */ jsx(Plus, { className: "h-3.5 w-3.5" }),
549
+ " Nova campanha"
550
+ ] })
551
+ ] }),
552
+ rows === null ? /* @__PURE__ */ jsx("div", { className: "flex justify-center py-10", children: /* @__PURE__ */ jsx(Loader2, { className: "h-5 w-5 animate-spin text-muted-foreground" }) }) : rows.length === 0 ? /* @__PURE__ */ jsxs(Card, { className: "flex flex-col items-center gap-2 p-10 text-center", children: [
553
+ /* @__PURE__ */ jsx(Megaphone, { className: "h-8 w-8 text-muted-foreground/40" }),
554
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: "Nenhuma campanha ainda." }),
555
+ /* @__PURE__ */ jsx("p", { className: "max-w-md text-xs text-muted-foreground", children: "Crie um segmento (quem recebe), um modelo de mensagem (o que recebe) e monte a campanha." }),
556
+ /* @__PURE__ */ jsxs(Button, { size: "sm", className: "mt-2", onClick: onNew, children: [
557
+ /* @__PURE__ */ jsx(Plus, { className: "h-3.5 w-3.5" }),
558
+ " Nova campanha"
559
+ ] })
560
+ ] }) : /* @__PURE__ */ jsx("div", { className: "space-y-2", children: rows.map((c) => {
561
+ const s = stats[c.id];
562
+ return /* @__PURE__ */ jsx(Card, { className: "cursor-pointer p-4 transition-colors hover:bg-muted/30", onClick: () => onOpen(c), children: /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-3", children: [
563
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
564
+ /* @__PURE__ */ jsxs("p", { className: "flex items-center gap-2 text-sm font-medium", children: [
565
+ c.name,
566
+ /* @__PURE__ */ jsx("span", { className: `rounded-full px-2 py-0.5 text-[10px] ${STATUS[c.status]?.cls ?? ""}`, children: STATUS[c.status]?.label ?? c.status })
567
+ ] }),
568
+ /* @__PURE__ */ jsxs("p", { className: "text-[11px] text-muted-foreground", children: [
569
+ c.steps.length,
570
+ " toques \xB7 ",
571
+ c.provider === "tyxter" ? "WhatsApp oficial" : "WhatsApp (QR)"
572
+ ] }),
573
+ c.pausedReason && /* @__PURE__ */ jsxs("p", { className: "mt-1 flex items-center gap-1 text-[11px] text-warning", children: [
574
+ /* @__PURE__ */ jsx(AlertTriangle, { className: "h-3 w-3" }),
575
+ " ",
576
+ c.pausedReason
577
+ ] })
578
+ ] }),
579
+ s && /* @__PURE__ */ jsxs("div", { className: "flex gap-4 text-center text-xs", children: [
580
+ /* @__PURE__ */ jsx(Metric, { label: "na campanha", value: s.enrolled }),
581
+ /* @__PURE__ */ jsx(Metric, { label: "enviadas", value: s.sent }),
582
+ /* @__PURE__ */ jsx(Metric, { label: "lidas", value: s.read }),
583
+ /* @__PURE__ */ jsx(Metric, { label: "responderam", value: s.replied, strong: true }),
584
+ /* @__PURE__ */ jsx(Metric, { label: "resposta", value: `${s.enrolled ? Math.round(100 * s.replied / s.enrolled) : 0}%` })
585
+ ] })
586
+ ] }) }, c.id);
587
+ }) })
588
+ ] });
589
+ }
590
+ function Metric({ label, value, strong }) {
591
+ return /* @__PURE__ */ jsxs("div", { children: [
592
+ /* @__PURE__ */ jsx("p", { className: `text-base leading-none ${strong ? "font-semibold text-success" : "font-medium"}`, children: value }),
593
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-[10px] text-muted-foreground", children: label })
594
+ ] });
595
+ }
596
+ function CampaignMonitor({ id, onBack, onEdit }) {
597
+ const [c, setC] = React2.useState(null);
598
+ const [stats, setStats] = React2.useState(null);
599
+ const [steps, setSteps] = React2.useState([]);
600
+ const [enrollments, setEnrollments] = React2.useState([]);
601
+ const [targets, setTargets] = React2.useState([]);
602
+ const [deals, setDeals] = React2.useState({});
603
+ const [filter, setFilter] = React2.useState("all");
604
+ const [busy, setBusy] = React2.useState(false);
605
+ const [confirmDelete, setConfirmDelete] = React2.useState(false);
606
+ const load = React2.useCallback(async () => {
607
+ try {
608
+ const camp = await journeysApi.campaign(id);
609
+ setC(camp);
610
+ const [st, sp, en, tg] = await Promise.all([
611
+ journeysApi.stats([id]).then((r) => r[id] ?? null),
612
+ journeysApi.stepStats(id),
613
+ journeysApi.enrollments(id),
614
+ journeysApi.targets({ campaignId: id, limit: 1e3 })
615
+ ]);
616
+ setStats(st);
617
+ setSteps(sp);
618
+ setEnrollments(en);
619
+ setTargets(tg);
620
+ const ids = [...new Set(en.map((e) => e.dealId).filter(Boolean))];
621
+ if (ids.length) {
622
+ const map = {};
623
+ for (let i = 0; i < ids.length; i += 200) {
624
+ const { data } = await getSupabaseClientOptional().from("v_deals").select("id, title, company_name").in("id", ids.slice(i, i + 200));
625
+ for (const d of data ?? []) map[d.id] = { title: d.title, company: d.company_name ?? null };
626
+ }
627
+ setDeals(map);
628
+ }
629
+ } catch (e) {
630
+ toast.error(e.message);
631
+ }
632
+ }, [id]);
633
+ React2.useEffect(() => {
634
+ void load();
635
+ const t = window.setInterval(() => {
636
+ if (document.visibilityState === "visible") void load();
637
+ }, 3e4);
638
+ return () => window.clearInterval(t);
639
+ }, [load]);
640
+ async function setStatus(status) {
641
+ setBusy(true);
642
+ try {
643
+ await journeysApi.setStatus(id, status);
644
+ await load();
645
+ } catch (e) {
646
+ toast.error(e.message);
647
+ } finally {
648
+ setBusy(false);
649
+ }
650
+ }
651
+ if (!c) return /* @__PURE__ */ jsx("div", { className: "flex justify-center py-10", children: /* @__PURE__ */ jsx(Loader2, { className: "h-5 w-5 animate-spin text-muted-foreground" }) });
652
+ const lastByEnrollment = /* @__PURE__ */ new Map();
653
+ for (const t of targets) if (t.enrollmentId && !lastByEnrollment.has(t.enrollmentId)) lastByEnrollment.set(t.enrollmentId, t);
654
+ const shown = enrollments.filter((e) => filter === "all" || e.state === filter);
655
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
656
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [
657
+ /* @__PURE__ */ jsxs(Button, { variant: "ghost", size: "sm", onClick: onBack, children: [
658
+ /* @__PURE__ */ jsx(ChevronLeft, { className: "h-4 w-4" }),
659
+ " Campanhas"
660
+ ] }),
661
+ /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
662
+ /* @__PURE__ */ jsxs(Button, { variant: "ghost", size: "sm", onClick: () => void load(), children: [
663
+ /* @__PURE__ */ jsx(RefreshCw, { className: "h-3.5 w-3.5" }),
664
+ " Atualizar"
665
+ ] }),
666
+ c.status === "running" && /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "outline", disabled: busy, onClick: () => void setStatus("paused"), children: [
667
+ /* @__PURE__ */ jsx(Pause, { className: "h-3.5 w-3.5" }),
668
+ " Pausar"
669
+ ] }),
670
+ (c.status === "paused" || c.status === "draft") && /* @__PURE__ */ jsxs(Button, { size: "sm", disabled: busy, onClick: () => void setStatus("running"), children: [
671
+ /* @__PURE__ */ jsx(Play, { className: "h-3.5 w-3.5" }),
672
+ " ",
673
+ c.status === "draft" ? "Iniciar" : "Retomar"
674
+ ] }),
675
+ c.status === "draft" && /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "outline", onClick: () => onEdit(c), children: [
676
+ /* @__PURE__ */ jsx(Pencil, { className: "h-3.5 w-3.5" }),
677
+ " Editar"
678
+ ] }),
679
+ c.status === "draft" && /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: () => setConfirmDelete(true), children: /* @__PURE__ */ jsx(Trash2, { className: "h-3.5 w-3.5" }) })
680
+ ] })
681
+ ] }),
682
+ /* @__PURE__ */ jsxs("div", { children: [
683
+ /* @__PURE__ */ jsxs("h2", { className: "flex items-center gap-2 text-base font-semibold", children: [
684
+ c.name,
685
+ /* @__PURE__ */ jsx("span", { className: `rounded-full px-2 py-0.5 text-[10px] ${STATUS[c.status]?.cls ?? ""}`, children: STATUS[c.status]?.label ?? c.status })
686
+ ] }),
687
+ c.description && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: c.description })
688
+ ] }),
689
+ c.pausedReason && /* @__PURE__ */ jsxs(Card, { className: "flex items-start gap-2 border-warning/40 bg-warning-soft p-3 text-xs text-warning-soft-foreground", children: [
690
+ /* @__PURE__ */ jsx(AlertTriangle, { className: "mt-0.5 h-4 w-4 shrink-0" }),
691
+ /* @__PURE__ */ jsxs("div", { children: [
692
+ /* @__PURE__ */ jsx("b", { children: "Pausada sozinha:" }),
693
+ " ",
694
+ c.pausedReason,
695
+ ". Ningu\xE9m recebe nada at\xE9 voc\xEA retomar."
696
+ ] })
697
+ ] }),
698
+ c.status === "running" && !c.settings.enrolled_at && /* @__PURE__ */ jsxs("p", { className: "flex items-center gap-2 text-xs text-muted-foreground", children: [
699
+ /* @__PURE__ */ jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }),
700
+ " Inscrevendo o segmento \u2014 leva at\xE9 um minuto."
701
+ ] }),
702
+ /* @__PURE__ */ jsx(
703
+ StatTiles,
704
+ {
705
+ loading: !stats,
706
+ tiles: [
707
+ { id: "enrolled", label: c.audience === "deals" ? "Neg\xF3cios na campanha" : "Pessoas na campanha", value: stats?.enrolled },
708
+ { id: "sent", label: "Mensagens enviadas", value: stats?.sent, hint: stats ? `${stats.pending} na fila` : void 0 },
709
+ { id: "read", label: "Lidas", value: stats?.read, hint: stats ? `${stats.delivered} entregues` : void 0 },
710
+ { id: "replied", label: "Responderam", value: stats?.replied, hint: stats ? `${stats.optedOut} pediram para sair` : void 0 }
711
+ ]
712
+ }
713
+ ),
714
+ /* @__PURE__ */ jsxs(Card, { className: "p-4", children: [
715
+ /* @__PURE__ */ jsx("p", { className: "mb-3 text-sm font-medium", children: "Por toque" }),
716
+ /* @__PURE__ */ jsx("div", { className: "space-y-3", children: c.steps.map((s) => {
717
+ const st = steps.find((x) => x.stepPosition === s.position);
718
+ const total = Math.max(1, st?.total ?? 0);
719
+ const bar = (n, cls) => /* @__PURE__ */ jsx("div", { className: `h-full ${cls}`, style: { width: `${100 * n / total}%` } });
720
+ return /* @__PURE__ */ jsxs("div", { children: [
721
+ /* @__PURE__ */ jsxs("div", { className: "mb-1 flex items-center justify-between text-xs", children: [
722
+ /* @__PURE__ */ jsxs("span", { className: "font-medium", children: [
723
+ "Toque ",
724
+ s.position,
725
+ " \xB7 ",
726
+ s.channel === "whatsapp" ? "WhatsApp" : s.channel === "email" ? "E-mail" : "Tarefa",
727
+ s.position > 1 ? ` \xB7 +${Math.round(s.waitMinutes / 144) / 10}d` : ""
728
+ ] }),
729
+ /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: st ? `${st.sent} enviadas \xB7 ${st.delivered} entregues \xB7 ${st.read} lidas \xB7 ${st.replied} responderam \xB7 ${st.failed} falhas \xB7 ${st.pending} na fila` : "ainda n\xE3o come\xE7ou" })
730
+ ] }),
731
+ /* @__PURE__ */ jsxs("div", { className: "flex h-2 overflow-hidden rounded-full bg-muted", children: [
732
+ st && bar(st.replied, "bg-success"),
733
+ st && bar(Math.max(0, st.read - st.replied), "bg-info"),
734
+ st && bar(Math.max(0, st.sent - st.read), "bg-primary/40"),
735
+ st && bar(st.failed, "bg-destructive")
736
+ ] })
737
+ ] }, s.position);
738
+ }) })
739
+ ] }),
740
+ /* @__PURE__ */ jsxs(Card, { className: "overflow-hidden", children: [
741
+ /* @__PURE__ */ jsx("div", { className: "flex flex-wrap items-center gap-1 border-b px-3 py-2", children: ["all", "active", "replied", "opted_out", "completed", "no_route"].map((f) => /* @__PURE__ */ jsxs(Button, { size: "sm", variant: filter === f ? "secondary" : "ghost", className: "h-7 text-xs", onClick: () => setFilter(f), children: [
742
+ f === "all" ? "Todos" : ENROLL_STATE[f],
743
+ " (",
744
+ f === "all" ? enrollments.length : enrollments.filter((e) => e.state === f).length,
745
+ ")"
746
+ ] }, f)) }),
747
+ /* @__PURE__ */ jsx("div", { className: "max-h-[480px] overflow-auto", children: /* @__PURE__ */ jsxs("table", { className: "w-full text-xs", children: [
748
+ /* @__PURE__ */ jsx("thead", { className: "sticky top-0 bg-card text-left text-muted-foreground", children: /* @__PURE__ */ jsxs("tr", { children: [
749
+ /* @__PURE__ */ jsx("th", { className: "px-3 py-2", children: "Neg\xF3cio" }),
750
+ /* @__PURE__ */ jsx("th", { className: "px-3 py-2", children: "Contato da vez" }),
751
+ /* @__PURE__ */ jsx("th", { className: "px-3 py-2", children: "Situa\xE7\xE3o" }),
752
+ /* @__PURE__ */ jsx("th", { className: "px-3 py-2", children: "\xDAltima mensagem" }),
753
+ /* @__PURE__ */ jsx("th", { className: "px-3 py-2", children: "Pr\xF3ximo toque" })
754
+ ] }) }),
755
+ /* @__PURE__ */ jsxs("tbody", { children: [
756
+ shown.map((e) => {
757
+ const d = e.dealId ? deals[e.dealId] : void 0;
758
+ const r = e.routes[e.routeIndex] ?? e.routes[0];
759
+ const last = lastByEnrollment.get(e.id);
760
+ return /* @__PURE__ */ jsxs("tr", { className: "border-t align-top", children: [
761
+ /* @__PURE__ */ jsxs("td", { className: "px-3 py-2", children: [
762
+ /* @__PURE__ */ jsx("p", { className: "font-medium", children: d?.company ?? d?.title ?? "\u2014" }),
763
+ /* @__PURE__ */ jsxs("p", { className: "text-[11px] text-muted-foreground", children: [
764
+ e.routes.length,
765
+ " contato(s)"
766
+ ] })
767
+ ] }),
768
+ /* @__PURE__ */ jsx("td", { className: "px-3 py-2", children: r ? /* @__PURE__ */ jsxs(Fragment, { children: [
769
+ /* @__PURE__ */ jsx("p", { children: r.name }),
770
+ /* @__PURE__ */ jsx("p", { className: "text-[11px] text-muted-foreground", children: r.phone_e164 ?? r.email ?? "\u2014" })
771
+ ] }) : "\u2014" }),
772
+ /* @__PURE__ */ jsx("td", { className: "px-3 py-2", children: /* @__PURE__ */ jsx("span", { className: `rounded-full px-2 py-0.5 text-[10px] ${e.state === "replied" ? "bg-success-soft text-success-soft-foreground" : e.state === "opted_out" ? "bg-destructive-soft text-destructive-soft-foreground" : "bg-muted text-muted-foreground"}`, children: ENROLL_STATE[e.state] ?? e.state }) }),
773
+ /* @__PURE__ */ jsx("td", { className: "max-w-[320px] px-3 py-2", children: last ? /* @__PURE__ */ jsxs(Fragment, { children: [
774
+ /* @__PURE__ */ jsx("p", { className: "line-clamp-2", children: last.body }),
775
+ /* @__PURE__ */ jsxs("p", { className: "text-[11px] text-muted-foreground", children: [
776
+ "toque ",
777
+ last.stepPosition,
778
+ " \xB7 ",
779
+ last.state,
780
+ last.failureDetail ? ` \xB7 ${last.failureDetail}` : ""
781
+ ] })
782
+ ] }) : /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "\u2014" }) }),
783
+ /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-muted-foreground", children: e.state === "active" && e.nextRunAt ? new Date(e.nextRunAt).toLocaleString("pt-BR", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" }) : "\u2014" })
784
+ ] }, e.id);
785
+ }),
786
+ shown.length === 0 && /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", { colSpan: 5, className: "px-3 py-8 text-center text-muted-foreground", children: "Ningu\xE9m aqui." }) })
787
+ ] })
788
+ ] }) })
789
+ ] }),
790
+ /* @__PURE__ */ jsx("p", { className: "text-[11px] text-muted-foreground", children: "Quem responde aparece no Conversas, com o vendedor do neg\xF3cio, e cada toque fica na linha do tempo do neg\xF3cio." }),
791
+ /* @__PURE__ */ jsx(
792
+ ConfirmDialog,
793
+ {
794
+ open: confirmDelete,
795
+ onCancel: () => setConfirmDelete(false),
796
+ title: "Excluir rascunho",
797
+ description: "O rascunho e a jornada dele deixam de existir.",
798
+ confirmLabel: "Excluir",
799
+ variant: "destructive",
800
+ onConfirm: () => {
801
+ journeysApi.deleteCampaign(id).then(onBack).catch((e) => toast.error(e.message));
802
+ }
803
+ }
804
+ )
805
+ ] });
806
+ }
807
+ function SendHistorySurface() {
808
+ const [rows, setRows] = React2.useState(null);
809
+ const [names, setNames] = React2.useState({});
810
+ React2.useEffect(() => {
811
+ void Promise.all([journeysApi.targets({ limit: 500 }), journeysApi.campaigns()]).then(([t, c]) => {
812
+ setRows(t);
813
+ setNames(Object.fromEntries(c.map((x) => [x.id, x.name])));
814
+ }).catch((e) => {
815
+ toast.error(e.message);
816
+ setRows([]);
817
+ });
818
+ }, []);
819
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
820
+ /* @__PURE__ */ jsxs("div", { children: [
821
+ /* @__PURE__ */ jsx("h2", { className: "text-base font-semibold", children: "Hist\xF3rico de envios" }),
822
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "Cada mensagem que as campanhas mandaram, a quem, e o que aconteceu com ela." })
823
+ ] }),
824
+ /* @__PURE__ */ jsx(Card, { className: "overflow-hidden", children: /* @__PURE__ */ jsx("div", { className: "max-h-[640px] overflow-auto", children: /* @__PURE__ */ jsxs("table", { className: "w-full text-xs", children: [
825
+ /* @__PURE__ */ jsx("thead", { className: "sticky top-0 bg-card text-left text-muted-foreground", children: /* @__PURE__ */ jsxs("tr", { children: [
826
+ /* @__PURE__ */ jsx("th", { className: "px-3 py-2", children: "Quando" }),
827
+ /* @__PURE__ */ jsx("th", { className: "px-3 py-2", children: "Campanha" }),
828
+ /* @__PURE__ */ jsx("th", { className: "px-3 py-2", children: "Para" }),
829
+ /* @__PURE__ */ jsx("th", { className: "px-3 py-2", children: "Mensagem" }),
830
+ /* @__PURE__ */ jsx("th", { className: "px-3 py-2", children: "Situa\xE7\xE3o" })
831
+ ] }) }),
832
+ /* @__PURE__ */ jsxs("tbody", { children: [
833
+ (rows ?? []).map((t) => /* @__PURE__ */ jsxs("tr", { className: "border-t align-top", children: [
834
+ /* @__PURE__ */ jsx("td", { className: "whitespace-nowrap px-3 py-2 text-muted-foreground", children: new Date(t.sentAt ?? t.queuedAt).toLocaleString("pt-BR", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" }) }),
835
+ /* @__PURE__ */ jsxs("td", { className: "px-3 py-2", children: [
836
+ names[t.campaignId] ?? "\u2014",
837
+ /* @__PURE__ */ jsxs("p", { className: "text-[11px] text-muted-foreground", children: [
838
+ "toque ",
839
+ t.stepPosition ?? 1,
840
+ " \xB7 ",
841
+ t.channel
842
+ ] })
843
+ ] }),
844
+ /* @__PURE__ */ jsx("td", { className: "px-3 py-2", children: t.phone ?? t.email ?? "\u2014" }),
845
+ /* @__PURE__ */ jsx("td", { className: "max-w-[420px] px-3 py-2", children: /* @__PURE__ */ jsx("p", { className: "line-clamp-2", children: t.body ?? "\u2014" }) }),
846
+ /* @__PURE__ */ jsxs("td", { className: "px-3 py-2", children: [
847
+ t.repliedAt ? "respondeu" : t.readAt ? "lida" : t.deliveredAt ? "entregue" : t.state,
848
+ t.failureDetail ? ` \xB7 ${t.failureDetail}` : ""
849
+ ] })
850
+ ] }, t.id)),
851
+ rows === null && /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", { colSpan: 5, className: "px-3 py-8 text-center", children: /* @__PURE__ */ jsx(Loader2, { className: "mx-auto h-4 w-4 animate-spin" }) }) }),
852
+ rows?.length === 0 && /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", { colSpan: 5, className: "px-3 py-8 text-center text-muted-foreground", children: "Nenhum envio ainda." }) })
853
+ ] })
854
+ ] }) }) })
855
+ ] });
856
+ }
857
+
858
+ export { CampaignsSurface, SendHistorySurface };
859
+ //# sourceMappingURL=CampaignsSurface-75POQIRI.js.map
860
+ //# sourceMappingURL=CampaignsSurface-75POQIRI.js.map