@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.
@@ -1,13 +1,13 @@
1
1
  {
2
- "version": "1.0.57",
2
+ "version": "1.0.66",
3
3
  "rc": 1,
4
- "branch": "rc/1.0.57-rc.1",
5
- "baseMaster": "1fb0e0b679bc9845eb00abf31b7a476d9a3d4921",
4
+ "branch": "rc/1.0.66-rc.1",
5
+ "baseMaster": "7250a195dc6b3e88fcb69245e4ee4dbebf1b5249",
6
6
  "tasks": [
7
- 1322
7
+ 64
8
8
  ],
9
9
  "frozen": true,
10
10
  "repositories": {
11
- "ControleOnline/ui-crm": "1d4360ffaf5f74e4e34147a8b284d50fbc6ce7d5"
11
+ "ControleOnline/ui-crm": "1914b740bf6800954bded23345c82beca57d04fc"
12
12
  }
13
- }
13
+ }
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.67",
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,11 @@
1
1
  /*
2
- * @agents MCP AI chat (Task type=ia). Keep under 500 lines; API via /mcp/chat*.
2
+ * @agents /ai — customer-facing help chat.
3
+ * Left: the user's latest conversations (AI chats and tickets with the platform team).
4
+ * New conversation: "IA" when the user's company has its own AI (it solves with MCP tools and, if it
5
+ * cannot, turns the chat into a Support/Commercial ticket); otherwise choose Suporte or Comercial
6
+ * and a ticket is opened for the platform team. Logic: useMcpChat.
3
7
  */
4
- import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
8
+ import React, {useRef, useState} from 'react';
5
9
  import {
6
10
  ActivityIndicator,
7
11
  FlatList,
@@ -13,286 +17,131 @@ import {
13
17
  TouchableOpacity,
14
18
  View,
15
19
  } from 'react-native';
16
- import {useStore} from '@store';
17
- import {api} from '@controleonline/ui-common/src/api';
18
- import useToastMessage from '../../hooks/useToastMessage';
20
+ import useMcpChat from './useMcpChat';
19
21
  import styles from './McpPage.styles';
20
22
 
21
- const PROVIDER_LABELS = {
22
- grok: 'Grok',
23
- openai: 'Codex / OpenAI',
24
- gemini: 'Gemini',
25
- claude: 'Claude',
26
- };
23
+ const {idOf, isCustomerConversation, stageLabel, messageRole} = require('./mcpChatUtils');
27
24
 
28
- 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;
25
+ const ROLE_LABELS = {ai: 'IA', note: null, customer: null, staff: 'Equipe', me: null};
26
+
27
+ const conversationLabel = task =>
28
+ isCustomerConversation(task)
29
+ ? `${stageLabel(task)} · ${task?.taskStatus?.status || 'aberto'}`
30
+ : 'IA';
36
31
 
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([]);
32
+ export default function McpPage() {
33
+ const chat = useMcpChat();
42
34
  const [draft, setDraft] = useState('');
43
- const [loadingList, setLoadingList] = useState(true);
44
- const [loadingChat, setLoadingChat] = useState(false);
45
- const [sending, setSending] = useState(false);
46
35
  const listRef = useRef(null);
36
+ const task = chat.activeTask;
37
+ const isNew = !chat.activeTaskId;
47
38
 
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([]);
39
+ const submit = async () => {
40
+ const text = draft;
131
41
  setDraft('');
42
+ const ok = await chat.sendMessage(text);
43
+ if (!ok) setDraft(text);
132
44
  };
133
45
 
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
46
  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);
47
+ const role = messageRole(item, {companyId: chat.companyId, task, currentPeopleId: chat.currentPeopleId});
48
+ if (role === 'note') return null; // internal notes of the team never show here
49
+ const right = role === 'me' || role === 'customer';
180
50
  return (
181
- <View style={[styles.bubble, isUser ? styles.bubbleUser : styles.bubbleAi]}>
182
- <Text style={styles.bubbleText}>{body}</Text>
51
+ <View style={[styles.bubble, right ? styles.bubbleUser : styles.bubbleAi]}>
52
+ {ROLE_LABELS[role] ? <Text style={styles.bubbleAuthor}>{ROLE_LABELS[role]}</Text> : null}
53
+ <Text style={styles.bubbleText}>{item?.body || ''}</Text>
54
+ {item?.status === 'error' ? <Text style={styles.bubbleMeta}>não enviado</Text> : null}
183
55
  </View>
184
56
  );
185
57
  };
186
58
 
59
+ const typing = chat.aiStatus ? (
60
+ <View style={[styles.bubble, styles.bubbleAi]}>
61
+ <Text style={styles.bubbleMeta}>{chat.aiStatus === 'processing' ? 'IA analisando…' : 'Enviado, aguardando a IA…'}</Text>
62
+ </View>
63
+ ) : null;
64
+
65
+ const options = chat.hasAi ? [['ai', 'IA']] : [['support', 'Suporte'], ['relationship', 'Comercial']];
66
+ const selected = chat.hasAi ? 'ai' : chat.ticketType;
67
+
187
68
  return (
188
- <KeyboardAvoidingView
189
- style={styles.root}
190
- behavior={Platform.OS === 'ios' ? 'padding' : undefined}
191
- keyboardVerticalOffset={80}>
69
+ <KeyboardAvoidingView style={styles.root} behavior={Platform.OS === 'ios' ? 'padding' : undefined} keyboardVerticalOffset={80}>
192
70
  <View style={styles.sidebar}>
193
71
  <View style={styles.sidebarHeader}>
194
- <Text style={styles.sidebarTitle}>Chats IA</Text>
195
- <TouchableOpacity onPress={startNewChat} style={styles.newBtn}>
72
+ <Text style={styles.sidebarTitle}>Atendimento</Text>
73
+ <TouchableOpacity onPress={chat.startNewChat} style={styles.newBtn}>
196
74
  <Text style={styles.newBtnText}>Novo</Text>
197
75
  </TouchableOpacity>
198
76
  </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
- )}
229
- </ScrollView>
230
- {loadingList ? (
231
- <ActivityIndicator style={{marginTop: 16}} />
77
+ {chat.loadingList ? (
78
+ <ActivityIndicator style={styles.spinner} />
232
79
  ) : (
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);
80
+ <ScrollView>
81
+ {chat.tasks.length === 0 ? <Text style={styles.emptyText}>Nenhum chamado ainda.</Text> : null}
82
+ {chat.tasks.map(item => {
83
+ const id = idOf(item);
239
84
  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>
85
+ <TouchableOpacity key={String(id)} onPress={() => chat.setActiveTaskId(id)} style={[styles.taskRow, id === Number(chat.activeTaskId) && styles.taskRowActive]}>
86
+ <Text numberOfLines={1} style={styles.taskRowText}>{item.name || `Chamado #${id}`}</Text>
87
+ <Text style={styles.taskRowMeta}>{conversationLabel(item)}</Text>
246
88
  </TouchableOpacity>
247
89
  );
248
- }}
249
- ListEmptyComponent={
250
- <Text style={styles.emptyText}>Nenhum chat ainda. Envie uma mensagem.</Text>
251
- }
252
- />
90
+ })}
91
+ </ScrollView>
253
92
  )}
254
93
  </View>
255
94
 
256
95
  <View style={styles.chatPane}>
257
96
  <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>
97
+ <View style={styles.chatHeaderText}>
98
+ <Text style={styles.chatTitle}>{isNew ? 'Como podemos ajudar?' : task?.name || `Chamado #${chat.activeTaskId}`}</Text>
99
+ {!isNew && task ? <Text style={styles.chatSubtitle}>{conversationLabel(task)}</Text> : null}
100
+ </View>
264
101
  </View>
265
- {loadingChat ? (
266
- <ActivityIndicator style={{marginTop: 24}} />
102
+ {chat.loadingChat ? (
103
+ <ActivityIndicator style={styles.spinner} />
267
104
  ) : (
268
105
  <FlatList
269
106
  ref={listRef}
270
- data={messages}
107
+ data={chat.messages}
271
108
  keyExtractor={item => String(item.id || item['@id'])}
272
109
  renderItem={renderMessage}
110
+ ListFooterComponent={typing}
273
111
  contentContainerStyle={styles.messagesContent}
274
112
  onContentSizeChange={() => listRef.current?.scrollToEnd?.({animated: true})}
275
113
  ListEmptyComponent={
276
114
  <Text style={styles.emptyText}>
277
- Pergunte algo. A conversa vira uma Task type=ia.
115
+ {chat.hasAi ? 'Pergunte à IA. Se ela não resolver, abre um chamado com a nossa equipe.' : 'Escolha Suporte ou Comercial e descreva o que precisa.'}
278
116
  </Text>
279
117
  }
280
118
  />
281
119
  )}
120
+ {isNew ? (
121
+ <View style={styles.ticketTypeRow}>
122
+ {options.map(([value, label]) => (
123
+ <TouchableOpacity
124
+ key={value}
125
+ disabled={chat.hasAi}
126
+ onPress={() => chat.setTicketType(value)}
127
+ style={[styles.providerChip, selected === value && styles.providerChipActive]}>
128
+ <Text style={[styles.providerChipText, selected === value && styles.providerChipTextActive]}>{label}</Text>
129
+ </TouchableOpacity>
130
+ ))}
131
+ </View>
132
+ ) : null}
282
133
  <View style={styles.composer}>
283
134
  <TextInput
284
135
  style={styles.input}
285
136
  value={draft}
286
137
  onChangeText={setDraft}
287
- placeholder="Mensagem para a IA…"
138
+ placeholder={isNew ? 'Descreva o que precisa…' : 'Escreva uma mensagem…'}
139
+ placeholderTextColor="#8b98a5"
288
140
  multiline
289
- editable={!sending}
141
+ editable={!chat.sending}
290
142
  />
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>
143
+ <TouchableOpacity style={[styles.sendBtn, (!draft.trim() || chat.sending) && styles.sendBtnDisabled]} disabled={!draft.trim() || chat.sending} onPress={submit}>
144
+ <Text style={styles.sendBtnText}>{chat.sending ? '…' : 'Enviar'}</Text>
296
145
  </TouchableOpacity>
297
146
  </View>
298
147
  </View>
@@ -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
+ };