@controleonline/ui-crm 1.0.69 → 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 (29) hide show
  1. package/.release/rc-manifest.json +6 -6
  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 -130
  19. package/src/react/pages/mcp/useRequests.js +127 -0
  20. package/src/react/pages/settings/GeneralSettings.js +8 -0
  21. package/src/react/pages/settings/sections/TicketSettingsSection.js +124 -0
  22. package/src/react/pages/tickets/TicketConversationPage.js +5 -164
  23. package/src/react/pages/tickets/TicketFunnelPage.js +5 -1
  24. package/src/react/pages/tickets/TicketWorkspace.js +245 -0
  25. package/src/react/router/routes.js +6 -6
  26. package/src/tests/react/components/conversation/formatText.test.js +40 -0
  27. package/src/react/pages/crm/conversation.styles.js +0 -206
  28. package/src/react/pages/mcp/McpPage.styles.js +0 -132
  29. package/src/react/pages/mcp/useMcpChat.js +0 -277
@@ -1,149 +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
- // With the company's own AI the chat goes straight to it; the type choice exists only without AI.
66
- const options = [['support', 'Suporte'], ['relationship', 'Comercial']];
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 ? 'Como podemos ajudar? Descreva o que precisa.' : 'Escolha Suporte ou Comercial e descreva o que precisa.'}
116
- </Text>
117
- }
118
- />
119
- )}
120
- {isNew && !chat.hasAi ? (
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
- onPress={() => chat.setTicketType(value)}
126
- style={[styles.providerChip, chat.ticketType === value && styles.providerChipActive]}>
127
- <Text style={[styles.providerChipText, chat.ticketType === 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>
128
143
  </TouchableOpacity>
129
144
  ))}
130
- </View>
131
- ) : null}
132
- <View style={styles.composer}>
133
- <TextInput
134
- style={styles.input}
135
- value={draft}
136
- onChangeText={setDraft}
137
- placeholder={isNew ? 'Descreva o que precisa…' : 'Escreva uma mensagem…'}
138
- placeholderTextColor="#8b98a5"
139
- multiline
140
- editable={!chat.sending}
141
- />
142
- <TouchableOpacity style={[styles.sendBtn, (!draft.trim() || chat.sending) && styles.sendBtnDisabled]} disabled={!draft.trim() || chat.sending} onPress={submit}>
143
- <Text style={styles.sendBtnText}>{chat.sending ? '…' : 'Enviar'}</Text>
144
- </TouchableOpacity>
145
- </View>
146
- </View>
147
- </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>
148
152
  );
149
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
+ }
@@ -32,6 +32,7 @@ import ShopSettingsSection from './sections/shop/ShopSettingsSection';
32
32
  import LogSection from './sections/LogSection';
33
33
  import MaintenanceSection from './sections/MaintenanceSection';
34
34
  import AiDefaultSection from './sections/AiDefaultSection';
35
+ import TicketSettingsSection from './sections/TicketSettingsSection';
35
36
 
36
37
  const MAIN_COMPANY_ONLY_TABS = new Set(['shop']);
37
38
  const TECHNICAL_TABS = new Set(['logs', 'maintenance']);
@@ -107,6 +108,13 @@ const SETTINGS_TABS = [
107
108
  stores: ['configs'],
108
109
  Component: AiDefaultSection,
109
110
  },
111
+ {
112
+ key: 'tickets',
113
+ label: 'Atendimento',
114
+ icon: 'support-agent',
115
+ stores: ['configs'],
116
+ Component: TicketSettingsSection,
117
+ },
110
118
  {
111
119
  key: 'loyalty',
112
120
  label: 'Fidelidade',
@@ -0,0 +1,124 @@
1
+ /*
2
+ * @agents General settings → Atendimento (app-community#1596/#1600): how requests are distributed and
3
+ * who answers them. Support: rule (random / fewest open) + the people who answer support (the only
4
+ * ones listed as responsible in /support). CRM: rule + sales assistants (salesmen always answer).
5
+ * Saved per company through GET|PUT /tickets/settings.
6
+ */
7
+ import React, {useCallback, useEffect, useState} from 'react';
8
+ import {ActivityIndicator, Text, TouchableOpacity, View} from 'react-native';
9
+
10
+ import useToastMessage from '@controleonline/ui-crm/src/react/hooks/useToastMessage';
11
+ import {fetchTicketSettings, saveTicketSettings} from '../../../components/conversation/requestApi';
12
+ import {useGeneralSettingsPalette, useGeneralSettingsStyles} from '../GeneralSettings.styles';
13
+ import GeneralSettingsSection from '../GeneralSettingsSection';
14
+ import {useGeneralSettingsConfig} from '../GeneralSettings.shared';
15
+
16
+ const STRATEGIES = [
17
+ {value: 'random', label: 'Aleatório'},
18
+ {value: 'least_open', label: 'Quem tem menos chamados abertos'},
19
+ ];
20
+
21
+ const Choice = ({active, label, onPress, palette, multi}) => (
22
+ <TouchableOpacity
23
+ onPress={onPress}
24
+ style={{
25
+ flexDirection: 'row',
26
+ alignItems: 'center',
27
+ paddingVertical: 10,
28
+ paddingHorizontal: 12,
29
+ marginBottom: 6,
30
+ borderRadius: 10,
31
+ borderWidth: 1,
32
+ borderColor: active ? palette.primary : palette.cardBorder,
33
+ backgroundColor: palette.cardBackground,
34
+ }}>
35
+ <View
36
+ style={{
37
+ width: 18,
38
+ height: 18,
39
+ borderRadius: multi ? 4 : 9,
40
+ borderWidth: 2,
41
+ marginRight: 10,
42
+ borderColor: palette.primary,
43
+ backgroundColor: active ? palette.primary : 'transparent',
44
+ }}
45
+ />
46
+ <Text style={{color: palette.textPrimary, flex: 1}}>{label}</Text>
47
+ </TouchableOpacity>
48
+ );
49
+
50
+ export default function TicketSettingsSection() {
51
+ const styles = useGeneralSettingsStyles();
52
+ const palette = useGeneralSettingsPalette();
53
+ const {showError, showSuccess} = useToastMessage();
54
+ const {currentCompany, mainCompany} = useGeneralSettingsConfig();
55
+ const companyId = Number(currentCompany?.id || mainCompany?.id || 0) || null;
56
+ const [settings, setSettings] = useState(null);
57
+ const [saving, setSaving] = useState(false);
58
+
59
+ const load = useCallback(async () => {
60
+ if (!companyId) return;
61
+ try {
62
+ setSettings(await fetchTicketSettings(companyId));
63
+ } catch (e) {
64
+ showError(e?.message || 'Não foi possível carregar as configurações de atendimento.');
65
+ }
66
+ }, [companyId, showError]);
67
+
68
+ useEffect(() => {
69
+ load();
70
+ }, [load]);
71
+
72
+ const save = async patch => {
73
+ if (saving) return;
74
+ setSaving(true);
75
+ try {
76
+ setSettings(await saveTicketSettings(companyId, patch));
77
+ showSuccess('Configuração de atendimento salva.');
78
+ } catch (e) {
79
+ showError(e?.message || 'Não foi possível salvar.');
80
+ } finally {
81
+ setSaving(false);
82
+ }
83
+ };
84
+
85
+ const toggle = (field, id) => {
86
+ const current = settings?.[field] || [];
87
+ save({[field]: current.includes(id) ? current.filter(x => x !== id) : [...current, id]});
88
+ };
89
+
90
+ if (!settings) return <ActivityIndicator style={{marginTop: 16}} />;
91
+ const employees = settings.employees || [];
92
+
93
+ return (
94
+ <View>
95
+ <GeneralSettingsSection
96
+ title="Suporte"
97
+ description="Chamados de suporte nascem sem responsável e são distribuídos entre as pessoas marcadas abaixo. Só elas respondem e aparecem como responsáveis em Atendimento de suporte.">
98
+ <Text style={styles.sectionTitle}>Regra de distribuição</Text>
99
+ {STRATEGIES.map(s => (
100
+ <Choice key={s.value} palette={palette} active={settings.support_strategy === s.value} label={s.label} onPress={() => save({support_strategy: s.value})} />
101
+ ))}
102
+ <Text style={[styles.sectionTitle, {marginTop: 12}]}>Quem atende suporte</Text>
103
+ {!employees.length ? <Text style={styles.helperText}>Nenhum colaborador vinculado à empresa.</Text> : null}
104
+ {employees.map(p => (
105
+ <Choice key={p.id} multi palette={palette} active={settings.support_responders.includes(p.id)} label={p.alias || p.name} onPress={() => toggle('support_responders', p.id)} />
106
+ ))}
107
+ </GeneralSettingsSection>
108
+
109
+ <GeneralSettingsSection
110
+ title="Comercial (CRM)"
111
+ description="Oportunidades nascem sem responsável e o motor do CRM distribui entre os vendedores. Vendedores sempre respondem; marque aqui os assistentes de vendas que também podem responder.">
112
+ <Text style={styles.sectionTitle}>Regra de distribuição</Text>
113
+ {STRATEGIES.map(s => (
114
+ <Choice key={s.value} palette={palette} active={settings.crm_strategy === s.value} label={s.label} onPress={() => save({crm_strategy: s.value})} />
115
+ ))}
116
+ <Text style={[styles.sectionTitle, {marginTop: 12}]}>Assistentes de vendas</Text>
117
+ {employees.map(p => (
118
+ <Choice key={p.id} multi palette={palette} active={settings.crm_assistants.includes(p.id)} label={p.alias || p.name} onPress={() => toggle('crm_assistants', p.id)} />
119
+ ))}
120
+ </GeneralSettingsSection>
121
+ {saving ? <ActivityIndicator style={{marginTop: 8}} /> : null}
122
+ </View>
123
+ );
124
+ }