@controleonline/ui-crm 1.0.67 → 1.0.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/.release/rc-manifest.json +6 -5
  2. package/package.json +4 -3
  3. package/src/react/components/conversation/Attachment.js +61 -0
  4. package/src/react/components/conversation/AudioPlayer.native.js +28 -0
  5. package/src/react/components/conversation/AudioPlayer.web.js +9 -0
  6. package/src/react/components/conversation/Composer.js +134 -0
  7. package/src/react/components/conversation/ConversationView.js +91 -0
  8. package/src/react/components/conversation/MessageBubble.js +68 -0
  9. package/src/react/components/conversation/OptionPicker.js +62 -0
  10. package/src/react/components/conversation/RichText.js +34 -0
  11. package/src/react/components/conversation/fileApi.js +78 -0
  12. package/src/react/components/conversation/formatText.js +61 -0
  13. package/src/react/components/conversation/requestApi.js +91 -0
  14. package/src/react/components/conversation/useAudioRecording.native.js +31 -0
  15. package/src/react/components/conversation/useAudioRecording.web.js +54 -0
  16. package/src/react/components/conversation/useChatPalette.js +41 -0
  17. package/src/react/pages/crm/conversation.js +25 -326
  18. package/src/react/pages/mcp/McpPage.js +134 -131
  19. package/src/react/pages/mcp/useRequests.js +127 -0
  20. package/src/react/pages/settings/GeneralSettings.js +16 -0
  21. package/src/react/pages/settings/sections/AiDefaultSection.js +122 -0
  22. package/src/react/pages/settings/sections/TicketSettingsSection.js +124 -0
  23. package/src/react/pages/tickets/TicketConversationPage.js +5 -164
  24. package/src/react/pages/tickets/TicketFunnelPage.js +5 -1
  25. package/src/react/pages/tickets/TicketWorkspace.js +245 -0
  26. package/src/react/router/routes.js +6 -6
  27. package/src/tests/react/components/conversation/formatText.test.js +40 -0
  28. package/src/react/pages/crm/conversation.styles.js +0 -206
  29. package/src/react/pages/mcp/McpPage.styles.js +0 -132
  30. package/src/react/pages/mcp/useMcpChat.js +0 -276
@@ -1,150 +1,153 @@
1
1
  /*
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.
2
+ * @agents Requests screen (/ai) of the customer companies' teams (app-community#1592–#1595, #1597):
3
+ * left, the user's requests with a status filter (default "open"); "Novo" asks Suporte or Comercial and
4
+ * the first message opens the request (born without a responsible person). Right, the WhatsApp-like
5
+ * conversation with text, attachments and voice notes. No direct AI chat here; information is read-only.
7
6
  */
8
- import React, {useRef, useState} from 'react';
9
- import {
10
- ActivityIndicator,
11
- FlatList,
12
- KeyboardAvoidingView,
13
- Platform,
14
- ScrollView,
15
- Text,
16
- TextInput,
17
- TouchableOpacity,
18
- View,
19
- } from 'react-native';
20
- import useMcpChat from './useMcpChat';
21
- import styles from './McpPage.styles';
7
+ import React, {useCallback, useState} from 'react';
8
+ import {ActivityIndicator, Modal, Pressable, ScrollView, Text, TouchableOpacity, useWindowDimensions, View} from 'react-native';
9
+ import useToastMessage from '../../hooks/useToastMessage';
10
+ import ConversationView from '../../components/conversation/ConversationView';
11
+ import OptionPicker from '../../components/conversation/OptionPicker';
12
+ import useChatPalette from '../../components/conversation/useChatPalette';
13
+ import {personName, REQUEST_TYPES, typeLabel} from '../../components/conversation/requestApi';
14
+ import useRequests from './useRequests';
22
15
 
23
- const {idOf, isCustomerConversation, stageLabel, messageRole} = require('./mcpChatUtils');
16
+ const {idOf} = require('./mcpChatUtils');
24
17
 
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';
18
+ const dateLabel = value => (value ? new Date(value).toLocaleDateString('pt-BR') : '');
31
19
 
32
20
  export default function McpPage() {
33
- const chat = useMcpChat();
34
- const [draft, setDraft] = useState('');
35
- const listRef = useRef(null);
36
- const task = chat.activeTask;
37
- const isNew = !chat.activeTaskId;
21
+ const palette = useChatPalette();
22
+ const {showError} = useToastMessage();
23
+ const onError = useCallback(message => showError(message), [showError]);
24
+ const r = useRequests({onError});
25
+ const {width} = useWindowDimensions();
26
+ const narrow = width < 760;
27
+ const [chooser, setChooser] = useState(false);
28
+
29
+ const showChat = Boolean(r.activeId || r.draftType);
30
+ const describe = useCallback(
31
+ item => {
32
+ if (item?.visibility === 'private' && idOf(item?.registeredBy) !== Number(r.meId)) return {kind: 'hidden'};
33
+ const mine = idOf(item?.registeredBy) === Number(r.meId);
34
+ return {side: mine ? 'right' : 'left', kind: 'msg', author: mine ? 'Você' : personName(item?.registeredBy) || 'Atendimento'};
35
+ },
36
+ [r.meId],
37
+ );
38
38
 
39
- const submit = async () => {
40
- const text = draft;
41
- setDraft('');
42
- const ok = await chat.sendMessage(text);
43
- if (!ok) setDraft(text);
44
- };
39
+ const statusOptions = [{value: '', label: 'Todos'}, ...r.statuses.map(s => ({value: s.status, label: s.status}))];
45
40
 
46
- const renderMessage = ({item}) => {
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';
50
- return (
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}
41
+ const list = (
42
+ <View style={{width: narrow ? '100%' : 320, borderRightWidth: narrow ? 0 : 1, borderRightColor: palette.border, backgroundColor: palette.panel, flex: narrow ? 1 : undefined}}>
43
+ <View style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 12}}>
44
+ <Text style={{color: palette.text, fontWeight: '700', fontSize: 17}}>Solicitações</Text>
45
+ <TouchableOpacity onPress={() => setChooser(true)} style={{backgroundColor: palette.chipActive, borderRadius: 16, paddingHorizontal: 14, paddingVertical: 7}}>
46
+ <Text style={{color: palette.chipActiveText, fontWeight: '700'}}>Novo</Text>
47
+ </TouchableOpacity>
55
48
  </View>
56
- );
57
- };
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>
49
+ <View style={{paddingHorizontal: 12}}>
50
+ <OptionPicker label="Status" value={r.statusFilter} options={statusOptions} onChange={value => r.setStatusFilter(value)} />
51
+ </View>
52
+ {r.loadingList ? (
53
+ <ActivityIndicator style={{marginTop: 16}} color={palette.primary} />
54
+ ) : (
55
+ <ScrollView>
56
+ {!r.requests.length ? <Text style={{color: palette.muted, padding: 16}}>Nenhuma solicitação com este status.</Text> : null}
57
+ {r.requests.map(item => {
58
+ const id = idOf(item);
59
+ const active = id === Number(r.activeId);
60
+ return (
61
+ <TouchableOpacity
62
+ key={String(id)}
63
+ onPress={() => r.open(id)}
64
+ style={{paddingHorizontal: 12, paddingVertical: 10, borderBottomWidth: 1, borderBottomColor: palette.border, backgroundColor: active ? palette.chip : 'transparent'}}>
65
+ <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
66
+ <Text style={{color: palette.text, fontWeight: '600', flex: 1}} numberOfLines={1}>
67
+ {item.name || `Solicitação #${id}`}
68
+ </Text>
69
+ <Text style={{color: palette.muted, fontSize: 11, marginLeft: 6}}>{dateLabel(item.alterDate)}</Text>
70
+ </View>
71
+ <Text style={{color: palette.muted, fontSize: 12, marginTop: 2}} numberOfLines={1}>
72
+ {[typeLabel(item.type), item.taskStatus?.status, personName(item.taskFor)].filter(Boolean).join(' · ')}
73
+ </Text>
74
+ </TouchableOpacity>
75
+ );
76
+ })}
77
+ </ScrollView>
78
+ )}
62
79
  </View>
63
- ) : null;
64
-
65
- const options = chat.hasAi ? [['ai', 'IA']] : [['support', 'Suporte'], ['relationship', 'Comercial']];
66
- const selected = chat.hasAi ? 'ai' : chat.ticketType;
80
+ );
67
81
 
68
- return (
69
- <KeyboardAvoidingView style={styles.root} behavior={Platform.OS === 'ios' ? 'padding' : undefined} keyboardVerticalOffset={80}>
70
- <View style={styles.sidebar}>
71
- <View style={styles.sidebarHeader}>
72
- <Text style={styles.sidebarTitle}>Atendimento</Text>
73
- <TouchableOpacity onPress={chat.startNewChat} style={styles.newBtn}>
74
- <Text style={styles.newBtnText}>Novo</Text>
82
+ const task = r.task;
83
+ const header = (
84
+ <View style={{borderBottomWidth: 1, borderBottomColor: palette.border, backgroundColor: palette.panel, paddingHorizontal: 12, paddingTop: 10, paddingBottom: 4}}>
85
+ <View style={{flexDirection: 'row', alignItems: 'center', gap: 8, marginBottom: 6}}>
86
+ {narrow ? (
87
+ <TouchableOpacity onPress={() => r.open(null)}>
88
+ <Text style={{color: palette.primary, fontSize: 18}}>‹</Text>
75
89
  </TouchableOpacity>
76
- </View>
77
- {chat.loadingList ? (
78
- <ActivityIndicator style={styles.spinner} />
79
- ) : (
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);
84
- return (
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>
88
- </TouchableOpacity>
89
- );
90
- })}
91
- </ScrollView>
92
- )}
90
+ ) : null}
91
+ <Text style={{color: palette.text, fontWeight: '700', fontSize: 16, flex: 1}} numberOfLines={1}>
92
+ {r.draftType ? `Nova solicitação · ${typeLabel(r.draftType)}` : task?.name || 'Solicitação'}
93
+ </Text>
93
94
  </View>
94
-
95
- <View style={styles.chatPane}>
96
- <View style={styles.chatHeader}>
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>
95
+ {task ? (
96
+ <View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
97
+ <OptionPicker label="Contexto" value={task.type} options={REQUEST_TYPES} />
98
+ <OptionPicker label="Status" value={task.taskStatus?.status} options={[{value: task.taskStatus?.status, label: task.taskStatus?.status}]} />
99
+ <OptionPicker label="Responsável" value="r" options={[{value: 'r', label: personName(task.taskFor) || 'Aguardando atendimento'}]} />
100
+ {task.category ? <OptionPicker label="Categoria" value="c" options={[{value: 'c', label: task.category?.name || ''}]} /> : null}
101
+ {task.dueDate ? <OptionPicker label="Previsão" value="d" options={[{value: 'd', label: dateLabel(task.dueDate)}]} /> : null}
101
102
  </View>
102
- {chat.loadingChat ? (
103
- <ActivityIndicator style={styles.spinner} />
104
- ) : (
105
- <FlatList
106
- ref={listRef}
107
- data={chat.messages}
108
- keyExtractor={item => String(item.id || item['@id'])}
109
- renderItem={renderMessage}
110
- ListFooterComponent={typing}
111
- contentContainerStyle={styles.messagesContent}
112
- onContentSizeChange={() => listRef.current?.scrollToEnd?.({animated: true})}
113
- ListEmptyComponent={
114
- <Text style={styles.emptyText}>
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.'}
116
- </Text>
117
- }
118
- />
119
- )}
120
- {isNew ? (
121
- <View style={styles.ticketTypeRow}>
122
- {options.map(([value, label]) => (
103
+ ) : null}
104
+ </View>
105
+ );
106
+
107
+ const chat = showChat ? (
108
+ <ConversationView
109
+ header={header}
110
+ messages={r.messages}
111
+ loading={r.loadingChat}
112
+ describe={describe}
113
+ onSend={r.send}
114
+ uploadCompanyId={r.companyId}
115
+ placeholder={r.draftType ? 'Descreva o que você precisa…' : 'Mensagem'}
116
+ emptyText={r.draftType ? 'Escreva sua mensagem, anexe arquivos ou grave um áudio. Nossa equipe responde por aqui.' : 'Nenhuma mensagem ainda.'}
117
+ onError={onError}
118
+ />
119
+ ) : (
120
+ <View style={{flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: palette.background, padding: 24}}>
121
+ <Text style={{color: palette.muted, textAlign: 'center'}}>Selecione uma solicitação ou toque em Novo.</Text>
122
+ </View>
123
+ );
124
+
125
+ return (
126
+ <View style={{flex: 1, flexDirection: 'row', minHeight: 0, backgroundColor: palette.background}}>
127
+ {!narrow || !showChat ? list : null}
128
+ {!narrow || showChat ? <View style={{flex: 1, minWidth: 0}}>{chat}</View> : null}
129
+ <Modal visible={chooser} transparent animationType="fade" onRequestClose={() => setChooser(false)}>
130
+ <Pressable style={{flex: 1, backgroundColor: 'rgba(0,0,0,0.45)', justifyContent: 'center', padding: 24}} onPress={() => setChooser(false)}>
131
+ <Pressable style={{backgroundColor: palette.panel, borderRadius: 14, padding: 16, borderWidth: 1, borderColor: palette.border, maxWidth: 420, width: '100%', alignSelf: 'center'}}>
132
+ <Text style={{color: palette.text, fontWeight: '700', fontSize: 17, marginBottom: 12}}>Nova solicitação</Text>
133
+ {REQUEST_TYPES.map(t => (
123
134
  <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>
135
+ key={t.value}
136
+ onPress={() => {
137
+ setChooser(false);
138
+ r.startNew(t.value);
139
+ }}
140
+ style={{borderWidth: 1, borderColor: palette.border, borderRadius: 10, padding: 14, marginBottom: 10, backgroundColor: palette.chip}}>
141
+ <Text style={{color: palette.text, fontWeight: '700', fontSize: 15}}>{t.label}</Text>
142
+ <Text style={{color: palette.muted, marginTop: 2}}>{t.hint}</Text>
129
143
  </TouchableOpacity>
130
144
  ))}
131
- </View>
132
- ) : null}
133
- <View style={styles.composer}>
134
- <TextInput
135
- style={styles.input}
136
- value={draft}
137
- onChangeText={setDraft}
138
- placeholder={isNew ? 'Descreva o que precisa…' : 'Escreva uma mensagem…'}
139
- placeholderTextColor="#8b98a5"
140
- multiline
141
- editable={!chat.sending}
142
- />
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>
145
- </TouchableOpacity>
146
- </View>
147
- </View>
148
- </KeyboardAvoidingView>
145
+ <TouchableOpacity onPress={() => setChooser(false)} style={{alignSelf: 'flex-end', paddingVertical: 6, paddingHorizontal: 4}}>
146
+ <Text style={{color: palette.muted}}>Cancelar</Text>
147
+ </TouchableOpacity>
148
+ </Pressable>
149
+ </Pressable>
150
+ </Modal>
151
+ </View>
149
152
  );
150
153
  }
@@ -0,0 +1,127 @@
1
+ /*
2
+ * @agents State of the requests screen (/ai, app-community#1592–#1595): the user's relationship/support
3
+ * requests filtered by status (default "open"), the selected one with its conversation, and the
4
+ * draft type of a new request. Live through websocket events (useRealtimeReload).
5
+ */
6
+ import {useCallback, useEffect, useState} from 'react';
7
+ import {useStore} from '@store';
8
+ import useRealtimeReload from '../tickets/useRealtimeReload';
9
+ import {fetchMessages, fetchMyRequests, fetchRequestStatuses, fetchTask, sendRequestMessage} from '../../components/conversation/requestApi';
10
+
11
+ const {idOf} = require('./mcpChatUtils');
12
+
13
+ export default function useRequests({onError}) {
14
+ const peopleStore = useStore('people');
15
+ const authStore = useStore('auth');
16
+ const company = peopleStore?.getters?.currentCompany || peopleStore?.getters?.mainCompany;
17
+ const companyId = idOf(company);
18
+ const meId = idOf(authStore?.getters?.user?.people);
19
+
20
+ const [statuses, setStatuses] = useState([]);
21
+ const [statusFilter, setStatusFilter] = useState('open');
22
+ const [requests, setRequests] = useState([]);
23
+ const [loadingList, setLoadingList] = useState(true);
24
+ const [activeId, setActiveId] = useState(null);
25
+ const [draftType, setDraftType] = useState(null);
26
+ const [task, setTask] = useState(null);
27
+ const [messages, setMessages] = useState([]);
28
+ const [loadingChat, setLoadingChat] = useState(false);
29
+
30
+ useEffect(() => {
31
+ fetchRequestStatuses().then(setStatuses).catch(() => setStatuses([]));
32
+ }, []);
33
+
34
+ const loadList = useCallback(async () => {
35
+ if (!meId) return;
36
+ try {
37
+ setRequests(await fetchMyRequests(meId, statusFilter));
38
+ } catch (e) {
39
+ onError?.(e?.message || 'Não foi possível carregar as solicitações');
40
+ } finally {
41
+ setLoadingList(false);
42
+ }
43
+ }, [meId, statusFilter, onError]);
44
+
45
+ const loadChat = useCallback(
46
+ async (id = activeId, {quiet = false} = {}) => {
47
+ if (!id) return;
48
+ if (!quiet) setLoadingChat(true);
49
+ try {
50
+ const [t, m] = await Promise.all([fetchTask(id), fetchMessages(id)]);
51
+ setTask(t);
52
+ setMessages(m);
53
+ } catch (e) {
54
+ onError?.(e?.message || 'Não foi possível carregar a conversa');
55
+ } finally {
56
+ setLoadingChat(false);
57
+ }
58
+ },
59
+ [activeId, onError],
60
+ );
61
+
62
+ useEffect(() => {
63
+ setLoadingList(true);
64
+ loadList();
65
+ }, [loadList]);
66
+
67
+ useEffect(() => {
68
+ setTask(null);
69
+ setMessages([]);
70
+ if (activeId) loadChat(activeId);
71
+ }, [activeId]); // eslint-disable-line react-hooks/exhaustive-deps
72
+
73
+ useRealtimeReload(
74
+ events => {
75
+ loadList();
76
+ if (activeId && events.some(e => Number(e.task_id) === Number(activeId))) loadChat(activeId, {quiet: true});
77
+ },
78
+ {delay: 300},
79
+ );
80
+
81
+ const open = id => {
82
+ setDraftType(null);
83
+ setActiveId(id);
84
+ };
85
+
86
+ const startNew = type => {
87
+ setActiveId(null);
88
+ setTask(null);
89
+ setMessages([]);
90
+ setDraftType(type);
91
+ };
92
+
93
+ /** Opens the draft request on the first message, otherwise continues the selected one. */
94
+ const send = async ({text, fileId}) => {
95
+ const res = await sendRequestMessage({taskId: activeId, type: draftType, text, fileId, companyId});
96
+ const id = Number(res?.task_id || activeId);
97
+ if (!activeId && id) {
98
+ setDraftType(null);
99
+ setActiveId(id);
100
+ // A new request is "open": show it in the list when the filter hides it.
101
+ if (statusFilter !== 'open') setStatusFilter('open');
102
+ else loadList();
103
+ } else {
104
+ await loadChat(id, {quiet: true});
105
+ loadList();
106
+ }
107
+ return true;
108
+ };
109
+
110
+ return {
111
+ companyId,
112
+ meId,
113
+ statuses,
114
+ statusFilter,
115
+ setStatusFilter,
116
+ requests,
117
+ loadingList,
118
+ activeId,
119
+ open,
120
+ draftType,
121
+ startNew,
122
+ task,
123
+ messages,
124
+ loadingChat,
125
+ send,
126
+ };
127
+ }
@@ -31,6 +31,8 @@ import MapsSection from './sections/MapsSection';
31
31
  import ShopSettingsSection from './sections/shop/ShopSettingsSection';
32
32
  import LogSection from './sections/LogSection';
33
33
  import MaintenanceSection from './sections/MaintenanceSection';
34
+ import AiDefaultSection from './sections/AiDefaultSection';
35
+ import TicketSettingsSection from './sections/TicketSettingsSection';
34
36
 
35
37
  const MAIN_COMPANY_ONLY_TABS = new Set(['shop']);
36
38
  const TECHNICAL_TABS = new Set(['logs', 'maintenance']);
@@ -99,6 +101,20 @@ const SETTINGS_TABS = [
99
101
  stores: ['configs'],
100
102
  Component: CrmSection,
101
103
  },
104
+ {
105
+ key: 'ai',
106
+ label: 'IA',
107
+ icon: 'chat',
108
+ stores: ['configs'],
109
+ Component: AiDefaultSection,
110
+ },
111
+ {
112
+ key: 'tickets',
113
+ label: 'Atendimento',
114
+ icon: 'support-agent',
115
+ stores: ['configs'],
116
+ Component: TicketSettingsSection,
117
+ },
102
118
  {
103
119
  key: 'loyalty',
104
120
  label: 'Fidelidade',
@@ -0,0 +1,122 @@
1
+ /*
2
+ * @agents General settings → IA: lists the AIs already connected to the company (keys are configured in
3
+ * Integrações) and chooses which one the /ai chat uses (POST /mcp/chat/default, api-platform-mcp#86).
4
+ */
5
+ import React, {useCallback, useEffect, useState} from 'react';
6
+ import {ActivityIndicator, Text, TouchableOpacity, View} from 'react-native';
7
+ import {useNavigation} from '@react-navigation/native';
8
+
9
+ import {api} from '@controleonline/ui-common/src/api';
10
+ import useToastMessage from '@controleonline/ui-crm/src/react/hooks/useToastMessage';
11
+
12
+ import {useGeneralSettingsPalette, useGeneralSettingsStyles} from '../GeneralSettings.styles';
13
+ import GeneralSettingsSection from '../GeneralSettingsSection';
14
+ import {useGeneralSettingsConfig} from '../GeneralSettings.shared';
15
+
16
+ const TITLES = {grok: 'Grok (xAI)', openai: 'Codex / OpenAI', gemini: 'Gemini', claude: 'Claude'};
17
+
18
+ const AiDefaultSection = () => {
19
+ const navigation = useNavigation();
20
+ const localStyles = useGeneralSettingsStyles();
21
+ const palette = useGeneralSettingsPalette();
22
+ const {showError, showSuccess} = useToastMessage();
23
+ const {currentCompany, mainCompany} = useGeneralSettingsConfig();
24
+ const companyId = Number(currentCompany?.id || mainCompany?.id || 0) || null;
25
+
26
+ const [loading, setLoading] = useState(true);
27
+ const [saving, setSaving] = useState(null);
28
+ const [providers, setProviders] = useState([]);
29
+ const [selected, setSelected] = useState(null);
30
+
31
+ const load = useCallback(async () => {
32
+ if (!companyId) return;
33
+ setLoading(true);
34
+ try {
35
+ const res = await api.fetch('/mcp/chat/providers', {params: {company_id: companyId}});
36
+ const list = Array.isArray(res?.providers) ? res.providers : [];
37
+ setProviders(list);
38
+ setSelected(res?.default || list.find(p => p.default)?.provider || list[0]?.provider || null);
39
+ } catch (e) {
40
+ showError(e?.message || 'Não foi possível carregar as IAs conectadas.');
41
+ } finally {
42
+ setLoading(false);
43
+ }
44
+ }, [companyId, showError]);
45
+
46
+ useEffect(() => {
47
+ load();
48
+ }, [load]);
49
+
50
+ const choose = async provider => {
51
+ if (provider === selected || saving) return;
52
+ setSaving(provider);
53
+ try {
54
+ await api.post('/mcp/chat/default', {provider, company_id: companyId});
55
+ setSelected(provider);
56
+ showSuccess(`${TITLES[provider] || provider} será usada no atendimento.`);
57
+ } catch (e) {
58
+ showError(e?.message || 'Não foi possível salvar a IA padrão.');
59
+ } finally {
60
+ setSaving(null);
61
+ }
62
+ };
63
+
64
+ return (
65
+ <GeneralSettingsSection
66
+ title="Inteligência Artificial"
67
+ description="Escolha qual das IAs conectadas atende no /ai. As chaves e modelos de cada IA são configurados em Integrações.">
68
+ {loading ? (
69
+ <ActivityIndicator style={{marginTop: 12}} />
70
+ ) : providers.length === 0 ? (
71
+ <View>
72
+ <Text style={localStyles.helperText}>Nenhuma IA conectada nesta empresa.</Text>
73
+ <TouchableOpacity onPress={() => navigation.navigate('IntegrationsPage')} style={{marginTop: 8}}>
74
+ <Text style={{color: palette?.primary || '#1976d2', fontWeight: '600'}}>Conectar uma IA em Integrações</Text>
75
+ </TouchableOpacity>
76
+ </View>
77
+ ) : (
78
+ <View>
79
+ {providers.map(p => {
80
+ const active = p.provider === selected;
81
+ return (
82
+ <TouchableOpacity
83
+ key={p.provider}
84
+ onPress={() => choose(p.provider)}
85
+ disabled={!!saving}
86
+ style={{
87
+ flexDirection: 'row',
88
+ alignItems: 'center',
89
+ paddingVertical: 12,
90
+ paddingHorizontal: 12,
91
+ marginBottom: 8,
92
+ borderRadius: 10,
93
+ borderWidth: 1,
94
+ borderColor: active ? palette?.primary || '#1976d2' : palette?.border || '#e2e8f0',
95
+ backgroundColor: palette?.surface || palette?.background || 'transparent',
96
+ }}>
97
+ <View
98
+ style={{
99
+ width: 18,
100
+ height: 18,
101
+ borderRadius: 9,
102
+ borderWidth: 2,
103
+ marginRight: 12,
104
+ borderColor: palette?.primary || '#1976d2',
105
+ backgroundColor: active ? palette?.primary || '#1976d2' : 'transparent',
106
+ }}
107
+ />
108
+ <View style={{flex: 1}}>
109
+ <Text style={localStyles.sectionTitle}>{TITLES[p.provider] || p.label || p.provider}</Text>
110
+ <Text style={localStyles.helperText}>{p.model ? `Modelo: ${p.model}` : 'Modelo padrão'}</Text>
111
+ </View>
112
+ {saving === p.provider ? <ActivityIndicator /> : active ? <Text style={localStyles.helperText}>Em uso</Text> : null}
113
+ </TouchableOpacity>
114
+ );
115
+ })}
116
+ </View>
117
+ )}
118
+ </GeneralSettingsSection>
119
+ );
120
+ };
121
+
122
+ export default AiDefaultSection;