@controleonline/ui-crm 1.0.76 → 1.0.80

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.75",
2
+ "version": "1.0.79",
3
3
  "rc": 1,
4
- "branch": "rc/1.0.75-rc.1",
5
- "baseMaster": "fd914b7908a506526f94b71bf5e6d29a209f5bb9",
4
+ "branch": "rc/1.0.79-rc.1",
5
+ "baseMaster": "c035f8ef5c06d31cdcada0e7bb17f06b7c529bb8",
6
6
  "tasks": [
7
- 71
7
+ 86
8
8
  ],
9
9
  "frozen": true,
10
10
  "repositories": {
11
- "ControleOnline/ui-crm": "42709ef109b99026f250942062969af69798fe62"
11
+ "ControleOnline/ui-crm": "6d8cfc9c8163d8305abd4f708850c5c5ac6ea88d"
12
12
  }
13
13
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@controleonline/ui-crm",
3
- "version": "1.0.76",
3
+ "version": "1.0.80",
4
4
  "author": "ControleOnline",
5
5
  "description": "ControleOnline CRM Quasar UI Component",
6
6
  "license": "MIT",
@@ -1,6 +1,7 @@
1
1
  /*
2
2
  * @agents Message input, WhatsApp-like: Enter sends (Shift+Enter breaks the line), 📎 attaches a file,
3
- * 🎤 records a voice note (sent when recording stops). `onSend({text, file})` resolves true on success.
3
+ * 🎤 records a voice note (sent when recording stops). Sending never blocks typing: the input is cleared
4
+ * at once and `onSend({text, file})` queues the message (ConversationView shows it as pending).
4
5
  */
5
6
  import React, {useState} from 'react';
6
7
  import {ActivityIndicator, Platform, Text, TextInput, TouchableOpacity, View} from 'react-native';
@@ -10,23 +11,17 @@ import {selectFile} from './fileApi';
10
11
  export default function Composer({palette, placeholder, disabled, disabledText, onSend, top, onError}) {
11
12
  const [text, setText] = useState('');
12
13
  const [file, setFile] = useState(null);
13
- const [sending, setSending] = useState(false);
14
+ const sending = false;
14
15
  const audio = useAudioRecording();
15
16
 
16
- const send = async (payload = {text, file}) => {
17
- if (sending || (!String(payload.text || '').trim() && !payload.file)) return;
18
- setSending(true);
19
- try {
20
- const ok = await onSend({text: String(payload.text || '').trim(), file: payload.file || null});
21
- if (ok !== false && payload !== null) {
22
- setText('');
23
- setFile(null);
24
- }
25
- } catch (e) {
26
- onError?.(e?.message || 'Não foi possível enviar');
27
- } finally {
28
- setSending(false);
29
- }
17
+ const send = (payload = {text, file}) => {
18
+ const message = {text: String(payload.text || '').trim(), file: payload.file || null};
19
+ if (!message.text && !message.file) return;
20
+ setText('');
21
+ setFile(null);
22
+ Promise.resolve()
23
+ .then(() => onSend(message))
24
+ .catch(e => onError?.(e?.message || 'Não foi possível enviar'));
30
25
  };
31
26
 
32
27
  const attach = async () => {
@@ -45,7 +40,7 @@ export default function Composer({palette, placeholder, disabled, disabledText,
45
40
  return;
46
41
  }
47
42
  const voice = await audio.stop();
48
- if (voice) await send({text: '', file: voice});
43
+ if (voice) send({text: '', file: voice});
49
44
  } catch (e) {
50
45
  onError?.(e?.message || 'Não foi possível gravar');
51
46
  }
@@ -3,8 +3,8 @@
3
3
  * day with WhatsApp-like bubbles, and the composer. Uploads happen here: `onSend({text, fileId})`.
4
4
  * `describe(item)` returns {side: 'left'|'right', kind: 'note'|'ai'|'msg'|'hidden', author}.
5
5
  */
6
- import React, {useMemo, useRef} from 'react';
7
- import {ActivityIndicator, FlatList, KeyboardAvoidingView, Platform, Text, View} from 'react-native';
6
+ import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
7
+ import {ActivityIndicator, FlatList, KeyboardAvoidingView, Platform, Text, TouchableOpacity, View} from 'react-native';
8
8
  import Composer from './Composer';
9
9
  import MessageBubble from './MessageBubble';
10
10
  import useChatPalette from './useChatPalette';
@@ -28,16 +28,25 @@ export default function ConversationView({
28
28
  emptyText = 'Nenhuma mensagem ainda.',
29
29
  footer = null,
30
30
  onError,
31
+ pendingKind = 'msg',
31
32
  }) {
32
33
  const palette = useChatPalette();
33
34
  const listRef = useRef(null);
35
+ // Optimistic messages: shown at once (🕓), sent one by one in the background, removed when the
36
+ // conversation reloads with them; a failed one stays (⚠) and is re-sent with a tap.
37
+ const [pending, setPending] = useState([]);
38
+ const onSendRef = useRef(onSend);
39
+ const queueRef = useRef(Promise.resolve());
40
+ useEffect(() => {
41
+ onSendRef.current = onSend;
42
+ }, [onSend]);
34
43
 
35
44
  const rows = useMemo(() => {
36
45
  const out = [];
37
46
  let lastDay = '';
38
47
  let lastAuthor = '';
39
- (messages || []).forEach(item => {
40
- const meta = describe(item);
48
+ [...(messages || []), ...pending].forEach(item => {
49
+ const meta = item?.localId ? {side: 'right', kind: item.kind, author: 'Você'} : describe(item);
41
50
  if (meta.kind === 'hidden') return;
42
51
  const day = dayLabel(item?.createdAt);
43
52
  if (day && day !== lastDay) {
@@ -50,11 +59,41 @@ export default function ConversationView({
50
59
  lastAuthor = authorKey;
51
60
  });
52
61
  return out;
53
- }, [messages, describe]);
62
+ }, [messages, pending, describe]);
54
63
 
55
- const send = async ({text, file}) => {
56
- const fileId = file ? await uploadAttachment(file, uploadCompanyId) : null;
57
- return onSend({text, fileId});
64
+ const deliver = useCallback(
65
+ entry => {
66
+ queueRef.current = queueRef.current.then(async () => {
67
+ setPending(list => list.map(p => (p.localId === entry.localId ? {...p, status: 'pending'} : p)));
68
+ try {
69
+ const fileId = entry.upload ? await uploadAttachment(entry.upload, uploadCompanyId) : null;
70
+ // kind is captured when the message is written (a note stays a note if the mode changes).
71
+ await onSendRef.current({text: entry.text, fileId, kind: entry.kind});
72
+ setPending(list => list.filter(p => p.localId !== entry.localId));
73
+ } catch (e) {
74
+ setPending(list => list.map(p => (p.localId === entry.localId ? {...p, status: 'error'} : p)));
75
+ onError?.(e?.message || 'Não foi possível enviar');
76
+ }
77
+ // Lets React apply state from this send (e.g. a new request id) before the next one.
78
+ await new Promise(resolve => setTimeout(resolve, 0));
79
+ });
80
+ },
81
+ [uploadCompanyId, onError],
82
+ );
83
+
84
+ const send = ({text, file}) => {
85
+ const entry = {
86
+ localId: `local-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
87
+ text,
88
+ body: [file ? `📎 ${file.name || 'arquivo'}` : '', text].filter(Boolean).join('\n'),
89
+ upload: file || null,
90
+ createdAt: new Date().toISOString(),
91
+ status: 'pending',
92
+ kind: pendingKind,
93
+ };
94
+ setPending(list => [...list, entry]);
95
+ deliver(entry);
96
+ return true;
58
97
  };
59
98
 
60
99
  const renderRow = ({item: row}) =>
@@ -64,6 +103,11 @@ export default function ConversationView({
64
103
  {row.label}
65
104
  </Text>
66
105
  </View>
106
+ ) : row.item?.localId && row.item.status === 'error' ? (
107
+ <TouchableOpacity onPress={() => deliver(row.item)} accessibilityLabel="Reenviar mensagem">
108
+ <MessageBubble item={row.item} side={row.meta.side} kind={row.meta.kind} author={row.meta.author} showAuthor={row.showAuthor} palette={palette} />
109
+ <Text style={{color: palette.danger, fontSize: 11, textAlign: 'right', paddingHorizontal: 12}}>Não enviada · toque para reenviar</Text>
110
+ </TouchableOpacity>
67
111
  ) : (
68
112
  <MessageBubble item={row.item} side={row.meta.side} kind={row.meta.kind} author={row.meta.author} showAuthor={row.showAuthor} palette={palette} />
69
113
  );
@@ -16,6 +16,36 @@ export const toItems = res => {
16
16
  return Array.isArray(items) ? items : [];
17
17
  };
18
18
 
19
+ /**
20
+ * The app remounts screens while it boots (company, menus, device): a call made in that window can fail
21
+ * before reaching the network, and the screen then shows "not found" / an empty list until F5.
22
+ * Retry a few times (growing delay) before giving up.
23
+ */
24
+ export const retrying = async (fn, {attempts = 4, delayMs = 700} = {}) => {
25
+ let last;
26
+ for (let i = 0; i < attempts; i++) {
27
+ try {
28
+ return await fn();
29
+ } catch (e) {
30
+ last = e;
31
+ if (i < attempts - 1) await new Promise(resolve => setTimeout(resolve, delayMs * (i + 1)));
32
+ }
33
+ }
34
+ throw last;
35
+ };
36
+
37
+ const required = (value, message) => {
38
+ if (!value) throw new Error(message);
39
+ return value;
40
+ };
41
+
42
+ /** Task + its messages; an empty task response counts as a failure (retried). */
43
+ export const fetchTaskWithMessages = taskId =>
44
+ retrying(async () => {
45
+ const [task, messages] = await Promise.all([fetchTask(taskId), fetchMessages(taskId)]);
46
+ return [required(task, 'Solicitação não encontrada'), messages];
47
+ });
48
+
19
49
  export const personName = p => (p && typeof p === 'object' ? p.alias || p.name || '' : '');
20
50
 
21
51
  /** Status names of both contexts, open first (filter of the requests list). */
@@ -6,7 +6,7 @@
6
6
  import {useCallback, useEffect, useState} from 'react';
7
7
  import {useStore} from '@store';
8
8
  import useRealtimeReload from '../tickets/useRealtimeReload';
9
- import {fetchMessages, fetchMyRequests, fetchRequestStatuses, fetchTask, sendRequestMessage} from '../../components/conversation/requestApi';
9
+ import {fetchMyRequests, fetchRequestStatuses, fetchTaskWithMessages, retrying, sendRequestMessage} from '../../components/conversation/requestApi';
10
10
 
11
11
  const {idOf} = require('./mcpChatUtils');
12
12
 
@@ -30,13 +30,13 @@ export default function useRequests({onError}) {
30
30
  // Loaded once the session is ready (a first call before login returned nothing and never retried).
31
31
  useEffect(() => {
32
32
  if (!meId) return;
33
- fetchRequestStatuses().then(setStatuses).catch(() => setStatuses([]));
33
+ retrying(fetchRequestStatuses).then(setStatuses).catch(() => setStatuses([]));
34
34
  }, [meId, companyId]);
35
35
 
36
36
  const loadList = useCallback(async () => {
37
37
  if (!meId) return;
38
38
  try {
39
- setRequests(await fetchMyRequests(meId, statusFilter));
39
+ setRequests(await retrying(() => fetchMyRequests(meId, statusFilter)));
40
40
  } catch (e) {
41
41
  onError?.(e?.message || 'Não foi possível carregar as solicitações');
42
42
  } finally {
@@ -49,7 +49,7 @@ export default function useRequests({onError}) {
49
49
  if (!id) return;
50
50
  if (!quiet) setLoadingChat(true);
51
51
  try {
52
- const [t, m] = await Promise.all([fetchTask(id), fetchMessages(id)]);
52
+ const [t, m] = await fetchTaskWithMessages(id);
53
53
  setTask(t);
54
54
  setMessages(m);
55
55
  } catch (e) {
@@ -15,10 +15,9 @@ import {
15
15
  assignAi,
16
16
  fetchCategories,
17
17
  fetchCompanyAis,
18
- fetchMessages,
19
18
  fetchResponders,
20
19
  fetchStatuses,
21
- fetchTask,
20
+ fetchTaskWithMessages,
22
21
  personName,
23
22
  postInteraction,
24
23
  REQUEST_TYPES,
@@ -63,7 +62,7 @@ export default function TicketWorkspace({taskId, extra = null}) {
63
62
  if (!taskId || !meId) return;
64
63
  if (!quiet) setLoading(true);
65
64
  try {
66
- const [t, m] = await Promise.all([fetchTask(taskId), fetchMessages(taskId)]);
65
+ const [t, m] = await fetchTaskWithMessages(taskId);
67
66
  setTask(t);
68
67
  setMessages(m);
69
68
  } catch (e) {
@@ -129,8 +128,9 @@ export default function TicketWorkspace({taskId, extra = null}) {
129
128
  [providerId, task, meId],
130
129
  );
131
130
 
132
- const send = async ({text, fileId}) => {
133
- await postInteraction(taskId, {text, fileId, visibility: mode});
131
+ const send = async ({text, fileId, kind}) => {
132
+ const visibility = kind ? (kind === 'note' ? 'private' : 'public') : mode;
133
+ await postInteraction(taskId, {text, fileId, visibility});
134
134
  await load({quiet: true});
135
135
  return true;
136
136
  };
@@ -216,6 +216,7 @@ export default function TicketWorkspace({taskId, extra = null}) {
216
216
  loading={loading}
217
217
  describe={describe}
218
218
  onSend={send}
219
+ pendingKind={mode === 'public' ? 'msg' : 'note'}
219
220
  uploadCompanyId={providerId}
220
221
  placeholder={mode === 'public' ? 'Mensagem para o cliente' : 'Nota visível só para a equipe'}
221
222
  canSend={options.canReply}