@controleonline/ui-crm 1.0.62 → 1.0.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,123 @@
1
+ /*
2
+ * @agents Pure helpers for the /ai chat (no React). Covered by src/tests/react/pages/mcp/mcpChatUtils.test.js.
3
+ */
4
+ const CHAT_EVENTS = ['mcp_chat_reply', 'conversation_message'];
5
+
6
+ const STAGE_LABELS = {
7
+ ia: 'IA',
8
+ relationship: 'Comercial',
9
+ support: 'Suporte',
10
+ };
11
+
12
+ const idOf = entity => {
13
+ if (entity === null || entity === undefined) return null;
14
+ if (typeof entity === 'number') return entity;
15
+ if (typeof entity === 'string') {
16
+ const tail = entity.split('/').pop();
17
+ return /^\d+$/.test(tail) ? Number(tail) : null;
18
+ }
19
+ if (entity.id !== undefined && entity.id !== null) return Number(entity.id);
20
+ return idOf(entity['@id']);
21
+ };
22
+
23
+ const parseAnnounce = task => {
24
+ const raw = task?.announce;
25
+ if (Array.isArray(raw) || (raw && typeof raw === 'object')) return raw;
26
+ try {
27
+ return JSON.parse(raw || '{}') || {};
28
+ } catch (e) {
29
+ return {};
30
+ }
31
+ };
32
+
33
+ // Internal chat of an employee: type ia with announce {"channel":"mcp"}. Everything else is a customer conversation.
34
+ const isInternalChat = task => {
35
+ const announce = parseAnnounce(task);
36
+ return task?.type === 'ia' && !Array.isArray(announce) && announce?.channel === 'mcp';
37
+ };
38
+ const isCustomerConversation = task => Boolean(task) && !isInternalChat(task);
39
+
40
+ // Channel of a customer conversation from its destinations (phone -> WhatsApp, address -> e-mail).
41
+ const conversationChannel = task => {
42
+ if (!isCustomerConversation(task)) return 'ai';
43
+ const announce = parseAnnounce(task);
44
+ const list = Array.isArray(announce) ? announce.map(String) : [];
45
+ if (list.some(v => /^\d{10,15}$/.test(v))) return 'whatsapp';
46
+ if (list.some(v => /@/.test(v))) return 'email';
47
+ return 'web';
48
+ };
49
+
50
+ const customerPhone = task => {
51
+ const announce = parseAnnounce(task);
52
+ if (!Array.isArray(announce)) return '';
53
+ return announce.find(v => /^\d{10,}$/.test(String(v))) || '';
54
+ };
55
+
56
+ const stageLabel = task => STAGE_LABELS[task?.type] || task?.type || '';
57
+
58
+ /**
59
+ * Websocket store keeps appending; consume only what arrived after `fromIndex`.
60
+ * Items can be single events or arrays of events.
61
+ */
62
+ const extractChatEvents = (messages, fromIndex = 0) => {
63
+ const list = Array.isArray(messages) ? messages : [];
64
+ const start = fromIndex > list.length ? 0 : fromIndex; // store was reset
65
+ const events = [];
66
+ list.slice(start).forEach(item => {
67
+ (Array.isArray(item) ? item : [item]).forEach(evt => {
68
+ if (evt && typeof evt === 'object' && CHAT_EVENTS.includes(String(evt.event || ''))) {
69
+ events.push(evt);
70
+ }
71
+ });
72
+ });
73
+ return {events, nextIndex: list.length};
74
+ };
75
+
76
+ /**
77
+ * Internal chats are private to their author; customer conversations are shared by the team.
78
+ */
79
+ const mergeConversations = (lists, currentPeopleId) => {
80
+ const byId = new Map();
81
+ lists.flat().forEach(task => {
82
+ const id = idOf(task);
83
+ if (!id || byId.has(id)) return;
84
+ const mine = currentPeopleId && idOf(task.registeredBy) === Number(currentPeopleId);
85
+ if (!isCustomerConversation(task) && currentPeopleId && !mine) return;
86
+ byId.set(id, task);
87
+ });
88
+ const time = t => new Date(t?.alterDate || t?.createdAt || 0).getTime() || 0;
89
+ return [...byId.values()].sort((a, b) => time(b) - time(a) || idOf(b) - idOf(a));
90
+ };
91
+
92
+ /**
93
+ * Bubble side/role. ai = the company (AI replies), note = private attendant note on a
94
+ * customer conversation, customer = the WhatsApp contact, me/staff = people of the company.
95
+ */
96
+ const messageRole = (item, {companyId, task, currentPeopleId}) => {
97
+ const by = idOf(item?.registeredBy);
98
+ const customerChat = isCustomerConversation(task);
99
+ if (by && companyId && by === Number(companyId)) {
100
+ return customerChat && item?.visibility === 'private' ? 'note' : 'ai';
101
+ }
102
+ if (customerChat) {
103
+ // In my own ticket (I am the client) my messages are mine.
104
+ if (by && currentPeopleId && by === Number(currentPeopleId)) return 'me';
105
+ return by && by === idOf(task?.client) ? 'customer' : 'staff';
106
+ }
107
+ if (!by && String(item?.id || '').startsWith('local-')) return 'me';
108
+ return by && currentPeopleId && by !== Number(currentPeopleId) ? 'staff' : 'me';
109
+ };
110
+
111
+ module.exports = {
112
+ isInternalChat,
113
+ conversationChannel,
114
+ STAGE_LABELS,
115
+ idOf,
116
+ parseAnnounce,
117
+ isCustomerConversation,
118
+ customerPhone,
119
+ stageLabel,
120
+ extractChatEvents,
121
+ mergeConversations,
122
+ messageRole,
123
+ };
@@ -0,0 +1,276 @@
1
+ /*
2
+ * @agents Data + realtime logic for /ai. Replies arrive by websocket (store "websocket",
3
+ * events mcp_chat_reply / conversation_message); a single fallback reload covers a lost event.
4
+ */
5
+ import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
6
+ import {useStore} from '@store';
7
+ import {api} from '@controleonline/ui-common/src/api';
8
+ import useToastMessage from '../../hooks/useToastMessage';
9
+
10
+ const {
11
+ idOf,
12
+ isCustomerConversation,
13
+ extractChatEvents,
14
+ mergeConversations,
15
+ } = require('./mcpChatUtils');
16
+
17
+ const REPLY_FALLBACK_MS = 90000;
18
+ const LIST_DEBOUNCE_MS = 400;
19
+ const TICKET_REFRESH_MS = 20000;
20
+ const toItems = res => {
21
+ const items = res?.member || res?.['hydra:member'] || res || [];
22
+ return Array.isArray(items) ? items : [];
23
+ };
24
+
25
+ export default function useMcpChat() {
26
+ const {showError} = useToastMessage();
27
+ const peopleStore = useStore('people');
28
+ const websocketStore = useStore('websocket');
29
+ const authStore = useStore('auth');
30
+ const wsMessages = websocketStore?.getters?.messages;
31
+ const currentPeopleId = idOf(authStore?.getters?.user?.people);
32
+ const company = peopleStore?.getters?.currentCompany || peopleStore?.getters?.mainCompany || null;
33
+ const companyId = idOf(company);
34
+
35
+ const [providers, setProviders] = useState([]);
36
+ const [provider, setProvider] = useState(null);
37
+ const [tasks, setTasks] = useState([]);
38
+ const [activeTaskId, setActiveTaskId] = useState(null);
39
+ const [messages, setMessages] = useState([]);
40
+ const [pending, setPending] = useState({}); // taskId -> 'pending' | 'processing'
41
+ const [loadingList, setLoadingList] = useState(true);
42
+ const [loadingChat, setLoadingChat] = useState(false);
43
+ const [sending, setSending] = useState(false);
44
+
45
+ const activeRef = useRef(null);
46
+ activeRef.current = activeTaskId;
47
+ // Start after whatever is already in the store: old replies must not replay.
48
+ const wsCursor = useRef(Array.isArray(wsMessages) ? wsMessages.length : 0);
49
+ const listTimer = useRef(null);
50
+ const fallbackTimers = useRef({});
51
+
52
+ const activeTask = useMemo(
53
+ () => tasks.find(t => idOf(t) === Number(activeTaskId)) || null,
54
+ [tasks, activeTaskId],
55
+ );
56
+ // A ticket I opened with the platform (my company has no AI): I talk in it from here.
57
+ const myTicket = Boolean(activeTask) && isCustomerConversation(activeTask) && idOf(activeTask.client) === Number(currentPeopleId);
58
+ // Someone else's customer conversation handled by our AI: read-only here.
59
+ const customerChat = isCustomerConversation(activeTask) && !myTicket;
60
+ const [ticketType, setTicketType] = useState('support');
61
+
62
+ const loadProviders = useCallback(async () => {
63
+ try {
64
+ const res = await api.fetch('/mcp/chat/providers', {params: companyId ? {company_id: companyId} : {}});
65
+ const list = Array.isArray(res?.providers) ? res.providers : [];
66
+ setProviders(list);
67
+ setProvider(prev => prev || list[0]?.provider || null);
68
+ } catch (e) {
69
+ showError(e?.message || 'Falha ao carregar providers de IA');
70
+ }
71
+ }, [companyId, showError]);
72
+
73
+ const loadTasks = useCallback(async () => {
74
+ if (!companyId) return;
75
+ const base = {provider: `/people/${companyId}`, 'order[alterDate]': 'desc', itemsPerPage: 50};
76
+ try {
77
+ // My internal chats + customer conversations the AI is handling + tickets I opened with the platform.
78
+ const [internal, customers, tickets] = await Promise.all([
79
+ api.fetch('/tasks', {params: {...base, type: 'ia', ...(currentPeopleId ? {registeredBy: `/people/${currentPeopleId}`} : {})}}),
80
+ api.fetch('/tasks', {params: {...base, 'exists[aiAgent]': true}}),
81
+ currentPeopleId
82
+ ? api.fetch('/tasks', {params: {client: `/people/${currentPeopleId}`, announce: 'via:ai', 'order[alterDate]': 'desc', itemsPerPage: 50}})
83
+ : Promise.resolve([]),
84
+ ]);
85
+ setTasks(mergeConversations([toItems(internal), toItems(customers), toItems(tickets)], currentPeopleId));
86
+ } catch (e) {
87
+ showError(e?.message || 'Falha ao listar conversas');
88
+ } finally {
89
+ setLoadingList(false);
90
+ }
91
+ }, [companyId, currentPeopleId, showError]);
92
+
93
+ const scheduleTasksReload = useCallback(() => {
94
+ clearTimeout(listTimer.current);
95
+ listTimer.current = setTimeout(loadTasks, LIST_DEBOUNCE_MS);
96
+ }, [loadTasks]);
97
+
98
+ const loadMessages = useCallback(
99
+ async (taskId, {silent = false} = {}) => {
100
+ if (!taskId) {
101
+ setMessages([]);
102
+ return;
103
+ }
104
+ if (!silent) setLoadingChat(true);
105
+ try {
106
+ const res = await api.fetch('/task_interations', {
107
+ params: {'task.id': taskId, type: 'comment', 'order[id]': 'asc', itemsPerPage: 200},
108
+ });
109
+ // Ignore a late response for a chat the user already left.
110
+ if (Number(activeRef.current) === Number(taskId)) setMessages(toItems(res));
111
+ } catch (e) {
112
+ showError(e?.message || 'Falha ao carregar mensagens');
113
+ } finally {
114
+ if (!silent) setLoadingChat(false);
115
+ }
116
+ },
117
+ [showError],
118
+ );
119
+
120
+ useEffect(() => {
121
+ loadProviders();
122
+ loadTasks();
123
+ }, [loadProviders, loadTasks]);
124
+
125
+ useEffect(() => {
126
+ loadMessages(activeTaskId);
127
+ }, [activeTaskId, loadMessages]);
128
+
129
+ // Platform staff replies to my ticket are not pushed to my devices: refresh while it is open.
130
+ useEffect(() => {
131
+ if (!myTicket || !activeTaskId) return undefined;
132
+ const timer = setInterval(() => loadMessages(activeTaskId, {silent: true}), TICKET_REFRESH_MS);
133
+ return () => clearInterval(timer);
134
+ }, [myTicket, activeTaskId, loadMessages]);
135
+
136
+ useEffect(
137
+ () => () => {
138
+ clearTimeout(listTimer.current);
139
+ Object.values(fallbackTimers.current).forEach(clearTimeout);
140
+ },
141
+ [],
142
+ );
143
+
144
+ const settle = useCallback(taskId => {
145
+ clearTimeout(fallbackTimers.current[taskId]);
146
+ delete fallbackTimers.current[taskId];
147
+ setPending(prev => {
148
+ const next = {...prev};
149
+ delete next[taskId];
150
+ return next;
151
+ });
152
+ }, []);
153
+
154
+ // Realtime: consume every new event since the last cursor (several can arrive in one batch).
155
+ useEffect(() => {
156
+ const {events, nextIndex} = extractChatEvents(wsMessages, wsCursor.current);
157
+ wsCursor.current = nextIndex;
158
+ if (!events.length) return;
159
+
160
+ let reloadActive = false;
161
+ events.forEach(evt => {
162
+ if (companyId && evt.companyId && Number(evt.companyId) !== Number(companyId)) return;
163
+ const taskId = Number(evt.task_id || 0);
164
+ if (!taskId) return;
165
+ if (evt.status === 'processing') {
166
+ setPending(prev => ({...prev, [taskId]: 'processing'}));
167
+ } else if (evt.event === 'mcp_chat_reply') {
168
+ settle(taskId);
169
+ if (evt.status === 'error') showError(evt.body || 'A IA não conseguiu responder.');
170
+ }
171
+ if (taskId === Number(activeRef.current) && evt.status !== 'processing') reloadActive = true;
172
+ });
173
+ if (reloadActive) loadMessages(activeRef.current, {silent: true});
174
+ scheduleTasksReload();
175
+ }, [wsMessages, companyId, loadMessages, scheduleTasksReload, settle, showError]);
176
+
177
+ const armFallback = useCallback(
178
+ taskId => {
179
+ clearTimeout(fallbackTimers.current[taskId]);
180
+ fallbackTimers.current[taskId] = setTimeout(() => {
181
+ settle(taskId);
182
+ if (Number(activeRef.current) === Number(taskId)) loadMessages(taskId, {silent: true});
183
+ }, REPLY_FALLBACK_MS);
184
+ },
185
+ [loadMessages, settle],
186
+ );
187
+
188
+ const sendMessage = useCallback(
189
+ async text => {
190
+ const body = String(text || '').trim();
191
+ if (!body || sending) return false;
192
+ if (customerChat) {
193
+ // Employees answer customers in CRM / Support; /ai only follows the AI here.
194
+ showError('Responda o cliente pelo CRM ou Suporte.');
195
+ return false;
196
+ }
197
+ // No AI for my company (or I'm in my ticket): the message goes to a ticket with the platform.
198
+ const ticketMode = myTicket || (!activeTaskId && !provider);
199
+ if (!ticketMode && !provider) {
200
+ showError('Nenhuma IA configurada para a empresa. Configure em Configurador → IA.');
201
+ return false;
202
+ }
203
+ setSending(true);
204
+ setMessages(prev => [...prev, {id: `local-${Date.now()}`, body, status: 'pending'}]);
205
+ try {
206
+ const res = await api.post('/mcp/chat', {
207
+ message: body,
208
+ ...(ticketMode ? {type: ticketType} : {provider}),
209
+ ...(activeTaskId ? {task_id: activeTaskId} : {}),
210
+ ...(companyId ? {company_id: companyId} : {}),
211
+ });
212
+ const taskId = Number(res?.task_id || 0);
213
+ if (taskId && res?.mode === 'ticket' && !res?.async) {
214
+ // Humans of the platform answer later; no AI reply to wait for.
215
+ if (taskId !== Number(activeTaskId)) setActiveTaskId(taskId);
216
+ else loadMessages(taskId, {silent: true});
217
+ scheduleTasksReload();
218
+ } else if (taskId) {
219
+ setPending(prev => ({...prev, [taskId]: prev[taskId] || 'pending'}));
220
+ armFallback(taskId);
221
+ if (taskId !== Number(activeTaskId)) setActiveTaskId(taskId);
222
+ else loadMessages(taskId, {silent: true});
223
+ scheduleTasksReload();
224
+ }
225
+ return true;
226
+ } catch (e) {
227
+ showError(e?.message || e?.error || 'Falha ao enviar mensagem');
228
+ setMessages(prev => prev.filter(m => !String(m.id).startsWith('local-')));
229
+ return false;
230
+ } finally {
231
+ setSending(false);
232
+ }
233
+ },
234
+ [activeTaskId, armFallback, companyId, customerChat, loadMessages, myTicket, provider, scheduleTasksReload, sending, showError, ticketType],
235
+ );
236
+
237
+ const takeOver = useCallback(
238
+ async type => {
239
+ if (!activeTaskId) return;
240
+ try {
241
+ await api.post('/mcp/chat/handoff', {task_id: activeTaskId, type, ...(companyId ? {company_id: companyId} : {})});
242
+ await Promise.all([loadTasks(), loadMessages(activeTaskId, {silent: true})]);
243
+ } catch (e) {
244
+ showError(e?.message || 'Falha ao transferir a conversa');
245
+ }
246
+ },
247
+ [activeTaskId, companyId, loadMessages, loadTasks, showError],
248
+ );
249
+
250
+ return {
251
+ companyId,
252
+ currentPeopleId,
253
+ providers,
254
+ provider,
255
+ setProvider,
256
+ tasks,
257
+ activeTask,
258
+ activeTaskId,
259
+ setActiveTaskId,
260
+ customerChat,
261
+ myTicket,
262
+ ticketType,
263
+ setTicketType,
264
+ messages,
265
+ loadingList,
266
+ loadingChat,
267
+ sending,
268
+ aiStatus: activeTaskId ? pending[activeTaskId] || null : null,
269
+ sendMessage,
270
+ takeOver,
271
+ startNewChat: () => {
272
+ setActiveTaskId(null);
273
+ setMessages([]);
274
+ },
275
+ };
276
+ }
@@ -82,7 +82,7 @@ const styles = StyleSheet.create({
82
82
  borderBottomColor: '#e2e8f0',
83
83
  },
84
84
 
85
- tabItem: { flex: 1, paddingVertical: 16, alignItems: 'center' },
85
+ tabItem: { flex: 1, minHeight: 40, justifyContent: 'center', alignItems: 'center' },
86
86
 
87
87
  tabActive: { borderBottomWidth: 3, borderBottomColor: colors.primary },
88
88
 
@@ -0,0 +1,51 @@
1
+ /*
2
+ * @agents Modal to put the company AI on a CRM/support ticket, with optional instructions.
3
+ */
4
+ import React, {useState} from 'react';
5
+ import {ActivityIndicator, Modal, Text, TextInput, TouchableOpacity, View} from 'react-native';
6
+ import styles from './tickets.styles';
7
+
8
+ export default function AssignAiModal({visible, ticketName, onCancel, onConfirm}) {
9
+ const [instructions, setInstructions] = useState('');
10
+ const [busy, setBusy] = useState(false);
11
+
12
+ const confirm = async () => {
13
+ setBusy(true);
14
+ try {
15
+ await onConfirm(instructions.trim());
16
+ setInstructions('');
17
+ } finally {
18
+ setBusy(false);
19
+ }
20
+ };
21
+
22
+ return (
23
+ <Modal visible={visible} transparent animationType="fade" onRequestClose={onCancel}>
24
+ <View style={styles.modalBackdrop}>
25
+ <View style={styles.modalCard}>
26
+ <Text style={styles.modalTitle}>Atribuir à IA</Text>
27
+ <Text style={styles.modalText}>
28
+ {`A IA vai falar com o cliente de "${ticketName || 'ticket'}" pelo WhatsApp ou e-mail do cadastro, `}
29
+ atualizar a etapa e devolver para a equipe quando precisar de uma pessoa.
30
+ </Text>
31
+ <TextInput
32
+ style={[styles.input, styles.modalInput]}
33
+ value={instructions}
34
+ onChangeText={setInstructions}
35
+ placeholder="Instruções (opcional): o que perguntar, qual oferta apresentar…"
36
+ placeholderTextColor="#8b98a5"
37
+ multiline
38
+ />
39
+ <View style={styles.modalActions}>
40
+ <TouchableOpacity style={styles.ghostBtn} onPress={onCancel} disabled={busy}>
41
+ <Text style={styles.ghostBtnText}>Cancelar</Text>
42
+ </TouchableOpacity>
43
+ <TouchableOpacity style={styles.primaryBtn} onPress={confirm} disabled={busy}>
44
+ {busy ? <ActivityIndicator color="#fff" /> : <Text style={styles.primaryBtnText}>Atribuir</Text>}
45
+ </TouchableOpacity>
46
+ </View>
47
+ </View>
48
+ </View>
49
+ </Modal>
50
+ );
51
+ }
@@ -0,0 +1,171 @@
1
+ /*
2
+ * @agents One customer ticket (ia triage, CRM or support): the full conversation, employee reply to the
3
+ * customer (public -> goes out through the ticket's WhatsApp/e-mail connection), internal notes (private),
4
+ * put the AI on the ticket or take it over. Live via websocket events.
5
+ */
6
+ import React, {useCallback, useEffect, useRef, useState} from 'react';
7
+ import {ActivityIndicator, FlatList, KeyboardAvoidingView, Platform, Text, TextInput, TouchableOpacity, View} from 'react-native';
8
+ import {useRoute} from '@react-navigation/native';
9
+ import {useStore} from '@store';
10
+ import useToastMessage from '../../hooks/useToastMessage';
11
+ import AssignAiModal from './AssignAiModal';
12
+ import useRealtimeReload from './useRealtimeReload';
13
+ import {assignAi, fetchTicket, fetchTicketMessages, postTicketMessage, takeOverTicket} from './ticketApi';
14
+ import styles from './tickets.styles';
15
+
16
+ const {idOf, conversationChannel, messageRole, stageLabel} = require('../mcp/mcpChatUtils');
17
+ const {personName} = require('./ticketUtils');
18
+
19
+ const CHANNEL_LABELS = {whatsapp: 'WhatsApp', email: 'E-mail', web: 'Site'};
20
+ const ROLE_STYLE = {customer: 'bubbleLeft', ai: 'bubbleAi', note: 'bubbleNote', staff: 'bubbleRight', me: 'bubbleRight'};
21
+
22
+ export default function TicketConversationPage() {
23
+ const route = useRoute();
24
+ const taskId = Number(route?.params?.taskId || 0);
25
+ const {showError} = useToastMessage();
26
+ const peopleStore = useStore('people');
27
+ const authStore = useStore('auth');
28
+ const companyId = idOf(peopleStore?.getters?.currentCompany || peopleStore?.getters?.mainCompany);
29
+ const currentPeopleId = idOf(authStore?.getters?.user?.people);
30
+
31
+ const [task, setTask] = useState(null);
32
+ const [messages, setMessages] = useState([]);
33
+ const [loading, setLoading] = useState(true);
34
+ const [draft, setDraft] = useState('');
35
+ const [mode, setMode] = useState('public');
36
+ const [sending, setSending] = useState(false);
37
+ const [assignOpen, setAssignOpen] = useState(false);
38
+ const listRef = useRef(null);
39
+
40
+ const load = useCallback(async () => {
41
+ if (!taskId) return;
42
+ try {
43
+ const [t, m] = await Promise.all([fetchTicket(taskId), fetchTicketMessages(taskId)]);
44
+ setTask(t);
45
+ setMessages(m);
46
+ } catch (e) {
47
+ showError(e?.message || 'Falha ao carregar o ticket');
48
+ } finally {
49
+ setLoading(false);
50
+ }
51
+ }, [taskId, showError]);
52
+
53
+ useEffect(() => {
54
+ load();
55
+ }, [load]);
56
+ const isThisTask = useCallback(evt => Number(evt.task_id) === taskId, [taskId]);
57
+ useRealtimeReload(load, {filter: isThisTask, delay: 200});
58
+
59
+ const send = async () => {
60
+ const body = draft.trim();
61
+ if (!body || sending) return;
62
+ setSending(true);
63
+ try {
64
+ await postTicketMessage(taskId, body, mode);
65
+ setDraft('');
66
+ await load();
67
+ } catch (e) {
68
+ showError(e?.message || 'Não foi possível enviar');
69
+ } finally {
70
+ setSending(false);
71
+ }
72
+ };
73
+
74
+ const takeOver = async type => {
75
+ try {
76
+ await takeOverTicket(taskId, companyId, type);
77
+ await load();
78
+ } catch (e) {
79
+ showError(e?.message || 'Não foi possível assumir');
80
+ }
81
+ };
82
+
83
+ const confirmAssign = async instructions => {
84
+ try {
85
+ await assignAi(taskId, companyId, instructions);
86
+ setAssignOpen(false);
87
+ await load();
88
+ } catch (e) {
89
+ showError(e?.message || 'Não foi possível atribuir a IA');
90
+ }
91
+ };
92
+
93
+ if (loading) return <ActivityIndicator style={styles.spinner} />;
94
+ if (!task) return <Text style={styles.emptyText}>Ticket não encontrado.</Text>;
95
+
96
+ const channel = CHANNEL_LABELS[conversationChannel(task)];
97
+ const renderMessage = ({item}) => {
98
+ const role = messageRole(item, {companyId, task, currentPeopleId});
99
+ const author = role === 'ai' ? 'IA' : role === 'note' ? 'Nota interna' : personName(item.registeredBy);
100
+ const isNote = item.visibility === 'private' && role !== 'ai';
101
+ return (
102
+ <View style={[styles.bubble, styles[isNote ? 'bubbleNote' : ROLE_STYLE[role]]]}>
103
+ {author ? <Text style={styles.bubbleAuthor}>{isNote && role !== 'note' ? `${author} · interno` : author}</Text> : null}
104
+ <Text style={styles.bubbleText}>{item.body}</Text>
105
+ {item.createdAt ? <Text style={styles.bubbleMeta}>{new Date(item.createdAt).toLocaleString('pt-BR')}</Text> : null}
106
+ </View>
107
+ );
108
+ };
109
+
110
+ return (
111
+ <KeyboardAvoidingView style={styles.root} behavior={Platform.OS === 'ios' ? 'padding' : undefined} keyboardVerticalOffset={80}>
112
+ <View style={styles.header}>
113
+ <View style={styles.headerText}>
114
+ <Text style={styles.title} numberOfLines={1}>{task.name || `Ticket #${taskId}`}</Text>
115
+ <Text style={styles.subtitle}>
116
+ {[personName(task.client), stageLabel(task), task.taskStatus?.status, channel].filter(Boolean).join(' · ')}
117
+ </Text>
118
+ </View>
119
+ </View>
120
+ <View style={styles.aiBar}>
121
+ <Text style={styles.aiBarText}>
122
+ {task.aiAgent ? 'A IA está atendendo este cliente.' : 'Atendimento humano. Você pode colocar a IA para conduzir.'}
123
+ </Text>
124
+ {task.aiAgent
125
+ ? (task.type === 'ia' ? ['relationship', 'support'] : [task.type]).map(type => (
126
+ <TouchableOpacity key={type} style={styles.ghostBtn} onPress={() => takeOver(type)}>
127
+ <Text style={styles.ghostBtnText}>{task.type === 'ia' ? `Assumir (${stageLabel({type})})` : 'Assumir'}</Text>
128
+ </TouchableOpacity>
129
+ ))
130
+ : (
131
+ <TouchableOpacity style={styles.ghostBtn} onPress={() => setAssignOpen(true)}>
132
+ <Text style={styles.ghostBtnText}>Atribuir IA</Text>
133
+ </TouchableOpacity>
134
+ )}
135
+ </View>
136
+ <FlatList
137
+ ref={listRef}
138
+ data={messages}
139
+ keyExtractor={item => String(item.id || item['@id'])}
140
+ renderItem={renderMessage}
141
+ contentContainerStyle={styles.messages}
142
+ onContentSizeChange={() => listRef.current?.scrollToEnd?.({animated: true})}
143
+ ListEmptyComponent={<Text style={styles.emptyText}>Sem mensagens ainda.</Text>}
144
+ />
145
+ <View style={styles.composer}>
146
+ <View style={styles.modeRow}>
147
+ <TouchableOpacity style={[styles.modeChip, mode === 'public' && styles.modeChipActive]} onPress={() => setMode('public')}>
148
+ <Text style={styles.modeChipText}>{`Responder cliente${channel ? ` (${channel})` : ''}`}</Text>
149
+ </TouchableOpacity>
150
+ <TouchableOpacity style={[styles.modeChip, mode === 'private' && styles.modeChipNote]} onPress={() => setMode('private')}>
151
+ <Text style={styles.modeChipText}>Nota interna</Text>
152
+ </TouchableOpacity>
153
+ </View>
154
+ <View style={styles.composerRow}>
155
+ <TextInput
156
+ style={styles.input}
157
+ value={draft}
158
+ onChangeText={setDraft}
159
+ placeholder={mode === 'public' ? 'Mensagem para o cliente (a IA sai da conversa)…' : 'Nota visível só para a equipe…'}
160
+ placeholderTextColor="#8b98a5"
161
+ multiline
162
+ />
163
+ <TouchableOpacity style={styles.primaryBtn} onPress={send} disabled={sending || !draft.trim()}>
164
+ {sending ? <ActivityIndicator color="#fff" /> : <Text style={styles.primaryBtnText}>Enviar</Text>}
165
+ </TouchableOpacity>
166
+ </View>
167
+ </View>
168
+ <AssignAiModal visible={assignOpen} ticketName={task.name} onCancel={() => setAssignOpen(false)} onConfirm={confirmAssign} />
169
+ </KeyboardAvoidingView>
170
+ );
171
+ }