@controleonline/ui-crm 1.0.63 → 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.
@@ -1,13 +1,14 @@
1
1
  {
2
- "version": "1.0.57",
2
+ "version": "1.0.64",
3
3
  "rc": 1,
4
- "branch": "rc/1.0.57-rc.1",
5
- "baseMaster": "1fb0e0b679bc9845eb00abf31b7a476d9a3d4921",
4
+ "branch": "rc/1.0.64-rc.1",
5
+ "baseMaster": "98a8048b0e9eeac415f323f70177a10ff5b5d1ac",
6
6
  "tasks": [
7
- 1322
7
+ 64,
8
+ 1447
8
9
  ],
9
10
  "frozen": true,
10
11
  "repositories": {
11
- "ControleOnline/ui-crm": "1d4360ffaf5f74e4e34147a8b284d50fbc6ce7d5"
12
+ "ControleOnline/ui-crm": "7fe6fca7d6f8d4500e2833af7449c5257bab9480"
12
13
  }
13
14
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@controleonline/ui-crm",
3
- "version": "1.0.63",
3
+ "version": "1.0.65",
4
4
  "author": "ControleOnline",
5
5
  "description": "ControleOnline CRM Quasar UI Component",
6
6
  "license": "MIT",
@@ -12,6 +12,7 @@ const CrmHeader = ({
12
12
  getStatusFilterKey,
13
13
  getStatusFilterLabel,
14
14
  onAddOpportunity,
15
+ onOpenFunnel,
15
16
  searchText,
16
17
  selectedStatusFilterKey,
17
18
  setSearchText,
@@ -39,6 +40,11 @@ const CrmHeader = ({
39
40
  </TouchableOpacity>
40
41
  )}
41
42
  </View>
43
+ {onOpenFunnel ? (
44
+ <TouchableOpacity style={styles.addButton} onPress={onOpenFunnel} accessibilityLabel="Funil">
45
+ <Icon name="columns" size={18} color="#FFFFFF" />
46
+ </TouchableOpacity>
47
+ ) : null}
42
48
  <TouchableOpacity style={styles.addButton} onPress={onAddOpportunity}>
43
49
  <IconAdd name="add" size={24} color="#FFFFFF" />
44
50
  </TouchableOpacity>
@@ -85,6 +85,7 @@ export default function CrmIndex() {
85
85
  getStatusFilterKey={data.getStatusFilterKey}
86
86
  getStatusFilterLabel={data.getStatusFilterLabel}
87
87
  onAddOpportunity={forms.openAddOpportunity}
88
+ onOpenFunnel={() => navigation.navigate('CrmFunnel')}
88
89
  searchText={data.searchText}
89
90
  selectedStatusFilterKey={data.selectedStatusFilterKey}
90
91
  setSearchText={data.setSearchText}
@@ -1,7 +1,8 @@
1
1
  /*
2
- * @agents MCP AI chat (Task type=ia). Keep under 500 lines; API via /mcp/chat*.
2
+ * @agents /ai: employee chats with the company AI (internal data via MCP) and follows the customer
3
+ * conversations the AI is handling now. Employees answer customers in CRM / Support. Logic: useMcpChat.
3
4
  */
4
- import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
5
+ import React, {useMemo, useRef, useState} from 'react';
5
6
  import {
6
7
  ActivityIndicator,
7
8
  FlatList,
@@ -13,288 +14,172 @@ import {
13
14
  TouchableOpacity,
14
15
  View,
15
16
  } from 'react-native';
16
- import {useStore} from '@store';
17
- import {api} from '@controleonline/ui-common/src/api';
18
- import useToastMessage from '../../hooks/useToastMessage';
17
+ import useMcpChat from './useMcpChat';
19
18
  import styles from './McpPage.styles';
20
19
 
21
- const PROVIDER_LABELS = {
22
- grok: 'Grok',
23
- openai: 'Codex / OpenAI',
24
- gemini: 'Gemini',
25
- claude: 'Claude',
20
+ const {idOf, isCustomerConversation, conversationChannel, stageLabel, messageRole} = require('./mcpChatUtils');
21
+
22
+ const PROVIDER_LABELS = {grok: 'Grok', openai: 'Codex / OpenAI', gemini: 'Gemini', claude: 'Claude'};
23
+ const CHANNEL_LABELS = {whatsapp: 'WhatsApp', email: 'E-mail', web: 'Site', ai: 'IA'};
24
+ const ROLE_LABELS = {ai: 'IA', note: 'Nota interna', customer: 'Cliente', staff: 'Equipe', me: null};
25
+
26
+ const TaskRow = ({item, selected, onPress}) => {
27
+ const customer = isCustomerConversation(item);
28
+ return (
29
+ <TouchableOpacity onPress={onPress} style={[styles.taskRow, selected && styles.taskRowActive]}>
30
+ <Text numberOfLines={1} style={styles.taskRowText}>
31
+ {item.name || `Conversa #${idOf(item)}`}
32
+ </Text>
33
+ {customer ? (
34
+ <Text style={styles.taskRowMeta}>
35
+ {CHANNEL_LABELS[conversationChannel(item)]} · {stageLabel(item)}
36
+ </Text>
37
+ ) : null}
38
+ </TouchableOpacity>
39
+ );
26
40
  };
27
41
 
28
42
  export default function McpPage() {
29
- const {showError, showSuccess} = useToastMessage();
30
- const peopleStore = useStore('people');
31
- const company =
32
- peopleStore?.getters?.currentCompany ||
33
- peopleStore?.getters?.mainCompany ||
34
- null;
35
- const companyId = company?.id || company?.['@id']?.split('/').pop() || null;
36
-
37
- const [providers, setProviders] = useState([]);
38
- const [provider, setProvider] = useState(null);
39
- const [tasks, setTasks] = useState([]);
40
- const [activeTaskId, setActiveTaskId] = useState(null);
41
- const [messages, setMessages] = useState([]);
43
+ const chat = useMcpChat();
42
44
  const [draft, setDraft] = useState('');
43
- const [loadingList, setLoadingList] = useState(true);
44
- const [loadingChat, setLoadingChat] = useState(false);
45
- const [sending, setSending] = useState(false);
46
45
  const listRef = useRef(null);
47
46
 
48
- const companyQuery = useMemo(
49
- () => (companyId ? {company_id: Number(companyId)} : {}),
50
- [companyId],
51
- );
52
-
53
- const loadProviders = useCallback(async () => {
54
- try {
55
- const res = await api.fetch('/mcp/chat/providers', {params: companyQuery});
56
- const list = res?.providers || res?.member || res || [];
57
- const arr = Array.isArray(list) ? list : [];
58
- setProviders(arr);
59
- const enabled = arr.find(p => p.enabled || p.has_key);
60
- setProvider(prev => prev || enabled?.provider || enabled?.id || enabled?.name || null);
61
- } catch (e) {
62
- showError(e?.message || 'Falha ao carregar providers de IA');
63
- }
64
- }, [companyQuery, showError]);
65
-
66
- const loadTasks = useCallback(async () => {
67
- setLoadingList(true);
68
- try {
69
- const params = {
70
- type: 'ia',
71
- order: {alterDate: 'desc'},
72
- itemsPerPage: 50,
73
- };
74
- if (companyId) {
75
- params.provider = `/people/${companyId}`;
76
- }
77
- const res = await api.fetch('/tasks', {params});
78
- const items = res?.member || res?.['hydra:member'] || res || [];
79
- setTasks(Array.isArray(items) ? items : []);
80
- } catch (e) {
81
- showError(e?.message || 'Falha ao listar chats');
82
- } finally {
83
- setLoadingList(false);
84
- }
85
- }, [companyId, showError]);
86
-
87
- const loadMessages = useCallback(
88
- async taskId => {
89
- if (!taskId) {
90
- setMessages([]);
91
- return;
92
- }
93
- setLoadingChat(true);
94
- try {
95
- const res = await api.fetch('/task_interations', {
96
- params: {
97
- 'task.id': taskId,
98
- type: 'comment',
99
- order: {id: 'asc'},
100
- itemsPerPage: 100,
101
- },
102
- });
103
- const items = res?.member || res?.['hydra:member'] || res || [];
104
- setMessages(Array.isArray(items) ? items : []);
105
- } catch (e) {
106
- showError(e?.message || 'Falha ao carregar mensagens');
107
- } finally {
108
- setLoadingChat(false);
109
- }
110
- },
111
- [showError],
112
- );
113
-
114
- useEffect(() => {
115
- loadProviders();
116
- loadTasks();
117
- }, [loadProviders, loadTasks]);
118
-
119
- useEffect(() => {
120
- loadMessages(activeTaskId);
121
- }, [activeTaskId, loadMessages]);
122
-
123
- const selectTask = task => {
124
- const id = task?.id || task?.['@id']?.split('/').pop();
125
- setActiveTaskId(id ? Number(id) : null);
126
- };
127
-
128
- const startNewChat = () => {
129
- setActiveTaskId(null);
130
- setMessages([]);
47
+ const [internal, tickets, customers] = useMemo(() => {
48
+ const mine = t => idOf(t.client) === Number(chat.currentPeopleId);
49
+ return [
50
+ chat.tasks.filter(t => !isCustomerConversation(t)),
51
+ chat.tasks.filter(t => isCustomerConversation(t) && mine(t)),
52
+ chat.tasks.filter(t => isCustomerConversation(t) && !mine(t)),
53
+ ];
54
+ }, [chat.tasks, chat.currentPeopleId]);
55
+ const noAi = chat.providers.length === 0;
56
+ const ticketComposer = chat.myTicket || (!chat.activeTaskId && noAi);
57
+
58
+ const submit = async () => {
59
+ const text = draft;
131
60
  setDraft('');
61
+ const ok = await chat.sendMessage(text);
62
+ if (!ok) setDraft(text);
132
63
  };
133
64
 
134
- const sendMessage = async () => {
135
- const text = draft.trim();
136
- if (!text || sending) return;
137
- if (!provider) {
138
- showError('Selecione um provider de IA configurado na empresa');
139
- return;
140
- }
141
- setSending(true);
142
- try {
143
- const body = {
144
- message: text,
145
- provider,
146
- ...(activeTaskId ? {task_id: activeTaskId} : {}),
147
- ...(companyId ? {company_id: Number(companyId)} : {}),
148
- };
149
- const res = await api.post('/mcp/chat', body);
150
- const newTaskId = res?.task?.id;
151
- setDraft('');
152
- if (newTaskId && newTaskId !== activeTaskId) {
153
- setActiveTaskId(Number(newTaskId));
154
- await loadTasks();
155
- } else {
156
- await loadMessages(activeTaskId || newTaskId);
157
- }
158
- if (res?.reply) {
159
- // optimistic refresh
160
- await loadMessages(newTaskId || activeTaskId);
161
- }
162
- } catch (e) {
163
- showError(e?.message || e?.error || 'Falha ao enviar mensagem');
164
- } finally {
165
- setSending(false);
166
- }
167
- };
168
-
169
- const activeTask = tasks.find(
170
- t => String(t.id) === String(activeTaskId) || t['@id']?.endsWith(`/${activeTaskId}`),
171
- );
172
-
173
65
  const renderMessage = ({item}) => {
174
- const body = item?.body || '';
175
- const byId =
176
- item?.registeredBy?.id ||
177
- item?.registeredBy?.['@id']?.split('/').pop() ||
178
- item?.registered_by_id;
179
- const isUser = companyId && String(byId) !== String(companyId);
66
+ const role = messageRole(item, {companyId: chat.companyId, task: chat.activeTask, currentPeopleId: chat.currentPeopleId});
67
+ const right = role === 'me' || role === 'staff';
180
68
  return (
181
- <View style={[styles.bubble, isUser ? styles.bubbleUser : styles.bubbleAi]}>
182
- <Text style={styles.bubbleText}>{body}</Text>
69
+ <View style={[styles.bubble, right ? styles.bubbleUser : styles.bubbleAi, role === 'note' && styles.bubbleNote, role === 'customer' && styles.bubbleCustomer]}>
70
+ {ROLE_LABELS[role] ? <Text style={styles.bubbleAuthor}>{ROLE_LABELS[role]}</Text> : null}
71
+ <Text style={styles.bubbleText}>{item?.body || ''}</Text>
72
+ {item?.status && !['done', 'pending'].includes(item.status) ? <Text style={styles.bubbleMeta}>{String(item.status)}</Text> : null}
183
73
  </View>
184
74
  );
185
75
  };
186
76
 
77
+ const typing = chat.aiStatus ? (
78
+ <View style={[styles.bubble, styles.bubbleAi]}>
79
+ <Text style={styles.bubbleMeta}>{chat.aiStatus === 'processing' ? 'IA consultando os dados…' : 'Enviado, aguardando a IA…'}</Text>
80
+ </View>
81
+ ) : null;
82
+
83
+ const renderSection = (title, items, empty) => (
84
+ <View>
85
+ <Text style={styles.sectionTitle}>{title}</Text>
86
+ {items.length === 0 ? <Text style={styles.emptyText}>{empty}</Text> : null}
87
+ {items.map(item => (
88
+ <TaskRow key={String(idOf(item))} item={item} selected={idOf(item) === Number(chat.activeTaskId)} onPress={() => chat.setActiveTaskId(idOf(item))} />
89
+ ))}
90
+ </View>
91
+ );
92
+
93
+ const task = chat.activeTask;
187
94
  return (
188
- <KeyboardAvoidingView
189
- style={styles.root}
190
- behavior={Platform.OS === 'ios' ? 'padding' : undefined}
191
- keyboardVerticalOffset={80}>
95
+ <KeyboardAvoidingView style={styles.root} behavior={Platform.OS === 'ios' ? 'padding' : undefined} keyboardVerticalOffset={80}>
192
96
  <View style={styles.sidebar}>
193
97
  <View style={styles.sidebarHeader}>
194
- <Text style={styles.sidebarTitle}>Chats IA</Text>
195
- <TouchableOpacity onPress={startNewChat} style={styles.newBtn}>
196
- <Text style={styles.newBtnText}>Novo</Text>
98
+ <Text style={styles.sidebarTitle}>IA</Text>
99
+ <TouchableOpacity onPress={chat.startNewChat} style={styles.newBtn}>
100
+ <Text style={styles.newBtnText}>Novo chat</Text>
197
101
  </TouchableOpacity>
198
102
  </View>
199
- <ScrollView
200
- horizontal
201
- style={styles.providerRow}
202
- contentContainerStyle={styles.providerRowContent}>
203
- {(providers.length ? providers : Object.keys(PROVIDER_LABELS).map(k => ({provider: k, enabled: false}))).map(
204
- p => {
205
- const key = p.provider || p.id || p.name;
206
- const selected = key === provider;
207
- const disabled = p.enabled === false && !p.has_key;
208
- return (
209
- <TouchableOpacity
210
- key={String(key)}
211
- disabled={disabled}
212
- onPress={() => setProvider(key)}
213
- style={[
214
- styles.providerChip,
215
- selected && styles.providerChipActive,
216
- disabled && styles.providerChipDisabled,
217
- ]}>
218
- <Text
219
- style={[
220
- styles.providerChipText,
221
- selected && styles.providerChipTextActive,
222
- ]}>
223
- {PROVIDER_LABELS[key] || p.label || key}
224
- </Text>
225
- </TouchableOpacity>
226
- );
227
- },
228
- )}
103
+ <ScrollView horizontal style={styles.providerRow} contentContainerStyle={styles.providerRowContent}>
104
+ {noAi ? <Text style={styles.emptyText}>Sem IA própria: suas mensagens abrem um chamado.</Text> : null}
105
+ {chat.providers.map(p => (
106
+ <TouchableOpacity key={p.provider} onPress={() => chat.setProvider(p.provider)} style={[styles.providerChip, p.provider === chat.provider && styles.providerChipActive]}>
107
+ <Text style={[styles.providerChipText, p.provider === chat.provider && styles.providerChipTextActive]}>
108
+ {PROVIDER_LABELS[p.provider] || p.label || p.provider}
109
+ </Text>
110
+ </TouchableOpacity>
111
+ ))}
229
112
  </ScrollView>
230
- {loadingList ? (
231
- <ActivityIndicator style={{marginTop: 16}} />
113
+ {chat.loadingList ? (
114
+ <ActivityIndicator style={styles.spinner} />
232
115
  ) : (
233
- <FlatList
234
- data={tasks}
235
- keyExtractor={item => String(item.id || item['@id'])}
236
- renderItem={({item}) => {
237
- const id = item.id || item['@id']?.split('/').pop();
238
- const selected = String(id) === String(activeTaskId);
239
- return (
240
- <TouchableOpacity
241
- onPress={() => selectTask(item)}
242
- style={[styles.taskRow, selected && styles.taskRowActive]}>
243
- <Text numberOfLines={1} style={styles.taskNameText}>
244
- {item.name || `Chat #${id}`}
245
- </Text>
246
- </TouchableOpacity>
247
- );
248
- }}
249
- ListEmptyComponent={
250
- <Text style={styles.emptyText}>Nenhum chat ainda. Envie uma mensagem.</Text>
251
- }
252
- />
116
+ <ScrollView>
117
+ {renderSection('Meus chats', internal, noAi ? 'Sua empresa ainda não tem IA configurada.' : 'Pergunte algo sobre a empresa.')}
118
+ {tickets.length ? renderSection('Meus chamados', tickets, '') : null}
119
+ {renderSection('IA atendendo clientes', customers, 'Nenhuma conversa com a IA agora.')}
120
+ </ScrollView>
253
121
  )}
254
122
  </View>
255
123
 
256
124
  <View style={styles.chatPane}>
257
125
  <View style={styles.chatHeader}>
258
- <Text style={styles.chatTitle}>
259
- {activeTask?.name || (activeTaskId ? `Chat #${activeTaskId}` : 'Novo chat')}
260
- </Text>
261
- <Text style={styles.chatSubtitle}>
262
- {PROVIDER_LABELS[provider] || provider || 'Selecione a IA'}
263
- </Text>
126
+ <View style={styles.chatHeaderText}>
127
+ <Text style={styles.chatTitle}>{task?.name || (chat.activeTaskId ? `Conversa #${chat.activeTaskId}` : 'Novo chat')}</Text>
128
+ <Text style={styles.chatSubtitle}>
129
+ {chat.myTicket
130
+ ? `Chamado ${stageLabel(task)} · ${task?.taskStatus?.status || 'aberto'}${task?.aiAgent ? ' · IA atendendo' : ''}`
131
+ : chat.customerChat
132
+ ? `${CHANNEL_LABELS[conversationChannel(task)]} · ${stageLabel(task)} · IA atendendo`
133
+ : ticketComposer
134
+ ? 'Novo chamado'
135
+ : PROVIDER_LABELS[chat.provider] || chat.provider || 'Selecione a IA'}
136
+ </Text>
137
+ </View>
138
+ {chat.customerChat ? (
139
+ <View style={styles.actionsRow}>
140
+ {(task?.type === 'ia' ? ['relationship', 'support'] : [task?.type]).map(type => (
141
+ <TouchableOpacity key={type} style={styles.actionBtn} onPress={() => chat.takeOver(type)}>
142
+ <Text style={styles.actionBtnText}>{`Assumir${task?.type === 'ia' ? ` (${stageLabel({type})})` : ''}`}</Text>
143
+ </TouchableOpacity>
144
+ ))}
145
+ </View>
146
+ ) : null}
264
147
  </View>
265
- {loadingChat ? (
266
- <ActivityIndicator style={{marginTop: 24}} />
148
+ {chat.loadingChat ? (
149
+ <ActivityIndicator style={styles.spinner} />
267
150
  ) : (
268
151
  <FlatList
269
152
  ref={listRef}
270
- data={messages}
153
+ data={chat.messages}
271
154
  keyExtractor={item => String(item.id || item['@id'])}
272
155
  renderItem={renderMessage}
156
+ ListFooterComponent={typing}
273
157
  contentContainerStyle={styles.messagesContent}
274
158
  onContentSizeChange={() => listRef.current?.scrollToEnd?.({animated: true})}
275
- ListEmptyComponent={
276
- <Text style={styles.emptyText}>
277
- Pergunte algo. A conversa vira uma Task type=ia.
278
- </Text>
279
- }
159
+ ListEmptyComponent={<Text style={styles.emptyText}>Pergunte sobre vendas, pedidos, clientes… A IA consulta os dados da empresa.</Text>}
280
160
  />
281
161
  )}
282
- <View style={styles.composer}>
283
- <TextInput
284
- style={styles.input}
285
- value={draft}
286
- onChangeText={setDraft}
287
- placeholder="Mensagem para a IA…"
288
- multiline
289
- editable={!sending}
290
- />
291
- <TouchableOpacity
292
- style={[styles.sendBtn, (!draft.trim() || sending) && styles.sendBtnDisabled]}
293
- disabled={!draft.trim() || sending}
294
- onPress={sendMessage}>
295
- <Text style={styles.sendBtnText}>{sending ? '…' : 'Enviar'}</Text>
296
- </TouchableOpacity>
297
- </View>
162
+ {chat.customerChat ? (
163
+ <Text style={styles.composerHint}>A IA está atendendo este cliente. Para responder você mesmo, use “Assumir” ou abra o ticket no CRM / Suporte.</Text>
164
+ ) : (
165
+ <View>
166
+ {ticketComposer && !chat.myTicket ? (
167
+ <View style={styles.ticketTypeRow}>
168
+ {[['support', 'Suporte'], ['relationship', 'Comercial']].map(([value, label]) => (
169
+ <TouchableOpacity key={value} onPress={() => chat.setTicketType(value)} style={[styles.providerChip, chat.ticketType === value && styles.providerChipActive]}>
170
+ <Text style={[styles.providerChipText, chat.ticketType === value && styles.providerChipTextActive]}>{label}</Text>
171
+ </TouchableOpacity>
172
+ ))}
173
+ </View>
174
+ ) : null}
175
+ <View style={styles.composer}>
176
+ <TextInput style={styles.input} value={draft} onChangeText={setDraft} placeholder={chat.myTicket ? 'Escreva no chamado…' : ticketComposer ? 'Descreva o que precisa; abriremos um chamado com a nossa equipe…' : 'Pergunte à IA…'} placeholderTextColor="#8b98a5" multiline editable={!chat.sending} />
177
+ <TouchableOpacity style={[styles.sendBtn, (!draft.trim() || chat.sending) && styles.sendBtnDisabled]} disabled={!draft.trim() || chat.sending} onPress={submit}>
178
+ <Text style={styles.sendBtnText}>{chat.sending ? '…' : ticketComposer && !chat.myTicket ? 'Abrir chamado' : 'Enviar'}</Text>
179
+ </TouchableOpacity>
180
+ </View>
181
+ </View>
182
+ )}
298
183
  </View>
299
184
  </KeyboardAvoidingView>
300
185
  );
@@ -58,14 +58,24 @@ export default StyleSheet.create({
58
58
  },
59
59
  taskRowActive: {backgroundColor: '#1e2732'},
60
60
  taskRowText: {color: '#e7e9ea', fontSize: 13},
61
+ taskRowMeta: {color: '#8b98a5', fontSize: 11, marginTop: 2},
62
+ sectionTitle: {color: '#8b98a5', fontSize: 11, fontWeight: '700', textTransform: 'uppercase', paddingHorizontal: 12, paddingTop: 12, paddingBottom: 4},
63
+ spinner: {marginTop: 16},
61
64
  emptyText: {color: '#8b98a5', padding: 16, fontSize: 13},
62
65
  chatPane: {flex: 1, minWidth: 0},
63
66
  chatHeader: {
67
+ flexDirection: 'row',
68
+ alignItems: 'center',
69
+ gap: 8,
64
70
  paddingHorizontal: 16,
65
71
  paddingVertical: 12,
66
72
  borderBottomWidth: 1,
67
73
  borderBottomColor: '#2a3441',
68
74
  },
75
+ chatHeaderText: {flex: 1, minWidth: 0},
76
+ actionsRow: {flexDirection: 'row', gap: 6},
77
+ actionBtn: {borderWidth: 1, borderColor: '#1d9bf0', borderRadius: 8, paddingHorizontal: 10, paddingVertical: 6},
78
+ actionBtnText: {color: '#1d9bf0', fontSize: 12, fontWeight: '600'},
69
79
  chatTitle: {color: '#e7e9ea', fontSize: 16, fontWeight: '600'},
70
80
  chatSubtitle: {color: '#8b98a5', fontSize: 12, marginTop: 2},
71
81
  messagesContent: {padding: 12, paddingBottom: 24},
@@ -84,6 +94,12 @@ export default StyleSheet.create({
84
94
  alignSelf: 'flex-start',
85
95
  backgroundColor: '#212a33',
86
96
  },
97
+ bubbleNote: {alignSelf: 'center', backgroundColor: '#3a2f12', borderWidth: 1, borderColor: '#8a6d1d'},
98
+ bubbleCustomer: {backgroundColor: '#1f3a2b'},
99
+ bubbleAuthor: {color: '#8b98a5', fontSize: 11, fontWeight: '700', marginBottom: 2},
100
+ bubbleMeta: {color: '#8b98a5', fontSize: 11, marginTop: 4},
101
+ ticketTypeRow: {flexDirection: 'row', gap: 6, paddingHorizontal: 10, paddingTop: 8},
102
+ composerHint: {color: '#8b98a5', fontSize: 12, padding: 12, borderTopWidth: 1, borderTopColor: '#2a3441'},
87
103
  bubbleText: {color: '#e7e9ea', fontSize: 14, lineHeight: 20},
88
104
  composer: {
89
105
  flexDirection: 'row',
@@ -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
+ };