@controleonline/ui-crm 1.0.69 → 1.0.74

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 +7 -7
  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 +7 -7
  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
@@ -0,0 +1,61 @@
1
+ /*
2
+ * @agents Pure parser for message text: **bold** / *bold*, _italic_, `code`, ~strike~, links and
3
+ * "- " / "* " bullets. Tested in src/tests/react/components/conversation/formatText.test.js.
4
+ */
5
+ const TOKEN = /(\*\*[^*\n]+\*\*|\*[^*\n]+\*|_[^_\n]+_|`[^`\n]+`|~[^~\n]+~|https?:\/\/[^\s<]+[^\s<.,;:!?)\]'"])/g;
6
+
7
+ const styleOf = token => {
8
+ if (token.startsWith('**')) return {bold: true, text: token.slice(2, -2)};
9
+ if (token.startsWith('*')) return {bold: true, text: token.slice(1, -1)};
10
+ if (token.startsWith('_')) return {italic: true, text: token.slice(1, -1)};
11
+ if (token.startsWith('`')) return {code: true, text: token.slice(1, -1)};
12
+ if (token.startsWith('~')) return {strike: true, text: token.slice(1, -1)};
13
+ return {link: token, text: token};
14
+ };
15
+
16
+ /** @returns {Array<Array<{text: string, bold?: boolean, italic?: boolean, code?: boolean, strike?: boolean, link?: string}>>} one array per line */
17
+ const parseRichText = value =>
18
+ String(value ?? '')
19
+ .replace(/\r\n/g, '\n')
20
+ .split('\n')
21
+ .map(line => {
22
+ const bullet = /^\s*[-*]\s+/.test(line);
23
+ const body = bullet ? line.replace(/^\s*[-*]\s+/, '') : line;
24
+ const parts = bullet ? [{text: '• '}] : [];
25
+ let last = 0;
26
+ body.replace(TOKEN, (match, _g, offset) => {
27
+ if (offset > last) parts.push({text: body.slice(last, offset)});
28
+ parts.push(styleOf(match));
29
+ last = offset + match.length;
30
+ return match;
31
+ });
32
+ if (last < body.length) parts.push({text: body.slice(last)});
33
+ return parts;
34
+ });
35
+
36
+ /** Day separator label: Hoje, Ontem or dd/mm/yyyy. */
37
+ const dayLabel = (date, now = new Date()) => {
38
+ const d = new Date(date);
39
+ if (Number.isNaN(d.getTime())) return '';
40
+ const start = x => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
41
+ const diff = Math.round((start(now) - start(d)) / 86400000);
42
+ if (diff === 0) return 'Hoje';
43
+ if (diff === 1) return 'Ontem';
44
+ return d.toLocaleDateString('pt-BR');
45
+ };
46
+
47
+ const timeLabel = date => {
48
+ const d = new Date(date);
49
+ return Number.isNaN(d.getTime()) ? '' : d.toLocaleTimeString('pt-BR', {hour: '2-digit', minute: '2-digit'});
50
+ };
51
+
52
+ const initialsOf = name =>
53
+ String(name || '?')
54
+ .trim()
55
+ .split(/\s+/)
56
+ .slice(0, 2)
57
+ .map(w => w[0] || '')
58
+ .join('')
59
+ .toUpperCase() || '?';
60
+
61
+ module.exports = {parseRichText, dayLabel, timeLabel, initialsOf};
@@ -0,0 +1,91 @@
1
+ /*
2
+ * @agents API of requests (relationship/support) shared by the customer screen (/support), the analyst screen (/ai) and CRM.
3
+ */
4
+ import {api} from '@controleonline/ui-common/src/api';
5
+
6
+ const {idOf} = require('../../pages/mcp/mcpChatUtils');
7
+
8
+ export const REQUEST_TYPES = [
9
+ {value: 'support', label: 'Suporte', hint: 'Dúvidas, problemas ou erros no sistema'},
10
+ {value: 'relationship', label: 'Comercial', hint: 'Planos, contratação, propostas e financeiro'},
11
+ ];
12
+ export const typeLabel = type => REQUEST_TYPES.find(t => t.value === type)?.label || type || '';
13
+
14
+ export const toItems = res => {
15
+ const items = res?.member || res?.['hydra:member'] || res || [];
16
+ return Array.isArray(items) ? items : [];
17
+ };
18
+
19
+ export const personName = p => (p && typeof p === 'object' ? p.alias || p.name || '' : '');
20
+
21
+ /** Status names of both contexts, open first (filter of the requests list). */
22
+ export const fetchRequestStatuses = async () => {
23
+ const lists = await Promise.all(REQUEST_TYPES.map(t => api.fetch('/statuses', {params: {context: t.value, itemsPerPage: 100}}).then(toItems).catch(() => [])));
24
+ const rank = {open: 0, pending: 1, closed: 2, canceled: 3};
25
+ const byName = new Map();
26
+ lists.flat().forEach(s => {
27
+ if (s?.status && !byName.has(s.status)) byName.set(s.status, s);
28
+ });
29
+ return [...byName.values()].sort((a, b) => (rank[a.realStatus] ?? 1) - (rank[b.realStatus] ?? 1));
30
+ };
31
+
32
+ export const fetchStatuses = async type => toItems(await api.fetch('/statuses', {params: {context: type, itemsPerPage: 100}}));
33
+ export const fetchCategories = async (type, companyId) =>
34
+ toItems(await api.fetch('/categories', {params: {context: type, ...(companyId ? {company: `/people/${companyId}`} : {}), itemsPerPage: 200}}));
35
+
36
+ export const fetchMyRequests = async (peopleId, statusName) =>
37
+ toItems(
38
+ await api.fetch('/tasks', {
39
+ params: {
40
+ client: `/people/${peopleId}`,
41
+ type: REQUEST_TYPES.map(t => t.value),
42
+ ...(statusName ? {'taskStatus.status': statusName} : {}),
43
+ 'order[alterDate]': 'desc',
44
+ itemsPerPage: 100,
45
+ },
46
+ }),
47
+ );
48
+
49
+ export const fetchTask = taskId => api.fetch(`/tasks/${taskId}`);
50
+
51
+ export const fetchMessages = async taskId =>
52
+ toItems(await api.fetch('/task_interations', {params: {'task.id': taskId, type: 'comment', 'order[id]': 'asc', itemsPerPage: 500}}));
53
+
54
+ /** Customer side: opens (type) or continues (taskId) a request through /mcp/chat. */
55
+ export const sendRequestMessage = ({taskId, type, text, fileId, companyId}) =>
56
+ api.post('/mcp/chat', {
57
+ ...(taskId ? {task_id: taskId} : {type}),
58
+ message: text || '',
59
+ ...(fileId ? {file_id: fileId} : {}),
60
+ ...(companyId ? {company_id: companyId} : {}),
61
+ });
62
+
63
+ /** Company side: public reply (goes to the customer) or internal note. */
64
+ export const postInteraction = (taskId, {text, fileId, visibility}) =>
65
+ api.post('/task_interations', {
66
+ task: `/tasks/${taskId}`,
67
+ // Plain text label: the API column is not utf8mb4 (no emoji).
68
+ body: text || (fileId ? 'Anexo' : ''),
69
+ type: 'comment',
70
+ visibility,
71
+ ...(fileId ? {file: `/files/${fileId}`} : {}),
72
+ });
73
+
74
+ export const updateTask = (task, patch) => api.put(`/tasks/${idOf(task)}`, patch);
75
+
76
+ export const fetchResponders = (type, companyId) => api.fetch('/tickets/responders', {params: {type, company_id: companyId}});
77
+
78
+ export const fetchCompanyAis = async companyId => {
79
+ try {
80
+ const res = await api.fetch('/mcp/chat/providers', {params: {company_id: companyId}});
81
+ return Array.isArray(res?.providers) ? res.providers : [];
82
+ } catch (e) {
83
+ return [];
84
+ }
85
+ };
86
+
87
+ export const assignAi = (taskId, companyId, instructions) => api.post('/mcp/chat/assign', {task_id: taskId, company_id: companyId, instructions});
88
+ export const takeOver = (taskId, companyId, type) => api.post('/mcp/chat/handoff', {task_id: taskId, company_id: companyId, type});
89
+
90
+ export const fetchTicketSettings = companyId => api.fetch('/tickets/settings', {params: {company_id: companyId}});
91
+ export const saveTicketSettings = (companyId, settings) => api.put('/tickets/settings', {company_id: companyId, ...settings});
@@ -0,0 +1,31 @@
1
+ /*
2
+ * @agents Native voice notes (expo-audio): returns {uri, name, mimeType} for uploadAttachment.
3
+ */
4
+ import {useCallback, useState} from 'react';
5
+ import {AudioModule, RecordingPresets, setAudioModeAsync, useAudioRecorder} from 'expo-audio';
6
+
7
+ export default function useAudioRecording() {
8
+ const recorder = useAudioRecorder(RecordingPresets.HIGH_QUALITY);
9
+ const [recording, setRecording] = useState(false);
10
+
11
+ const start = useCallback(async () => {
12
+ const permission = await AudioModule.requestRecordingPermissionsAsync();
13
+ if (!permission?.granted) throw new Error('Permita o uso do microfone para gravar áudio.');
14
+ await setAudioModeAsync({allowsRecording: true, playsInSilentMode: true});
15
+ await recorder.prepareToRecordAsync();
16
+ recorder.record();
17
+ setRecording(true);
18
+ }, [recorder]);
19
+
20
+ const finish = useCallback(
21
+ async keep => {
22
+ await recorder.stop();
23
+ setRecording(false);
24
+ await setAudioModeAsync({allowsRecording: false, playsInSilentMode: true});
25
+ return keep && recorder.uri ? {uri: recorder.uri, name: `audio-${Date.now()}.m4a`, mimeType: 'audio/mp4'} : null;
26
+ },
27
+ [recorder],
28
+ );
29
+
30
+ return {recording, start, stop: () => finish(true), cancel: () => finish(false)};
31
+ }
@@ -0,0 +1,54 @@
1
+ /*
2
+ * @agents Web voice notes: MediaRecorder -> File (audio/webm) ready for uploadAttachment.
3
+ */
4
+ import {useCallback, useRef, useState} from 'react';
5
+
6
+ export default function useAudioRecording() {
7
+ const [recording, setRecording] = useState(false);
8
+ const recorderRef = useRef(null);
9
+ const chunksRef = useRef([]);
10
+ const streamRef = useRef(null);
11
+
12
+ const start = useCallback(async () => {
13
+ if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getUserMedia || typeof MediaRecorder === 'undefined') {
14
+ throw new Error('Gravação de áudio não suportada neste navegador.');
15
+ }
16
+ const stream = await navigator.mediaDevices.getUserMedia({audio: true});
17
+ streamRef.current = stream;
18
+ chunksRef.current = [];
19
+ const recorder = new MediaRecorder(stream);
20
+ recorder.ondataavailable = event => event.data?.size && chunksRef.current.push(event.data);
21
+ recorder.start();
22
+ recorderRef.current = recorder;
23
+ setRecording(true);
24
+ }, []);
25
+
26
+ const finish = useCallback(
27
+ keep =>
28
+ new Promise(resolve => {
29
+ const recorder = recorderRef.current;
30
+ const release = () => streamRef.current?.getTracks?.().forEach(track => track.stop());
31
+ if (!recorder) {
32
+ setRecording(false);
33
+ resolve(null);
34
+ return;
35
+ }
36
+ recorder.onstop = () => {
37
+ release();
38
+ setRecording(false);
39
+ recorderRef.current = null;
40
+ if (!keep || !chunksRef.current.length) {
41
+ resolve(null);
42
+ return;
43
+ }
44
+ const type = recorder.mimeType || 'audio/webm';
45
+ const blob = new Blob(chunksRef.current, {type});
46
+ resolve(new File([blob], `audio-${Date.now()}.webm`, {type}));
47
+ };
48
+ recorder.stop();
49
+ }),
50
+ [],
51
+ );
52
+
53
+ return {recording, start, stop: () => finish(true), cancel: () => finish(false)};
54
+ }
@@ -0,0 +1,41 @@
1
+ /*
2
+ * @agents Colors of the shared conversation (requests, Support, CRM): always from the system theme
3
+ * (theme store + company theme), never fixed. WhatsApp-like roles map onto theme tokens.
4
+ */
5
+ import {useMemo} from 'react';
6
+ import {useGeneralSettingsPalette} from '../../pages/settings/GeneralSettings.styles';
7
+ import {withOpacity} from '@controleonline/../../src/styles/branding';
8
+
9
+ export default function useChatPalette() {
10
+ const t = useGeneralSettingsPalette();
11
+
12
+ return useMemo(() => {
13
+ const primary = t.primary || t.buttonBackground;
14
+ return {
15
+ ...t,
16
+ primary,
17
+ background: t.pageBackground,
18
+ panel: t.cardBackground || t.pageBackground,
19
+ border: t.cardBorder || t.listItemBorder,
20
+ text: t.textPrimary || t.cardText,
21
+ muted: t.textMuted || t.textSecondary,
22
+ // Own messages: primary bubble; others: card bubble; internal notes: warning tint.
23
+ mineBubble: withOpacity(primary, 0.9),
24
+ mineText: t.buttonText || t.textPrimary,
25
+ otherBubble: t.cardBackground || t.listItemBackground,
26
+ otherText: t.textPrimary || t.cardText,
27
+ noteBubble: withOpacity(t.warning || primary, 0.18),
28
+ noteBorder: t.warning || primary,
29
+ chip: t.badgeDisabledBackground || withOpacity(primary, 0.12),
30
+ chipText: t.textSecondary || t.textPrimary,
31
+ chipActive: primary,
32
+ chipActiveText: t.buttonText || t.textPrimary,
33
+ input: t.inputBackground || t.cardBackground,
34
+ inputBorder: t.inputBorder || t.cardBorder,
35
+ inputText: t.inputText || t.textPrimary,
36
+ placeholder: t.inputPlaceholderText || t.textMuted,
37
+ danger: t.error || t.iconDanger,
38
+ success: t.success || t.iconSuccess,
39
+ };
40
+ }, [t]);
41
+ }
@@ -1,342 +1,41 @@
1
- import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
2
- import { KeyboardAvoidingView, Platform, ScrollView, TextInput, TouchableOpacity, View } from 'react-native';
3
- import {Text} from 'react-native-animatable';
4
- import Icon from 'react-native-vector-icons/FontAwesome';
5
- import IconMaterial from 'react-native-vector-icons/MaterialIcons';
1
+ /*
2
+ * @agents CRM conversation of an opportunity (relationship request): the same analyst workspace as
3
+ * Support (TicketWorkspace — status, category, responsible, context, AI, WhatsApp-like chat), plus the
4
+ * client's marketing events. Only salesmen/sales assistants (or the AI) may reply (app-community#1600).
5
+ */
6
+ import React, {useEffect} from 'react';
6
7
  import {useNavigation, useRoute} from '@react-navigation/native';
7
- import {useStore} from '@store';
8
- import {useSafeAreaInsets} from 'react-native-safe-area-context';
9
8
  import useToastMessage from '../../hooks/useToastMessage';
10
- import {colors} from '@controleonline/../../src/styles/colors';
11
- import styles from './conversation.styles';
12
9
  import MarketingEventsSection from './components/MarketingEventsSection';
10
+ import TicketWorkspace from '../tickets/TicketWorkspace';
11
+
12
+ const {idOf} = require('../mcp/mcpChatUtils');
13
+
14
+ const peopleRefOf = value => {
15
+ const id = idOf(value);
16
+ return id ? `/people/${id}` : '';
17
+ };
13
18
 
14
19
  export default function CrmConversation() {
15
- const [message, setMessage] = useState('');
16
- const [messages, setMessages] = useState([]);
17
- const scrollViewRef = useRef(null);
18
- const navigation = useNavigation();
19
20
  const route = useRoute();
20
- const insets = useSafeAreaInsets();
21
+ const navigation = useNavigation();
21
22
  const {showError} = useToastMessage();
22
-
23
23
  const opportunity = route.params?.opportunity || null;
24
- const taskInteractionsStore = useStore('tasksInterations');
25
- const getters = taskInteractionsStore?.getters || {};
26
- const actions = taskInteractionsStore?.actions || {};
27
- const items = getters?.items || [];
28
- const peopleStore = useStore('people');
29
- const peopleGetters = peopleStore?.getters || {};
30
- const people = peopleGetters?.items || [];
31
-
32
- const taskResource =
33
- opportunity?.['@id'] || (opportunity?.id ? `/tasks/${opportunity.id}` : null);
34
-
35
- const canSend = !!message.trim() && !!taskResource;
36
- const primaryColor = colors.primary;
37
-
38
- const normalizePeopleReference = value => {
39
- if (!value) {
40
- return '';
41
- }
42
-
43
- const rawValue = typeof value === 'object' ? value['@id'] ?? value.id : value;
44
- if (rawValue == null) {
45
- return '';
46
- }
47
-
48
- const normalized = String(rawValue).trim();
49
- if (!normalized) {
50
- return '';
51
- }
52
-
53
- if (normalized.startsWith('/people/') || normalized.startsWith('/peoples/')) {
54
- return normalized;
55
- }
56
-
57
- if (normalized.startsWith('/')) {
58
- return normalized;
59
- }
60
-
61
- if (/^\d+$/.test(normalized)) {
62
- return `/people/${normalized}`;
63
- }
64
-
65
- return normalized;
66
- };
67
-
68
- const clientName = useMemo(() => {
69
- const directName =
70
- opportunity?.client?.name ||
71
- opportunity?.client?.realname ||
72
- opportunity?.client?.alias ||
73
- opportunity?.clientName ||
74
- opportunity?.people?.name;
75
-
76
- if (directName) {
77
- return directName;
78
- }
79
-
80
- const clientRef = normalizePeopleReference(opportunity?.client);
81
- if (!clientRef || !Array.isArray(people)) {
82
- return global.t?.t('users','label', 'client', 'Cliente');
83
- }
84
-
85
- const linkedPerson = people.find(
86
- person => normalizePeopleReference(person) === clientRef,
87
- );
88
-
89
- return linkedPerson?.name || linkedPerson?.realname || global.t?.t('users','label', 'client', 'Cliente');
90
- }, [opportunity, people]);
91
-
92
- const clientPeopleRef = useMemo(() => {
93
- return (
94
- normalizePeopleReference(opportunity?.client) ||
95
- normalizePeopleReference(opportunity?.people) ||
96
- ''
97
- );
98
- }, [opportunity]);
99
-
100
- const formatTime = timestamp =>
101
- timestamp.toLocaleTimeString('pt-br', {
102
- hour: '2-digit',
103
- minute: '2-digit',
104
- });
24
+ const taskId = idOf(opportunity) || Number(route.params?.taskId || 0);
105
25
 
106
26
  useEffect(() => {
107
- if (!opportunity) {
108
- showError(global.t?.t('users','error', 'opportunityNotFound', 'Oportunidade nao encontrada para abrir a conversa.'));
27
+ if (!taskId) {
28
+ showError(global.t?.t('users', 'error', 'opportunityNotFound', 'Oportunidade nao encontrada para abrir a conversa.'));
109
29
  navigation.goBack();
110
30
  }
111
- }, [opportunity, navigation, showError]);
112
-
113
- useEffect(() => {
114
- if (!taskResource || typeof actions.getItems !== 'function') {
115
- return;
116
- }
117
-
118
- actions.getItems({task: taskResource}).catch(error => {
119
- console.error('Erro ao carregar conversa:', error);
120
- showError(global.t?.t('users','error', 'loadMessages', 'Nao foi possivel carregar as mensagens da conversa.'));
121
- });
122
- }, [taskResource, actions, showError]);
123
-
124
- useEffect(() => {
125
- if (!Array.isArray(items) || items.length === 0) {
126
- setMessages([]);
127
- return;
128
- }
129
-
130
- const transformedMessages = items
131
- .filter(item => item?.body && item.body !== 'null')
132
- .map(item => ({
133
- id: item.id,
134
- text: String(item.body).replace(/"/g, ''),
135
- timestamp: new Date(item.createdAt),
136
- isFromUser: item.visibility === 'private',
137
- }))
138
- .sort((a, b) => a.timestamp - b.timestamp);
139
-
140
- setMessages(transformedMessages);
141
- }, [items]);
142
-
143
- useEffect(() => {
144
- if (messages.length > 0) {
145
- requestAnimationFrame(() => {
146
- scrollViewRef.current?.scrollToEnd({animated: true});
147
- });
148
- }
149
- }, [messages]);
150
-
151
- const formatDate = timestamp => {
152
- const today = new Date();
153
- const messageDate = new Date(timestamp);
154
-
155
- if (messageDate.toDateString() === today.toDateString()) {
156
- return global.t?.t('users','date', 'today', 'Hoje');
157
- }
158
-
159
- const yesterday = new Date(today);
160
- yesterday.setDate(yesterday.getDate() - 1);
161
-
162
- if (messageDate.toDateString() === yesterday.toDateString()) {
163
- return global.t?.t('users','date', 'yesterday', 'Ontem');
164
- }
165
-
166
- return messageDate.toLocaleDateString('pt-br', {
167
- day: '2-digit',
168
- month: '2-digit',
169
- year: 'numeric',
170
- });
171
- };
172
-
173
- const sendMessage = async () => {
174
- if (!canSend || typeof actions.save !== 'function') {
175
- return;
176
- }
177
-
178
- try {
179
- await actions.save({
180
- body: message.trim(),
181
- file: null,
182
- task: taskResource,
183
- type: 'comment',
184
- visibility: 'public',
185
- });
186
-
187
- setMessage('');
188
- await actions.getItems?.({task: taskResource});
189
- } catch (error) {
190
- console.error('Erro ao enviar mensagem:', error);
191
- showError(global.t?.t('users','error', 'sendMessage', 'Nao foi possivel enviar a mensagem.'));
192
- }
193
- };
194
-
195
- const handleInputKeyPress = event => {
196
- const key = event?.nativeEvent?.key;
197
- const shift = !!event?.nativeEvent?.shiftKey;
198
-
199
- if (key === 'Enter' && !shift) {
200
- event?.preventDefault?.();
201
- sendMessage();
202
- }
203
- };
204
-
205
- const renderMessage = (msg, index) => {
206
- const showDate =
207
- index === 0 ||
208
- formatDate(msg.timestamp) !== formatDate(messages[index - 1].timestamp);
209
-
210
- return (
211
- <View key={msg.id || `${msg.timestamp}-${index}`}>
212
- {showDate && (
213
- <View style={styles.dateContainer}>
214
- <Text style={styles.dateText}>{formatDate(msg.timestamp)}</Text>
215
- </View>
216
- )}
217
-
218
- <View
219
- style={[
220
- styles.messageContainer,
221
- msg.isFromUser ? styles.userMessage : styles.otherMessage,
222
- ]}>
223
- <View
224
- style={[
225
- styles.messageBubble,
226
- msg.isFromUser ? styles.userBubble : styles.otherBubble,
227
- ]}>
228
- <Text
229
- style={[
230
- styles.messageText,
231
- msg.isFromUser
232
- ? styles.userMessageText
233
- : styles.otherMessageText,
234
- ]}>
235
- {msg.text}
236
- </Text>
237
- <Text
238
- style={[
239
- styles.messageTime,
240
- msg.isFromUser
241
- ? styles.userMessageTime
242
- : styles.otherMessageTime,
243
- ]}>
244
- {formatTime(msg.timestamp)}
245
- </Text>
246
- </View>
247
- </View>
248
- </View>
249
- );
250
- };
31
+ }, [taskId, navigation, showError]);
251
32
 
33
+ if (!taskId) return null;
34
+ const client = opportunity?.client;
252
35
  return (
253
- <KeyboardAvoidingView
254
- style={styles.container}
255
- behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
256
- <View
257
- style={[
258
- styles.header,
259
- {
260
- paddingTop: Math.max(insets.top, 10),
261
- backgroundColor: primaryColor,
262
- },
263
- ]}>
264
- <TouchableOpacity
265
- style={styles.backButton}
266
- onPress={() => navigation.goBack()}>
267
- <Icon name="arrow-left" size={22} color="#FFFFFF" />
268
- </TouchableOpacity>
269
-
270
- <View style={styles.headerInfo}>
271
- <View style={styles.avatar}>
272
- <Icon name="user" size={18} color="#FFFFFF" />
273
- </View>
274
- <View style={styles.headerText}>
275
- <Text style={styles.headerName}>
276
- {clientName}
277
- </Text>
278
- </View>
279
- </View>
280
- </View>
281
-
282
- <MarketingEventsSection peopleRef={clientPeopleRef} peopleName={clientName} />
283
-
284
- <ScrollView
285
- ref={scrollViewRef}
286
- style={styles.messagesContainer}
287
- contentContainerStyle={[
288
- styles.messagesContent,
289
- messages.length === 0 && styles.messagesContentEmpty,
290
- ]}
291
- showsVerticalScrollIndicator={false}>
292
- {messages.length === 0 ? (
293
- <View style={styles.emptyStateContainer}>
294
- <View style={styles.emptyStateIconCircle}>
295
- <IconMaterial name="chat-bubble-outline" size={72} color="#94A3B8" />
296
- </View>
297
- <Text style={styles.emptyStateTitle}>
298
- {global.t?.t('users','state', 'emptyTitle', 'Nenhuma mensagem ainda')}
299
- </Text>
300
- <Text style={styles.emptyStateSubtitle}>
301
- {global.t?.t('users','state', 'emptySubtitle', 'Inicie a conversa enviando a primeira mensagem.')}
302
- </Text>
303
- </View>
304
- ) : (
305
- messages.map((msg, index) => renderMessage(msg, index))
306
- )}
307
- </ScrollView>
308
-
309
- <View style={[styles.inputContainer, {paddingBottom: Math.max(insets.bottom, 8)}]}>
310
- <View style={styles.inputWrapper}>
311
- <TextInput
312
- style={styles.textInput}
313
- value={message}
314
- onChangeText={setMessage}
315
- placeholder={global.t?.t('users','placeholder', 'message', 'Digite uma mensagem...')}
316
- placeholderTextColor="#7A8794"
317
- multiline={false}
318
- maxLength={1000}
319
- returnKeyType="send"
320
- blurOnSubmit={false}
321
- onSubmitEditing={sendMessage}
322
- onKeyPress={handleInputKeyPress}
323
- />
324
- </View>
325
-
326
- <TouchableOpacity
327
- style={[
328
- styles.sendButton,
329
- canSend ? styles.sendButtonActive : styles.sendButtonInactive,
330
- ]}
331
- onPress={sendMessage}
332
- disabled={!canSend}>
333
- <IconMaterial
334
- name="send"
335
- size={20}
336
- color={canSend ? '#FFFFFF' : '#B8C2CC'}
337
- />
338
- </TouchableOpacity>
339
- </View>
340
- </KeyboardAvoidingView>
36
+ <TicketWorkspace
37
+ taskId={taskId}
38
+ extra={client ? <MarketingEventsSection peopleRef={peopleRefOf(client)} peopleName={client?.name || client?.alias || 'Cliente'} /> : null}
39
+ />
341
40
  );
342
41
  }