@controleonline/ui-common 1.2.108 → 1.2.109

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,90 +1,91 @@
1
1
  import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
- import { ActivityIndicator, Platform, RefreshControl, ScrollView, Text, TextInput, TouchableOpacity, View } from 'react-native';
2
+ import {
3
+ ScrollView,
4
+ Text,
5
+ View,
6
+ } from 'react-native';
3
7
  import { SafeAreaView } from 'react-native-safe-area-context';
4
8
  import { useFocusEffect } from '@react-navigation/native';
5
9
  import Icon from 'react-native-vector-icons/Feather';
6
10
  import QRCode from 'react-native-qrcode-svg';
7
11
 
8
- import useToastMessage from '@controleonline/ui-crm/src/react/hooks/useToastMessage';
9
12
  import { useStore } from '@store';
10
13
  import { colors } from '@controleonline/../../src/styles/colors';
11
- import styles from './WhatsAppConnectionPage.styles';
14
+ import { createStyles } from './WhatsAppConnectionPage.styles';
12
15
  import {
16
+ resolveThemePalette,
17
+ withOpacity,
18
+ } from '@controleonline/../../src/styles/branding';
19
+ import DefaultTable from '@controleonline/ui-default/src/react/components/table/DefaultTable';
20
+ import WhatsAppProviderForm from './WhatsAppProviderForm';
21
+ import {
22
+ CHANNEL_WHATSAPP_OFFICIAL,
13
23
  PROVIDER_OFFICIAL,
14
24
  PROVIDER_UNOFFICIAL,
15
25
  extractDigits,
26
+ formatApiError,
16
27
  formatPhoneLabel,
17
28
  normalizeConnection,
18
29
  toArray,
19
- formatApiError,
20
- buildOfficialProviderConfig,
21
30
  } from './whatsAppConnectionHelpers';
22
- import WhatsAppProviderForm from './WhatsAppProviderForm';
23
- import {
24
- resolveThemePalette,
25
- withOpacity,
26
- } from '@controleonline/../../src/styles/branding';
27
-
28
- const shadowStyle = Platform.select({
29
- ios: {
30
- shadowColor: '#0F172A',
31
- shadowOffset: { width: 0, height: 8 },
32
- shadowOpacity: 0.08,
33
- shadowRadius: 16,
34
- },
35
- android: { elevation: 3 },
36
- web: { boxShadow: '0 10px 24px rgba(15,23,42,0.08)' },
37
- });
38
-
39
-
40
- const sanitizeDdi = value => extractDigits(value).slice(0, 3);
41
- const sanitizeDdd = value => extractDigits(value).slice(0, 2);
42
- const sanitizePhone = value => extractDigits(value).slice(0, 9);
43
31
 
44
32
  export default function WhatsAppConnectionPage() {
45
33
  const peopleStore = useStore('people');
46
34
  const themeStore = useStore('theme');
47
35
  const connectionsStore = useStore('connections');
48
- const { currentCompany } = peopleStore.getters;
49
- const { colors: themeColors } = themeStore.getters;
50
- const connectionsActions = connectionsStore.actions;
51
- const { showError, showSuccess, showInfo } = useToastMessage();
36
+ const connectionsActions = connectionsStore.actions || {};
52
37
 
38
+ const { currentCompany } = peopleStore.getters || {};
39
+ const { colors: themeColors } = themeStore.getters || {};
53
40
  const brandColors = useMemo(
54
41
  () =>
55
42
  resolveThemePalette(
56
- {
57
- ...themeColors,
58
- ...(currentCompany?.theme?.colors || {}),
59
- },
43
+ { ...themeColors, ...(currentCompany?.theme?.colors || {}) },
60
44
  colors,
61
45
  ),
62
- [themeColors, currentCompany?.id],
46
+ [themeColors, currentCompany],
63
47
  );
48
+ const styles = useMemo(() => createStyles(brandColors), [brandColors]);
64
49
 
65
- const [loading, setLoading] = useState(true);
66
- const [refreshing, setRefreshing] = useState(false);
67
- const [submitting, setSubmitting] = useState(false);
68
- const [connections, setConnections] = useState([]);
50
+ const providerId = currentCompany?.id;
51
+ const peopleIri = useMemo(
52
+ () => (providerId ? `/people/${String(providerId).replace(/\D/g, '')}` : ''),
53
+ [providerId],
54
+ );
55
+ const requestParams = useMemo(
56
+ () => (peopleIri ? { people: peopleIri } : {}),
57
+ [peopleIri],
58
+ );
59
+
60
+ const [providerMode, setProviderMode] = useState(PROVIDER_UNOFFICIAL);
69
61
  const [ddi, setDdi] = useState('55');
70
62
  const [ddd, setDdd] = useState('');
71
63
  const [phone, setPhone] = useState('');
72
- const [providerMode, setProviderMode] = useState(PROVIDER_UNOFFICIAL);
73
64
  const [accessToken, setAccessToken] = useState('');
74
65
  const [phoneNumberId, setPhoneNumberId] = useState('');
75
66
  const [apiVersion, setApiVersion] = useState('v22.0');
67
+ const [selectedId, setSelectedId] = useState(null);
68
+ const [selectedStatusIri, setSelectedStatusIri] = useState(null);
76
69
  const [qrValue, setQrValue] = useState('');
77
70
  const [connectionStatus, setConnectionStatus] = useState('');
78
- const [lastRequestedPhone, setLastRequestedPhone] = useState('');
79
-
71
+ const [submitting, setSubmitting] = useState(false);
72
+ const [feedback, setFeedback] = useState(null);
80
73
  const pollingRef = useRef(null);
81
- const providerId = currentCompany?.id;
82
- const peopleIri = useMemo(
83
- () => (providerId ? `/people/${String(providerId).replace(/\D/g, '')}` : ''),
84
- [providerId],
74
+
75
+ const completePhone = useMemo(
76
+ () => `${extractDigits(ddi)}${extractDigits(ddd)}${extractDigits(phone)}`,
77
+ [ddi, ddd, phone],
85
78
  );
86
79
 
87
- const completePhone = useMemo(() => `${ddi}${ddd}${phone}`, [ddi, ddd, phone]);
80
+ const showError = useCallback(message => {
81
+ setFeedback({ type: 'error', message: String(message || 'Erro') });
82
+ }, []);
83
+ const showSuccess = useCallback(message => {
84
+ setFeedback({ type: 'success', message: String(message || 'OK') });
85
+ }, []);
86
+ const showInfo = useCallback(message => {
87
+ setFeedback({ type: 'info', message: String(message || '') });
88
+ }, []);
88
89
 
89
90
  const clearPolling = useCallback(() => {
90
91
  if (pollingRef.current) {
@@ -93,88 +94,77 @@ export default function WhatsAppConnectionPage() {
93
94
  }
94
95
  }, []);
95
96
 
96
- const loadConnections = useCallback(async () => {
97
- if (!peopleIri) {
98
- setConnections([]);
99
- setLoading(false);
100
- return [];
101
- }
102
-
103
- try {
104
- const response = await connectionsActions.getItems({
105
- people: peopleIri,
106
- });
107
- const normalized = toArray(response).map(normalizeConnection);
108
- setConnections(normalized);
109
- return normalized;
110
- } catch (error) {
111
- showError(formatApiError(error));
112
- setConnections([]);
113
- return [];
114
- } finally {
115
- setLoading(false);
116
- }
117
- }, [connectionsActions, peopleIri, showError]);
118
-
119
- const requestQrCode = useCallback(async phoneNumber => {
120
- const targetPhone = extractDigits(phoneNumber);
121
- if (!targetPhone) {
122
- showError('Informe DDI, DDD e telefone para gerar o QR Code.');
123
- return null;
124
- }
125
-
126
- try {
127
- setSubmitting(true);
128
- const response = await connectionsActions.createWhatsappConnection({
129
- phone: targetPhone,
130
- });
131
-
132
- const nextStatus = String(response?.status || '').trim();
133
- const nextQr = String(response?.qr || '').trim();
134
-
135
- setLastRequestedPhone(targetPhone);
136
- setConnectionStatus(nextStatus || 'Aguardando autenticacao');
137
-
138
- if (nextQr) {
139
- setQrValue(nextQr);
97
+ const resolveStatusIri = useCallback(
98
+ item => {
99
+ const status = item?.status;
100
+ if (!status) return selectedStatusIri;
101
+ if (typeof status === 'string' && status.startsWith('/')) return status;
102
+ if (typeof status === 'object') {
103
+ return status['@id'] || status.id || selectedStatusIri;
140
104
  }
105
+ return selectedStatusIri;
106
+ },
107
+ [selectedStatusIri],
108
+ );
141
109
 
142
- if (nextStatus === 'CONNECTED') {
110
+ const requestQrCode = useCallback(
111
+ async phoneNumber => {
112
+ const targetPhone = extractDigits(phoneNumber);
113
+ if (!targetPhone) {
114
+ showError('Informe DDI, DDD e telefone para gerar o QR Code.');
115
+ return null;
116
+ }
117
+ try {
118
+ setSubmitting(true);
119
+ const response = await connectionsActions.createWhatsappConnection({
120
+ phone: targetPhone,
121
+ });
122
+ const nextStatus = String(response?.status || '').trim();
123
+ const nextQr = String(response?.qr || '').trim();
124
+ setConnectionStatus(nextStatus || 'Aguardando autenticacao');
125
+ if (nextQr) setQrValue(nextQr);
126
+ if (nextStatus === 'CONNECTED') {
127
+ clearPolling();
128
+ setQrValue('');
129
+ showSuccess('WhatsApp conectado com sucesso.');
130
+ connectionsStore.actions?.getItems?.({ people: peopleIri });
131
+ }
132
+ return response;
133
+ } catch (error) {
143
134
  clearPolling();
144
- setQrValue('');
145
- showSuccess('WhatsApp conectado com sucesso.');
146
- await loadConnections();
135
+ showError(formatApiError(error));
136
+ return null;
137
+ } finally {
138
+ setSubmitting(false);
147
139
  }
140
+ },
141
+ [
142
+ clearPolling,
143
+ connectionsActions,
144
+ connectionsStore.actions,
145
+ peopleIri,
146
+ showError,
147
+ showSuccess,
148
+ ],
149
+ );
148
150
 
149
- return response;
150
- } catch (error) {
151
+ const startPolling = useCallback(
152
+ async selectedPhone => {
153
+ const targetPhone = extractDigits(selectedPhone || completePhone);
154
+ if (!targetPhone) {
155
+ showError('Informe DDI, DDD e telefone para gerar o QR Code.');
156
+ return;
157
+ }
151
158
  clearPolling();
152
- showError(formatApiError(error));
153
- return null;
154
- } finally {
155
- setSubmitting(false);
156
- }
157
- }, [clearPolling, connectionsActions, loadConnections, showError, showSuccess]);
158
-
159
- const startPolling = useCallback(async selectedPhone => {
160
- const targetPhone = extractDigits(selectedPhone || completePhone);
161
- if (!targetPhone) {
162
- showError('Informe DDI, DDD e telefone para gerar o QR Code.');
163
- return;
164
- }
165
-
166
- clearPolling();
167
- const response = await requestQrCode(targetPhone);
168
- if (response?.status === 'CONNECTED') {
169
- return;
170
- }
171
-
172
- showInfo('Aguardando autenticacao do WhatsApp pelo QR Code.');
173
- pollingRef.current = setInterval(() => {
174
- requestQrCode(targetPhone);
175
- }, 5000);
176
- }, [clearPolling, completePhone, requestQrCode, showError, showInfo]);
177
-
159
+ const response = await requestQrCode(targetPhone);
160
+ if (response?.status === 'CONNECTED') return;
161
+ showInfo('Aguardando autenticacao do WhatsApp pelo QR Code.');
162
+ pollingRef.current = setInterval(() => {
163
+ requestQrCode(targetPhone);
164
+ }, 5000);
165
+ },
166
+ [clearPolling, completePhone, requestQrCode, showError, showInfo],
167
+ );
178
168
 
179
169
  const saveOfficialConnection = useCallback(async () => {
180
170
  const token = String(accessToken || '').trim();
@@ -183,19 +173,46 @@ export default function WhatsAppConnectionPage() {
183
173
  showError('Informe access token e phone_number_id da Cloud API.');
184
174
  return null;
185
175
  }
176
+ if (!peopleIri) {
177
+ showError('Selecione uma empresa.');
178
+ return null;
179
+ }
180
+
181
+ const items = toArray(connectionsStore.getters?.items).map(normalizeConnection);
182
+ const statusIri =
183
+ selectedStatusIri ||
184
+ items.map(i => i.statusIri).find(Boolean) ||
185
+ null;
186
+
187
+ if (!selectedId && !statusIri) {
188
+ showError(
189
+ 'Nao foi possivel resolver o status. Selecione uma conexao existente na lista ou crie uma nao oficial antes.',
190
+ );
191
+ return null;
192
+ }
193
+
186
194
  setSubmitting(true);
187
195
  try {
188
- const response = await connectionsActions.saveOfficialWhatsappConnection({
196
+ const payload = {
197
+ id: selectedId || undefined,
189
198
  accessToken: token,
190
199
  phoneNumberId: pnid,
191
200
  apiVersion: apiVersion || 'v22.0',
192
201
  people: peopleIri,
193
- name: `WhatsApp Oficial ${pnid}`,
194
- });
195
- showSuccess('Conexao oficial salva. Envios usarao a Cloud API diretamente.');
202
+ name: `WA Oficial ${pnid}`.slice(0, 50),
203
+ type: 'relationship',
204
+ status: statusIri || undefined,
205
+ };
206
+ const response = await connectionsActions.saveOfficialWhatsappConnection(payload);
207
+ showSuccess(
208
+ selectedId
209
+ ? 'Conexao atualizada para canal oficial (Cloud API).'
210
+ : 'Conexao oficial salva. Envios usarao a Cloud API.',
211
+ );
196
212
  setConnectionStatus('CONNECTED');
197
213
  setQrValue('');
198
- await loadConnections();
214
+ setProviderMode(PROVIDER_OFFICIAL);
215
+ connectionsStore.actions?.getItems?.({ people: peopleIri });
199
216
  return response;
200
217
  } catch (error) {
201
218
  showError(formatApiError(error));
@@ -203,272 +220,171 @@ export default function WhatsAppConnectionPage() {
203
220
  } finally {
204
221
  setSubmitting(false);
205
222
  }
206
- }, [accessToken, phoneNumberId, apiVersion, connectionsActions, peopleIri, loadConnections, showError, showSuccess]);
223
+ }, [
224
+ accessToken,
225
+ phoneNumberId,
226
+ apiVersion,
227
+ peopleIri,
228
+ selectedId,
229
+ selectedStatusIri,
230
+ connectionsActions,
231
+ connectionsStore.getters?.items,
232
+ connectionsStore.actions,
233
+ showError,
234
+ showSuccess,
235
+ ]);
207
236
 
208
237
  const handlePrimaryAction = useCallback(async () => {
209
238
  if (providerMode === PROVIDER_OFFICIAL) {
210
239
  return saveOfficialConnection();
211
240
  }
212
- return handlePrimaryAction();
241
+ return startPolling(completePhone);
213
242
  }, [providerMode, saveOfficialConnection, startPolling, completePhone]);
214
243
 
215
- useFocusEffect(
216
- useCallback(() => {
217
- setLoading(true);
218
- loadConnections();
219
-
220
- return () => {
221
- clearPolling();
222
- };
223
- }, [clearPolling, loadConnections]),
224
- );
225
-
226
- useEffect(() => () => clearPolling(), [clearPolling]);
227
-
228
- const onRefresh = useCallback(async () => {
229
- setRefreshing(true);
230
- try {
231
- await loadConnections();
232
- } finally {
233
- setRefreshing(false);
234
- }
235
- }, [loadConnections]);
236
-
237
244
  const handleUseExistingConnection = useCallback(item => {
238
- const nextDdi = String(item?.phone?.ddi || '55');
239
- const nextDdd = String(item?.phone?.ddd || '');
240
- const nextPhone = extractDigits(item?.phone?.phone || '');
241
-
245
+ const raw = item || {};
246
+ const normalized = normalizeConnection(raw);
247
+ const nextDdi = String(raw?.phone?.ddi || '55');
248
+ const nextDdd = String(raw?.phone?.ddd || '');
249
+ const nextPhone = extractDigits(raw?.phone?.phone || '');
242
250
  setDdi(nextDdi);
243
251
  setDdd(nextDdd);
244
252
  setPhone(nextPhone);
245
- setConnectionStatus(item?.status || 'Pendente');
246
- setLastRequestedPhone(`${nextDdi}${nextDdd}${nextPhone}`);
253
+ setConnectionStatus(normalized.status || 'Pendente');
247
254
  setQrValue('');
248
- setProviderMode(item?.channel === PROVIDER_OFFICIAL ? PROVIDER_OFFICIAL : PROVIDER_UNOFFICIAL);
249
- if (item?.channel === PROVIDER_OFFICIAL) {
250
- setPhoneNumberId('');
251
- setAccessToken('');
252
- }
255
+ setSelectedId(normalized.numericId || null);
256
+ setSelectedStatusIri(normalized.statusIri || null);
257
+ setProviderMode(
258
+ normalized.channel === CHANNEL_WHATSAPP_OFFICIAL
259
+ ? PROVIDER_OFFICIAL
260
+ : PROVIDER_UNOFFICIAL,
261
+ );
262
+ setAccessToken('');
263
+ setPhoneNumberId('');
264
+ setFeedback({
265
+ type: 'info',
266
+ message: `Conexao #${normalized.numericId || '—'} selecionada. Ajuste o canal e salve.`,
267
+ });
253
268
  }, []);
254
269
 
270
+ useFocusEffect(
271
+ useCallback(() => {
272
+ if (peopleIri) {
273
+ connectionsStore.actions?.getItems?.({ people: peopleIri });
274
+ }
275
+ return () => clearPolling();
276
+ }, [peopleIri, clearPolling]),
277
+ );
278
+
279
+ useEffect(() => () => clearPolling(), [clearPolling]);
280
+
281
+ const renderConnectionCard = useCallback(
282
+ ({ item }) => {
283
+ if (!item) return null;
284
+ const n = normalizeConnection(item);
285
+ return (
286
+ <View>
287
+ <Text style={styles.previewName}>{n.name}</Text>
288
+ <Text style={styles.previewMeta}>
289
+ {n.phoneLabel} · {n.channel} · {n.status}
290
+ </Text>
291
+ </View>
292
+ );
293
+ },
294
+ [styles],
295
+ );
296
+
255
297
  if (!providerId) {
256
298
  return (
257
299
  <SafeAreaView style={styles.container} edges={['bottom']}>
258
300
  <View style={styles.centerState}>
259
301
  <Icon name="building" size={32} color="#94A3B8" />
260
302
  <Text style={styles.centerStateTitle}>Selecione uma empresa</Text>
261
- <Text style={styles.centerStateText}>
262
- A configuracao do WhatsApp depende da empresa ativa.
263
- </Text>
264
- </View>
265
- </SafeAreaView>
266
- );
267
- }
268
-
269
- if (loading) {
270
- return (
271
- <SafeAreaView style={[styles.container, { backgroundColor: brandColors.background }]} edges={['bottom']}>
272
- <View style={styles.centerState}>
273
- <ActivityIndicator size="large" color={brandColors.primary} />
274
- <Text style={styles.centerStateTitle}>Carregando canal</Text>
275
- <Text style={styles.centerStateText}>
276
- Buscando conexoes de WhatsApp da empresa ativa.
277
- </Text>
278
303
  </View>
279
304
  </SafeAreaView>
280
305
  );
281
306
  }
282
307
 
283
308
  return (
284
- <SafeAreaView style={[styles.container, { backgroundColor: brandColors.background }]} edges={['bottom']}>
309
+ <SafeAreaView
310
+ style={[styles.container, { backgroundColor: brandColors.background }]}
311
+ edges={['bottom']}>
285
312
  <ScrollView
286
- contentContainerStyle={styles.scroll}
287
- showsVerticalScrollIndicator={false}
288
- refreshControl={
289
- <RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={brandColors.primary} />
290
- }>
291
- <View style={[styles.heroCard, shadowStyle, { backgroundColor: brandColors.primary }]}>
292
- <View style={styles.heroCopy}>
293
- <Text style={styles.heroEyebrow}>CANAIS DE COMUNICACAO</Text>
294
- <Text style={styles.heroTitle}>WhatsApp</Text>
295
- <Text style={styles.heroText}>
296
- Gere o QR Code, acompanhe o status e gerencie os numeros conectados.
297
- </Text>
298
- </View>
299
- <View style={styles.heroBadge}>
300
- <Icon name="message-circle" size={22} color={brandColors.primary} />
301
- </View>
302
- </View>
303
-
304
- <View style={[styles.formCard, shadowStyle]}>
305
- <View style={styles.formHeader}>
306
- <View>
307
- <Text style={styles.cardTitle}>Nova autenticacao</Text>
308
- <Text style={styles.cardSubtitle}>
309
- Escolha Nao oficial (QR) ou Oficial (Cloud API) e preencha os dados.
310
- </Text>
311
- </View>
312
- <View style={[styles.statusBadge, { backgroundColor: withOpacity('#2563EB', 0.12) }]}>
313
- <Text style={styles.statusBadgeText}>{connectionStatus || 'Aguardando configuracao'}</Text>
314
- </View>
313
+ contentContainerStyle={{ padding: 12, paddingBottom: 32 }}
314
+ keyboardShouldPersistTaps="handled">
315
+ {feedback ? (
316
+ <View
317
+ style={[
318
+ styles.feedbackBox,
319
+ {
320
+ backgroundColor:
321
+ feedback.type === 'error'
322
+ ? withOpacity('#ef4444', 0.12)
323
+ : feedback.type === 'success'
324
+ ? withOpacity('#10b981', 0.12)
325
+ : withOpacity('#2563eb', 0.1),
326
+ },
327
+ ]}>
328
+ <Text style={styles.feedbackText}>{feedback.message}</Text>
315
329
  </View>
330
+ ) : null}
316
331
 
317
- <View style={styles.formRow}>
318
- <View style={styles.inputGroupSmall}>
319
- <Text style={styles.inputLabel}>DDI</Text>
320
- <TextInput
321
- keyboardType="number-pad"
322
- onChangeText={value => setDdi(sanitizeDdi(value))}
323
- placeholder="55"
324
- placeholderTextColor="#94A3B8"
325
- style={styles.input}
326
- value={ddi}
327
- />
328
- </View>
329
- <View style={styles.inputGroupSmall}>
330
- <Text style={styles.inputLabel}>DDD</Text>
331
- <TextInput
332
- keyboardType="number-pad"
333
- onChangeText={value => setDdd(sanitizeDdd(value))}
334
- placeholder="11"
335
- placeholderTextColor="#94A3B8"
336
- style={styles.input}
337
- value={ddd}
338
- />
339
- </View>
340
- <View style={styles.inputGroupLarge}>
341
- <Text style={styles.inputLabel}>Telefone</Text>
342
- <TextInput
343
- keyboardType="number-pad"
344
- onChangeText={value => setPhone(sanitizePhone(value))}
345
- placeholder="999999999"
346
- placeholderTextColor="#94A3B8"
347
- style={styles.input}
348
- value={phone}
349
- />
350
- </View>
351
- </View>
352
-
353
- <WhatsAppProviderForm
354
- styles={styles}
355
- brandColors={brandColors}
356
- providerMode={providerMode}
357
- setProviderMode={setProviderMode}
358
- accessToken={accessToken}
359
- setAccessToken={setAccessToken}
360
- phoneNumberId={phoneNumberId}
361
- setPhoneNumberId={setPhoneNumberId}
362
- apiVersion={apiVersion}
363
- setApiVersion={setApiVersion}
364
- submitting={submitting}
365
- onPrimaryAction={() => handlePrimaryAction()}
366
- />
367
-
368
- <Text style={styles.helperText}>
369
- Numero atual: {completePhone || 'Nao informado'}
332
+ {selectedId ? (
333
+ <Text style={styles.selectedHint}>
334
+ Editando conexao #{selectedId}
335
+ {providerMode === PROVIDER_OFFICIAL ? ' · modo oficial' : ''}
370
336
  </Text>
371
- </View>
372
-
373
- <View style={[styles.qrCard, shadowStyle]}>
374
- <View style={styles.qrHeader}>
375
- <View>
376
- <Text style={styles.cardTitle}>QR Code</Text>
377
- <Text style={styles.cardSubtitle}>
378
- Escaneie com o WhatsApp para concluir a autenticacao do canal.
379
- </Text>
380
- </View>
337
+ ) : null}
338
+
339
+ <WhatsAppProviderForm
340
+ styles={styles}
341
+ brandColors={brandColors}
342
+ providerMode={providerMode}
343
+ setProviderMode={setProviderMode}
344
+ ddi={ddi}
345
+ setDdi={setDdi}
346
+ ddd={ddd}
347
+ setDdd={setDdd}
348
+ phone={phone}
349
+ setPhone={setPhone}
350
+ accessToken={accessToken}
351
+ setAccessToken={setAccessToken}
352
+ phoneNumberId={phoneNumberId}
353
+ setPhoneNumberId={setPhoneNumberId}
354
+ apiVersion={apiVersion}
355
+ setApiVersion={setApiVersion}
356
+ submitting={submitting}
357
+ onPrimaryAction={handlePrimaryAction}
358
+ />
359
+
360
+ {connectionStatus ? (
361
+ <Text style={styles.statusLine}>Status: {connectionStatus}</Text>
362
+ ) : null}
363
+
364
+ {qrValue ? (
365
+ <View style={styles.qrWrap}>
366
+ <QRCode value={qrValue} size={180} />
381
367
  </View>
382
-
383
- {qrValue ? (
384
- <View style={styles.qrContent}>
385
- <View style={styles.qrWrap}>
386
- <QRCode value={qrValue} size={210} />
387
- </View>
388
- <Text style={styles.qrCaption}>
389
- Atualizando automaticamente a cada 5 segundos enquanto a autenticacao estiver pendente.
390
- </Text>
391
- </View>
392
- ) : (
393
- <View style={styles.emptyStateBox}>
394
- <Icon name="maximize" size={24} color="#94A3B8" />
395
- <Text style={styles.emptyStateTitle}>QR Code indisponivel</Text>
396
- <Text style={styles.emptyStateText}>
397
- Solicite um QR Code para o numero escolhido ou selecione uma conexao existente abaixo.
398
- </Text>
399
- </View>
400
- )}
401
- </View>
402
-
403
- <View style={styles.listHeader}>
404
- <View>
405
- <Text style={styles.cardTitle}>Conexoes existentes</Text>
406
- <Text style={styles.cardSubtitle}>
407
- Toque em um item para reutilizar o numero e solicitar um novo QR Code.
408
- </Text>
409
- </View>
410
- <View style={styles.countBadge}>
411
- <Text style={styles.countBadgeText}>{connections.length} item(ns)</Text>
412
- </View>
413
- </View>
414
-
415
- <View style={styles.listWrap}>
416
- {connections.length > 0 ? (
417
- connections.map(item => (
418
- <TouchableOpacity
419
- key={item.id}
420
- activeOpacity={0.92}
421
- onPress={() => handleUseExistingConnection(item)}
422
- style={[styles.connectionCard, shadowStyle]}>
423
- <View style={styles.connectionTop}>
424
- <View style={[styles.connectionIconWrap, { backgroundColor: withOpacity('#10b981', 0.12) }]}>
425
- <Icon name="phone-call" size={18} color="#10b981" />
426
- </View>
427
- <View style={[styles.connectionStatusBadge, { backgroundColor: withOpacity('#2563EB', 0.12) }]}>
428
- <Text style={styles.connectionStatusText}>{item.status}</Text>
429
- </View>
430
- </View>
431
-
432
- <Text style={styles.connectionName}>{item.name}</Text>
433
-
434
- <View style={styles.connectionMetaRow}>
435
- <View style={styles.connectionMetaItem}>
436
- <Text style={styles.connectionMetaLabel}>Telefone</Text>
437
- <Text style={styles.connectionMetaValue}>{item.phoneLabel}</Text>
438
- </View>
439
- <View style={styles.connectionMetaItem}>
440
- <Text style={styles.connectionMetaLabel}>Tipo</Text>
441
- <Text style={styles.connectionMetaValue}>{item.type}</Text>
442
- </View>
443
- </View>
444
-
445
- <View style={styles.connectionMetaRow}>
446
- <View style={styles.connectionMetaItem}>
447
- <Text style={styles.connectionMetaLabel}>Canal</Text>
448
- <Text style={styles.connectionMetaValue}>{item.channel}</Text>
449
- </View>
450
- <View style={styles.connectionMetaItem}>
451
- <Text style={styles.connectionMetaLabel}>Ultima sessao</Text>
452
- <Text style={styles.connectionMetaValue}>
453
- {extractDigits(item.phone?.phone || '') &&
454
- lastRequestedPhone &&
455
- lastRequestedPhone.endsWith(extractDigits(item.phone?.phone || ''))
456
- ? 'Selecionada'
457
- : 'Disponivel'}
458
- </Text>
459
- </View>
460
- </View>
461
- </TouchableOpacity>
462
- ))
463
- ) : (
464
- <View style={[styles.emptyStateBox, { marginTop: 4 }]}>
465
- <Icon name="inbox" size={24} color="#94A3B8" />
466
- <Text style={styles.emptyStateTitle}>Nenhuma conexao cadastrada</Text>
467
- <Text style={styles.emptyStateText}>
468
- O primeiro QR Code gerado vai iniciar a configuracao deste canal para a empresa.
469
- </Text>
470
- </View>
471
- )}
368
+ ) : null}
369
+
370
+ <View style={{ minHeight: 280, marginTop: 16 }}>
371
+ <DefaultTable
372
+ storeName="connections"
373
+ requestParams={requestParams}
374
+ initialViewMode="table"
375
+ forceCardsOnCompact
376
+ showToolbar
377
+ showRowActions={false}
378
+ showColumnFiltersButton={false}
379
+ showSearch
380
+ searchKey="search"
381
+ searchPlaceholder="Buscar conexao"
382
+ onRowPress={handleUseExistingConnection}
383
+ renderCard={renderConnectionCard}
384
+ totalItemsLabel="connections"
385
+ visibleColumnsPreferenceKey="whatsapp-connections"
386
+ accentColor={brandColors.primary}
387
+ />
472
388
  </View>
473
389
  </ScrollView>
474
390
  </SafeAreaView>