@controleonline/ui-crm 1.0.63 → 1.0.67
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/.release/rc-manifest.json +6 -6
- package/package.json +1 -1
- package/src/react/pages/crm/components/CrmHeader.js +6 -0
- package/src/react/pages/crm/index.js +1 -0
- package/src/react/pages/mcp/McpPage.js +79 -230
- package/src/react/pages/mcp/McpPage.styles.js +16 -0
- package/src/react/pages/mcp/mcpChatUtils.js +123 -0
- package/src/react/pages/mcp/useMcpChat.js +276 -0
- package/src/react/pages/tickets/AssignAiModal.js +51 -0
- package/src/react/pages/tickets/TicketConversationPage.js +171 -0
- package/src/react/pages/tickets/TicketFunnelPage.js +141 -0
- package/src/react/pages/tickets/ticketApi.js +38 -0
- package/src/react/pages/tickets/ticketUtils.js +81 -0
- package/src/react/pages/tickets/tickets.styles.js +61 -0
- package/src/react/pages/tickets/useRealtimeReload.js +28 -0
- package/src/react/router/routes.js +44 -0
- package/src/tests/react/pages/mcp/mcpChatUtils.test.js +73 -0
- package/src/tests/react/pages/tickets/ticketUtils.test.js +43 -0
|
@@ -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
|
+
// The user's conversations: chats with the company AI + tickets with the platform team.
|
|
78
|
+
const [internal, tickets] = await Promise.all([
|
|
79
|
+
api.fetch('/tasks', {params: {...base, type: 'ia', ...(currentPeopleId ? {registeredBy: `/people/${currentPeopleId}`} : {})}}),
|
|
80
|
+
currentPeopleId
|
|
81
|
+
? api.fetch('/tasks', {params: {client: `/people/${currentPeopleId}`, announce: 'via:ai', 'order[alterDate]': 'desc', itemsPerPage: 50}})
|
|
82
|
+
: Promise.resolve([]),
|
|
83
|
+
]);
|
|
84
|
+
setTasks(mergeConversations([toItems(internal), toItems(tickets)], currentPeopleId));
|
|
85
|
+
} catch (e) {
|
|
86
|
+
showError(e?.message || 'Falha ao listar conversas');
|
|
87
|
+
} finally {
|
|
88
|
+
setLoadingList(false);
|
|
89
|
+
}
|
|
90
|
+
}, [companyId, currentPeopleId, showError]);
|
|
91
|
+
|
|
92
|
+
const scheduleTasksReload = useCallback(() => {
|
|
93
|
+
clearTimeout(listTimer.current);
|
|
94
|
+
listTimer.current = setTimeout(loadTasks, LIST_DEBOUNCE_MS);
|
|
95
|
+
}, [loadTasks]);
|
|
96
|
+
|
|
97
|
+
const loadMessages = useCallback(
|
|
98
|
+
async (taskId, {silent = false} = {}) => {
|
|
99
|
+
if (!taskId) {
|
|
100
|
+
setMessages([]);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (!silent) setLoadingChat(true);
|
|
104
|
+
try {
|
|
105
|
+
const res = await api.fetch('/task_interations', {
|
|
106
|
+
params: {'task.id': taskId, type: 'comment', 'order[id]': 'asc', itemsPerPage: 200},
|
|
107
|
+
});
|
|
108
|
+
// Ignore a late response for a chat the user already left.
|
|
109
|
+
if (Number(activeRef.current) === Number(taskId)) setMessages(toItems(res));
|
|
110
|
+
} catch (e) {
|
|
111
|
+
showError(e?.message || 'Falha ao carregar mensagens');
|
|
112
|
+
} finally {
|
|
113
|
+
if (!silent) setLoadingChat(false);
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
[showError],
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
useEffect(() => {
|
|
120
|
+
loadProviders();
|
|
121
|
+
loadTasks();
|
|
122
|
+
}, [loadProviders, loadTasks]);
|
|
123
|
+
|
|
124
|
+
useEffect(() => {
|
|
125
|
+
loadMessages(activeTaskId);
|
|
126
|
+
}, [activeTaskId, loadMessages]);
|
|
127
|
+
|
|
128
|
+
// Platform staff replies to my ticket are not pushed to my devices: refresh while it is open.
|
|
129
|
+
useEffect(() => {
|
|
130
|
+
if (!myTicket || !activeTaskId) return undefined;
|
|
131
|
+
const timer = setInterval(() => loadMessages(activeTaskId, {silent: true}), TICKET_REFRESH_MS);
|
|
132
|
+
return () => clearInterval(timer);
|
|
133
|
+
}, [myTicket, activeTaskId, loadMessages]);
|
|
134
|
+
|
|
135
|
+
useEffect(
|
|
136
|
+
() => () => {
|
|
137
|
+
clearTimeout(listTimer.current);
|
|
138
|
+
Object.values(fallbackTimers.current).forEach(clearTimeout);
|
|
139
|
+
},
|
|
140
|
+
[],
|
|
141
|
+
);
|
|
142
|
+
|
|
143
|
+
const settle = useCallback(taskId => {
|
|
144
|
+
clearTimeout(fallbackTimers.current[taskId]);
|
|
145
|
+
delete fallbackTimers.current[taskId];
|
|
146
|
+
setPending(prev => {
|
|
147
|
+
const next = {...prev};
|
|
148
|
+
delete next[taskId];
|
|
149
|
+
return next;
|
|
150
|
+
});
|
|
151
|
+
}, []);
|
|
152
|
+
|
|
153
|
+
// Realtime: consume every new event since the last cursor (several can arrive in one batch).
|
|
154
|
+
useEffect(() => {
|
|
155
|
+
const {events, nextIndex} = extractChatEvents(wsMessages, wsCursor.current);
|
|
156
|
+
wsCursor.current = nextIndex;
|
|
157
|
+
if (!events.length) return;
|
|
158
|
+
|
|
159
|
+
let reloadActive = false;
|
|
160
|
+
events.forEach(evt => {
|
|
161
|
+
if (companyId && evt.companyId && Number(evt.companyId) !== Number(companyId)) return;
|
|
162
|
+
const taskId = Number(evt.task_id || 0);
|
|
163
|
+
if (!taskId) return;
|
|
164
|
+
if (evt.status === 'processing') {
|
|
165
|
+
setPending(prev => ({...prev, [taskId]: 'processing'}));
|
|
166
|
+
} else if (evt.event === 'mcp_chat_reply') {
|
|
167
|
+
settle(taskId);
|
|
168
|
+
if (evt.status === 'error') showError(evt.body || 'A IA não conseguiu responder.');
|
|
169
|
+
}
|
|
170
|
+
if (taskId === Number(activeRef.current) && evt.status !== 'processing') reloadActive = true;
|
|
171
|
+
});
|
|
172
|
+
if (reloadActive) loadMessages(activeRef.current, {silent: true});
|
|
173
|
+
scheduleTasksReload();
|
|
174
|
+
}, [wsMessages, companyId, loadMessages, scheduleTasksReload, settle, showError]);
|
|
175
|
+
|
|
176
|
+
const armFallback = useCallback(
|
|
177
|
+
taskId => {
|
|
178
|
+
clearTimeout(fallbackTimers.current[taskId]);
|
|
179
|
+
fallbackTimers.current[taskId] = setTimeout(() => {
|
|
180
|
+
settle(taskId);
|
|
181
|
+
if (Number(activeRef.current) === Number(taskId)) loadMessages(taskId, {silent: true});
|
|
182
|
+
}, REPLY_FALLBACK_MS);
|
|
183
|
+
},
|
|
184
|
+
[loadMessages, settle],
|
|
185
|
+
);
|
|
186
|
+
|
|
187
|
+
const sendMessage = useCallback(
|
|
188
|
+
async text => {
|
|
189
|
+
const body = String(text || '').trim();
|
|
190
|
+
if (!body || sending) return false;
|
|
191
|
+
if (customerChat) {
|
|
192
|
+
// Employees answer customers in CRM / Support; /ai only follows the AI here.
|
|
193
|
+
showError('Responda o cliente pelo CRM ou Suporte.');
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
// No AI for my company (or I'm in my ticket): the message goes to a ticket with the platform.
|
|
197
|
+
const ticketMode = myTicket || (!activeTaskId && !provider);
|
|
198
|
+
if (!ticketMode && !provider) {
|
|
199
|
+
showError('Nenhuma IA configurada para a empresa. Configure em Configurador → IA.');
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
setSending(true);
|
|
203
|
+
setMessages(prev => [...prev, {id: `local-${Date.now()}`, body, status: 'pending'}]);
|
|
204
|
+
try {
|
|
205
|
+
const res = await api.post('/mcp/chat', {
|
|
206
|
+
message: body,
|
|
207
|
+
...(ticketMode ? {type: ticketType} : {provider}),
|
|
208
|
+
...(activeTaskId ? {task_id: activeTaskId} : {}),
|
|
209
|
+
...(companyId ? {company_id: companyId} : {}),
|
|
210
|
+
});
|
|
211
|
+
const taskId = Number(res?.task_id || 0);
|
|
212
|
+
if (taskId && res?.mode === 'ticket' && !res?.async) {
|
|
213
|
+
// Humans of the platform answer later; no AI reply to wait for.
|
|
214
|
+
if (taskId !== Number(activeTaskId)) setActiveTaskId(taskId);
|
|
215
|
+
else loadMessages(taskId, {silent: true});
|
|
216
|
+
scheduleTasksReload();
|
|
217
|
+
} else if (taskId) {
|
|
218
|
+
setPending(prev => ({...prev, [taskId]: prev[taskId] || 'pending'}));
|
|
219
|
+
armFallback(taskId);
|
|
220
|
+
if (taskId !== Number(activeTaskId)) setActiveTaskId(taskId);
|
|
221
|
+
else loadMessages(taskId, {silent: true});
|
|
222
|
+
scheduleTasksReload();
|
|
223
|
+
}
|
|
224
|
+
return true;
|
|
225
|
+
} catch (e) {
|
|
226
|
+
showError(e?.message || e?.error || 'Falha ao enviar mensagem');
|
|
227
|
+
setMessages(prev => prev.filter(m => !String(m.id).startsWith('local-')));
|
|
228
|
+
return false;
|
|
229
|
+
} finally {
|
|
230
|
+
setSending(false);
|
|
231
|
+
}
|
|
232
|
+
},
|
|
233
|
+
[activeTaskId, armFallback, companyId, customerChat, loadMessages, myTicket, provider, scheduleTasksReload, sending, showError, ticketType],
|
|
234
|
+
);
|
|
235
|
+
|
|
236
|
+
const takeOver = useCallback(
|
|
237
|
+
async type => {
|
|
238
|
+
if (!activeTaskId) return;
|
|
239
|
+
try {
|
|
240
|
+
await api.post('/mcp/chat/handoff', {task_id: activeTaskId, type, ...(companyId ? {company_id: companyId} : {})});
|
|
241
|
+
await Promise.all([loadTasks(), loadMessages(activeTaskId, {silent: true})]);
|
|
242
|
+
} catch (e) {
|
|
243
|
+
showError(e?.message || 'Falha ao transferir a conversa');
|
|
244
|
+
}
|
|
245
|
+
},
|
|
246
|
+
[activeTaskId, companyId, loadMessages, loadTasks, showError],
|
|
247
|
+
);
|
|
248
|
+
|
|
249
|
+
return {
|
|
250
|
+
companyId,
|
|
251
|
+
currentPeopleId,
|
|
252
|
+
providers,
|
|
253
|
+
provider,
|
|
254
|
+
setProvider,
|
|
255
|
+
tasks,
|
|
256
|
+
activeTask,
|
|
257
|
+
activeTaskId,
|
|
258
|
+
setActiveTaskId,
|
|
259
|
+
customerChat,
|
|
260
|
+
myTicket,
|
|
261
|
+
hasAi: providers.length > 0,
|
|
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
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* @agents Kanban funnel for customer tickets (type relationship = CRM, support = Suporte).
|
|
3
|
+
* First column "Triagem IA" = customer conversations the AI has not classified yet.
|
|
4
|
+
* Cards: move stage, put the AI on the ticket, open the conversation. Live via websocket events.
|
|
5
|
+
*/
|
|
6
|
+
import React, {useCallback, useEffect, useMemo, useState} from 'react';
|
|
7
|
+
import {ActivityIndicator, ScrollView, Text, TextInput, TouchableOpacity, View} from 'react-native';
|
|
8
|
+
import {useNavigation} 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, fetchStatuses, fetchTickets, fetchTriage, moveTicket} from './ticketApi';
|
|
14
|
+
import styles from './tickets.styles';
|
|
15
|
+
|
|
16
|
+
const {idOf, conversationChannel} = require('../mcp/mcpChatUtils');
|
|
17
|
+
const {TICKET_TYPES, buildColumns, neighbourStatus, personName, timeAgo} = require('./ticketUtils');
|
|
18
|
+
|
|
19
|
+
const CHANNEL_LABELS = {whatsapp: 'WhatsApp', email: 'E-mail', web: 'Site'};
|
|
20
|
+
|
|
21
|
+
const TicketCard = ({task, columns, onMove, onAssign, onOpen}) => {
|
|
22
|
+
const previous = neighbourStatus(columns, task, -1);
|
|
23
|
+
const next = neighbourStatus(columns, task, 1);
|
|
24
|
+
const channel = conversationChannel(task);
|
|
25
|
+
return (
|
|
26
|
+
<TouchableOpacity style={styles.card} onPress={() => onOpen(task)}>
|
|
27
|
+
<Text style={styles.cardTitle} numberOfLines={2}>{task.name || `#${idOf(task)}`}</Text>
|
|
28
|
+
<Text style={styles.cardMeta} numberOfLines={1}>
|
|
29
|
+
{[personName(task.client), timeAgo(task.alterDate)].filter(Boolean).join(' · ')}
|
|
30
|
+
</Text>
|
|
31
|
+
<View style={styles.badges}>
|
|
32
|
+
{task.aiAgent ? <View style={[styles.badge, styles.badgeAi]}><Text style={styles.badgeText}>IA atendendo</Text></View> : null}
|
|
33
|
+
{CHANNEL_LABELS[channel] ? <View style={styles.badge}><Text style={styles.badgeText}>{CHANNEL_LABELS[channel]}</Text></View> : null}
|
|
34
|
+
</View>
|
|
35
|
+
<View style={styles.cardActions}>
|
|
36
|
+
{previous ? <TouchableOpacity style={styles.iconBtn} onPress={() => onMove(task, previous)}><Text style={styles.iconBtnText}>◀</Text></TouchableOpacity> : null}
|
|
37
|
+
{next ? <TouchableOpacity style={styles.iconBtn} onPress={() => onMove(task, next)}><Text style={styles.iconBtnText}>▶</Text></TouchableOpacity> : null}
|
|
38
|
+
{!task.aiAgent ? <TouchableOpacity style={styles.iconBtn} onPress={() => onAssign(task)}><Text style={styles.iconBtnText}>Atribuir IA</Text></TouchableOpacity> : null}
|
|
39
|
+
</View>
|
|
40
|
+
</TouchableOpacity>
|
|
41
|
+
);
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export default function TicketFunnelPage({type = 'relationship'}) {
|
|
45
|
+
const navigation = useNavigation();
|
|
46
|
+
const {showError, showSuccess} = useToastMessage();
|
|
47
|
+
const peopleStore = useStore('people');
|
|
48
|
+
const companyId = idOf(peopleStore?.getters?.currentCompany || peopleStore?.getters?.mainCompany);
|
|
49
|
+
const meta = TICKET_TYPES[type] || TICKET_TYPES.relationship;
|
|
50
|
+
|
|
51
|
+
const [statuses, setStatuses] = useState([]);
|
|
52
|
+
const [tickets, setTickets] = useState([]);
|
|
53
|
+
const [triage, setTriage] = useState([]);
|
|
54
|
+
const [loading, setLoading] = useState(true);
|
|
55
|
+
const [search, setSearch] = useState('');
|
|
56
|
+
const [assigning, setAssigning] = useState(null);
|
|
57
|
+
|
|
58
|
+
const load = useCallback(async () => {
|
|
59
|
+
if (!companyId) return;
|
|
60
|
+
try {
|
|
61
|
+
const [s, t, tr] = await Promise.all([fetchStatuses(type), fetchTickets(type, companyId), fetchTriage(companyId)]);
|
|
62
|
+
setStatuses(s);
|
|
63
|
+
setTickets(t);
|
|
64
|
+
setTriage(tr);
|
|
65
|
+
} catch (e) {
|
|
66
|
+
showError(e?.message || 'Falha ao carregar o funil');
|
|
67
|
+
} finally {
|
|
68
|
+
setLoading(false);
|
|
69
|
+
}
|
|
70
|
+
}, [companyId, type, showError]);
|
|
71
|
+
|
|
72
|
+
useEffect(() => {
|
|
73
|
+
load();
|
|
74
|
+
}, [load]);
|
|
75
|
+
useRealtimeReload(load);
|
|
76
|
+
|
|
77
|
+
const columns = useMemo(() => {
|
|
78
|
+
const q = search.trim().toLowerCase();
|
|
79
|
+
const match = t => !q || `${t.name || ''} ${personName(t.client)}`.toLowerCase().includes(q);
|
|
80
|
+
return buildColumns(statuses, tickets.filter(match), triage.filter(match));
|
|
81
|
+
}, [statuses, tickets, triage, search]);
|
|
82
|
+
|
|
83
|
+
const move = async (task, status) => {
|
|
84
|
+
setTickets(prev => prev.map(t => (idOf(t) === idOf(task) ? {...t, taskStatus: status} : t)));
|
|
85
|
+
try {
|
|
86
|
+
await moveTicket(task, status);
|
|
87
|
+
} catch (e) {
|
|
88
|
+
showError(e?.message || 'Não foi possível mover');
|
|
89
|
+
load();
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const confirmAssign = async instructions => {
|
|
94
|
+
try {
|
|
95
|
+
await assignAi(idOf(assigning), companyId, instructions);
|
|
96
|
+
showSuccess('IA atribuída. Ela fará o primeiro contato com o cliente.');
|
|
97
|
+
setAssigning(null);
|
|
98
|
+
load();
|
|
99
|
+
} catch (e) {
|
|
100
|
+
showError(e?.message || 'Não foi possível atribuir a IA');
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const open = task => navigation.navigate('TicketConversation', {taskId: idOf(task)});
|
|
105
|
+
|
|
106
|
+
return (
|
|
107
|
+
<View style={styles.root}>
|
|
108
|
+
<View style={styles.header}>
|
|
109
|
+
<View style={styles.headerText}>
|
|
110
|
+
<Text style={styles.title}>{meta.title}</Text>
|
|
111
|
+
<Text style={styles.subtitle}>{`${tickets.length} tickets · ${triage.length} em triagem pela IA`}</Text>
|
|
112
|
+
</View>
|
|
113
|
+
<TextInput style={styles.search} value={search} onChangeText={setSearch} placeholder="Buscar cliente ou título" placeholderTextColor="#8b98a5" />
|
|
114
|
+
</View>
|
|
115
|
+
{loading ? (
|
|
116
|
+
<ActivityIndicator style={styles.spinner} />
|
|
117
|
+
) : (
|
|
118
|
+
<ScrollView horizontal style={styles.board} contentContainerStyle={styles.boardContent}>
|
|
119
|
+
{columns.map(column => (
|
|
120
|
+
<View key={column.key} style={[styles.column, {borderTopColor: column.color}]}>
|
|
121
|
+
<View style={styles.columnHeader}>
|
|
122
|
+
<Text style={styles.columnTitle}>{column.title}</Text>
|
|
123
|
+
<Text style={styles.columnCount}>{column.tasks.length}</Text>
|
|
124
|
+
</View>
|
|
125
|
+
<ScrollView style={styles.columnBody}>
|
|
126
|
+
{column.tasks.length === 0 ? <Text style={styles.emptyText}>{meta.empty}</Text> : null}
|
|
127
|
+
{column.tasks.map(task => (
|
|
128
|
+
<TicketCard key={String(idOf(task))} task={task} columns={columns} onMove={move} onAssign={setAssigning} onOpen={open} />
|
|
129
|
+
))}
|
|
130
|
+
</ScrollView>
|
|
131
|
+
</View>
|
|
132
|
+
))}
|
|
133
|
+
</ScrollView>
|
|
134
|
+
)}
|
|
135
|
+
<AssignAiModal visible={Boolean(assigning)} ticketName={assigning?.name} onCancel={() => setAssigning(null)} onConfirm={confirmAssign} />
|
|
136
|
+
</View>
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export const CrmFunnelPage = () => <TicketFunnelPage type="relationship" />;
|
|
141
|
+
export const SupportFunnelPage = () => <TicketFunnelPage type="support" />;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* @agents API calls shared by funnels and ticket screens.
|
|
3
|
+
*/
|
|
4
|
+
import {api} from '@controleonline/ui-common/src/api';
|
|
5
|
+
|
|
6
|
+
const {idOf} = require('../mcp/mcpChatUtils');
|
|
7
|
+
|
|
8
|
+
export const toItems = res => {
|
|
9
|
+
const items = res?.member || res?.['hydra:member'] || res || [];
|
|
10
|
+
return Array.isArray(items) ? items : [];
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export const fetchStatuses = async type => toItems(await api.fetch('/statuses', {params: {context: type, itemsPerPage: 100}}));
|
|
14
|
+
|
|
15
|
+
export const fetchTickets = async (type, companyId) =>
|
|
16
|
+
toItems(await api.fetch('/tasks', {params: {type, provider: `/people/${companyId}`, 'order[alterDate]': 'desc', itemsPerPage: 300}}));
|
|
17
|
+
|
|
18
|
+
// Customer conversations the AI is still triaging (internal /ai chats are filtered out by the caller).
|
|
19
|
+
export const fetchTriage = async companyId =>
|
|
20
|
+
toItems(await api.fetch('/tasks', {params: {type: 'ia', provider: `/people/${companyId}`, 'exists[aiAgent]': true, itemsPerPage: 100}}));
|
|
21
|
+
|
|
22
|
+
export const fetchTicket = taskId => api.fetch(`/tasks/${taskId}`);
|
|
23
|
+
|
|
24
|
+
export const fetchTicketMessages = async taskId =>
|
|
25
|
+
toItems(await api.fetch('/task_interations', {params: {'task.id': taskId, type: 'comment', 'order[id]': 'asc', itemsPerPage: 300}}));
|
|
26
|
+
|
|
27
|
+
export const moveTicket = (task, status) =>
|
|
28
|
+
api.put(`/tasks/${idOf(task)}`, {taskStatus: status?.['@id'] || `/statuses/${idOf(status)}`});
|
|
29
|
+
|
|
30
|
+
/** public = goes to the customer through the ticket's connection; private = internal note. */
|
|
31
|
+
export const postTicketMessage = (taskId, body, visibility) =>
|
|
32
|
+
api.post('/task_interations', {task: `/tasks/${taskId}`, body, type: 'comment', visibility});
|
|
33
|
+
|
|
34
|
+
export const assignAi = (taskId, companyId, instructions) =>
|
|
35
|
+
api.post('/mcp/chat/assign', {task_id: taskId, company_id: companyId, instructions});
|
|
36
|
+
|
|
37
|
+
export const takeOverTicket = (taskId, companyId, type) =>
|
|
38
|
+
api.post('/mcp/chat/handoff', {task_id: taskId, company_id: companyId, type});
|