@controleonline/ui-common 1.2.112 → 1.2.113

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 (54) hide show
  1. package/.release/rc-manifest.json +6 -6
  2. package/package.json +1 -1
  3. package/src/react/components/CategoryForm.js +539 -539
  4. package/src/react/components/DefaultProvider.native.js +2 -2
  5. package/src/react/components/DefaultProvider.web.js +2 -2
  6. package/src/react/components/integrations/IntegrationHero/index.js +1 -1
  7. package/src/react/components/integrations/IntegrationHero/styles.js +2 -2
  8. package/src/react/components/integrations/IntegrationTabs/index.js +1 -1
  9. package/src/react/components/integrations/IntegrationTabs/styles.js +1 -1
  10. package/src/react/pages/AiProviderConfigPage.js +304 -0
  11. package/src/react/pages/Connections.js +96 -18
  12. package/src/react/pages/Connections.styles.js +72 -72
  13. package/src/react/pages/Devices/detail/DeviceDetailHeader.js +1 -1
  14. package/src/react/pages/Devices/detail/DeviceDetailMovementSections.js +1 -1
  15. package/src/react/pages/Devices/detail/useDeviceDetailStateA.js +2 -2
  16. package/src/react/pages/Devices/detail/useDeviceDetailStateB.js +2 -2
  17. package/src/react/pages/Devices/deviceTypes/DeviceGroupCard.js +1 -1
  18. package/src/react/pages/Devices/deviceTypes/shared.js +2 -2
  19. package/src/react/pages/Devices.js +2 -2
  20. package/src/react/pages/Devices.styles.js +353 -353
  21. package/src/react/pages/Food99IntegrationPage/components/Food99CatalogTab.js +219 -219
  22. package/src/react/pages/Food99IntegrationPage/components/Food99OverviewTab.js +134 -134
  23. package/src/react/pages/Food99IntegrationPage/components/Food99PreviewModal.js +173 -173
  24. package/src/react/pages/Food99IntegrationPage/components/Food99QuickWalletModal.js +1 -1
  25. package/src/react/pages/Food99IntegrationPage/components/Food99SettingsTab.js +306 -306
  26. package/src/react/pages/Food99IntegrationPage/components/Food99StoreTab.js +417 -417
  27. package/src/react/pages/Food99IntegrationPage/index.js +1530 -1530
  28. package/src/react/pages/Food99IntegrationPage/styles.js +792 -792
  29. package/src/react/pages/IFoodIntegrationPage/components/IFoodOperationsTab.js +267 -267
  30. package/src/react/pages/IFoodIntegrationPage/components/IFoodOverviewTab.js +118 -118
  31. package/src/react/pages/IFoodIntegrationPage/components/IFoodPreviewModal.js +101 -101
  32. package/src/react/pages/IFoodIntegrationPage/components/IFoodStoreTab.js +150 -150
  33. package/src/react/pages/IFoodIntegrationPage/index.js +1298 -1298
  34. package/src/react/pages/Imports.js +1 -1
  35. package/src/react/pages/Imports.styles.js +223 -223
  36. package/src/react/pages/IntegrationConfigPage.js +2 -2
  37. package/src/react/pages/Integrations.js +15 -2
  38. package/src/react/pages/Integrations.styles.js +130 -130
  39. package/src/react/pages/LinkedInIntegrationPage.js +2 -2
  40. package/src/react/pages/ManagerOrderNotificationsPage.js +642 -642
  41. package/src/react/pages/MarketplaceIntegrationPage/components/MarketplaceProductCard.js +205 -205
  42. package/src/react/pages/MercadoLivreIntegrationPage.js +2 -2
  43. package/src/react/pages/PrinterDeviceDetailPage.js +1915 -1915
  44. package/src/react/pages/PrinterDeviceFormPage.js +2 -2
  45. package/src/react/pages/WhatsAppConnectionPage.js +364 -280
  46. package/src/react/pages/WhatsAppConnectionPage.styles.js +279 -315
  47. package/src/react/pages/WhatsAppProviderForm.js +1 -1
  48. package/src/react/pages/integrationsCatalog.js +32 -0
  49. package/src/react/pages/whatsAppConnectionHelpers.js +10 -38
  50. package/src/react/router/publicRoutes.js +0 -3
  51. package/src/react/utils/fileUrl.js +1 -1
  52. package/src/store/connections/customActions.js +14 -16
  53. package/src/store/connections/index.js +105 -109
  54. package/src/react/router/__tests__/publicRoutes.test.js +0 -12
@@ -1,91 +1,90 @@
1
1
  import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
- import {
3
- ScrollView,
4
- Text,
5
- View,
6
- } from 'react-native';
2
+ import { ActivityIndicator, Platform, RefreshControl, ScrollView, Text, TextInput, TouchableOpacity, View } from 'react-native';
7
3
  import { SafeAreaView } from 'react-native-safe-area-context';
8
4
  import { useFocusEffect } from '@react-navigation/native';
9
5
  import Icon from 'react-native-vector-icons/Feather';
10
6
  import QRCode from 'react-native-qrcode-svg';
11
7
 
8
+ import useToastMessage from '@controleonline/ui-crm/src/react/hooks/useToastMessage';
12
9
  import { useStore } from '@store';
13
- import { colors } from '@controleonline/ui-layout/src/styles/colors';
14
- import { createStyles } from './WhatsAppConnectionPage.styles';
15
- import {
16
- resolveThemePalette,
17
- withOpacity,
18
- } from '@controleonline/ui-layout/src/styles/branding';
19
- import DefaultTable from '@controleonline/ui-default/src/react/components/table/DefaultTable';
20
- import WhatsAppProviderForm from './WhatsAppProviderForm';
10
+ import { colors } from '@controleonline/../../src/styles/colors';
11
+ import styles from './WhatsAppConnectionPage.styles';
21
12
  import {
22
- CHANNEL_WHATSAPP_OFFICIAL,
23
13
  PROVIDER_OFFICIAL,
24
14
  PROVIDER_UNOFFICIAL,
25
15
  extractDigits,
26
- formatApiError,
27
16
  formatPhoneLabel,
28
17
  normalizeConnection,
29
18
  toArray,
19
+ formatApiError,
20
+ buildOfficialProviderConfig,
30
21
  } 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);
31
43
 
32
44
  export default function WhatsAppConnectionPage() {
33
45
  const peopleStore = useStore('people');
34
46
  const themeStore = useStore('theme');
35
47
  const connectionsStore = useStore('connections');
36
- const connectionsActions = connectionsStore.actions || {};
48
+ const { currentCompany } = peopleStore.getters;
49
+ const { colors: themeColors } = themeStore.getters;
50
+ const connectionsActions = connectionsStore.actions;
51
+ const { showError, showSuccess, showInfo } = useToastMessage();
37
52
 
38
- const { currentCompany } = peopleStore.getters || {};
39
- const { colors: themeColors } = themeStore.getters || {};
40
53
  const brandColors = useMemo(
41
54
  () =>
42
55
  resolveThemePalette(
43
- { ...themeColors, ...(currentCompany?.theme?.colors || {}) },
56
+ {
57
+ ...themeColors,
58
+ ...(currentCompany?.theme?.colors || {}),
59
+ },
44
60
  colors,
45
61
  ),
46
- [themeColors, currentCompany],
47
- );
48
- const styles = useMemo(() => createStyles(brandColors), [brandColors]);
49
-
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],
62
+ [themeColors, currentCompany?.id],
58
63
  );
59
64
 
60
- const [providerMode, setProviderMode] = useState(PROVIDER_UNOFFICIAL);
65
+ const [loading, setLoading] = useState(true);
66
+ const [refreshing, setRefreshing] = useState(false);
67
+ const [submitting, setSubmitting] = useState(false);
68
+ const [connections, setConnections] = useState([]);
61
69
  const [ddi, setDdi] = useState('55');
62
70
  const [ddd, setDdd] = useState('');
63
71
  const [phone, setPhone] = useState('');
72
+ const [providerMode, setProviderMode] = useState(PROVIDER_UNOFFICIAL);
64
73
  const [accessToken, setAccessToken] = useState('');
65
74
  const [phoneNumberId, setPhoneNumberId] = useState('');
66
75
  const [apiVersion, setApiVersion] = useState('v22.0');
67
- const [selectedId, setSelectedId] = useState(null);
68
- const [selectedStatusIri, setSelectedStatusIri] = useState(null);
69
76
  const [qrValue, setQrValue] = useState('');
70
77
  const [connectionStatus, setConnectionStatus] = useState('');
71
- const [submitting, setSubmitting] = useState(false);
72
- const [feedback, setFeedback] = useState(null);
73
- const pollingRef = useRef(null);
78
+ const [lastRequestedPhone, setLastRequestedPhone] = useState('');
74
79
 
75
- const completePhone = useMemo(
76
- () => `${extractDigits(ddi)}${extractDigits(ddd)}${extractDigits(phone)}`,
77
- [ddi, ddd, phone],
80
+ const pollingRef = useRef(null);
81
+ const providerId = currentCompany?.id;
82
+ const peopleIri = useMemo(
83
+ () => (providerId ? `/people/${String(providerId).replace(/\D/g, '')}` : ''),
84
+ [providerId],
78
85
  );
79
86
 
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
- }, []);
87
+ const completePhone = useMemo(() => `${ddi}${ddd}${phone}`, [ddi, ddd, phone]);
89
88
 
90
89
  const clearPolling = useCallback(() => {
91
90
  if (pollingRef.current) {
@@ -94,77 +93,88 @@ export default function WhatsAppConnectionPage() {
94
93
  }
95
94
  }, []);
96
95
 
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;
104
- }
105
- return selectedStatusIri;
106
- },
107
- [selectedStatusIri],
108
- );
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();
109
134
 
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;
135
+ setLastRequestedPhone(targetPhone);
136
+ setConnectionStatus(nextStatus || 'Aguardando autenticacao');
137
+
138
+ if (nextQr) {
139
+ setQrValue(nextQr);
116
140
  }
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) {
141
+
142
+ if (nextStatus === 'CONNECTED') {
134
143
  clearPolling();
135
- showError(formatApiError(error));
136
- return null;
137
- } finally {
138
- setSubmitting(false);
144
+ setQrValue('');
145
+ showSuccess('WhatsApp conectado com sucesso.');
146
+ await loadConnections();
139
147
  }
140
- },
141
- [
142
- clearPolling,
143
- connectionsActions,
144
- connectionsStore.actions,
145
- peopleIri,
146
- showError,
147
- showSuccess,
148
- ],
149
- );
150
148
 
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
- }
149
+ return response;
150
+ } catch (error) {
158
151
  clearPolling();
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
- );
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
+
168
178
 
169
179
  const saveOfficialConnection = useCallback(async () => {
170
180
  const token = String(accessToken || '').trim();
@@ -173,46 +183,19 @@ export default function WhatsAppConnectionPage() {
173
183
  showError('Informe access token e phone_number_id da Cloud API.');
174
184
  return null;
175
185
  }
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
-
194
186
  setSubmitting(true);
195
187
  try {
196
- const payload = {
197
- id: selectedId || undefined,
188
+ const response = await connectionsActions.saveOfficialWhatsappConnection({
198
189
  accessToken: token,
199
190
  phoneNumberId: pnid,
200
191
  apiVersion: apiVersion || 'v22.0',
201
192
  people: peopleIri,
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
- );
193
+ name: `WhatsApp Oficial ${pnid}`,
194
+ });
195
+ showSuccess('Conexao oficial salva. Envios usarao a Cloud API diretamente.');
212
196
  setConnectionStatus('CONNECTED');
213
197
  setQrValue('');
214
- setProviderMode(PROVIDER_OFFICIAL);
215
- connectionsStore.actions?.getItems?.({ people: peopleIri });
198
+ await loadConnections();
216
199
  return response;
217
200
  } catch (error) {
218
201
  showError(formatApiError(error));
@@ -220,79 +203,54 @@ export default function WhatsAppConnectionPage() {
220
203
  } finally {
221
204
  setSubmitting(false);
222
205
  }
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
- ]);
206
+ }, [accessToken, phoneNumberId, apiVersion, connectionsActions, peopleIri, loadConnections, showError, showSuccess]);
236
207
 
237
208
  const handlePrimaryAction = useCallback(async () => {
238
209
  if (providerMode === PROVIDER_OFFICIAL) {
239
210
  return saveOfficialConnection();
240
211
  }
241
- return startPolling(completePhone);
212
+ return handlePrimaryAction();
242
213
  }, [providerMode, saveOfficialConnection, startPolling, completePhone]);
243
214
 
244
- const handleUseExistingConnection = useCallback(item => {
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 || '');
250
- setDdi(nextDdi);
251
- setDdd(nextDdd);
252
- setPhone(nextPhone);
253
- setConnectionStatus(normalized.status || 'Pendente');
254
- setQrValue('');
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
- });
268
- }, []);
269
-
270
215
  useFocusEffect(
271
216
  useCallback(() => {
272
- if (peopleIri) {
273
- connectionsStore.actions?.getItems?.({ people: peopleIri });
274
- }
275
- return () => clearPolling();
276
- }, [peopleIri, clearPolling]),
217
+ setLoading(true);
218
+ loadConnections();
219
+
220
+ return () => {
221
+ clearPolling();
222
+ };
223
+ }, [clearPolling, loadConnections]),
277
224
  );
278
225
 
279
226
  useEffect(() => () => clearPolling(), [clearPolling]);
280
227
 
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
- );
228
+ const onRefresh = useCallback(async () => {
229
+ setRefreshing(true);
230
+ try {
231
+ await loadConnections();
232
+ } finally {
233
+ setRefreshing(false);
234
+ }
235
+ }, [loadConnections]);
236
+
237
+ 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
+
242
+ setDdi(nextDdi);
243
+ setDdd(nextDdd);
244
+ setPhone(nextPhone);
245
+ setConnectionStatus(item?.status || 'Pendente');
246
+ setLastRequestedPhone(`${nextDdi}${nextDdd}${nextPhone}`);
247
+ setQrValue('');
248
+ setProviderMode(item?.channel === PROVIDER_OFFICIAL ? PROVIDER_OFFICIAL : PROVIDER_UNOFFICIAL);
249
+ if (item?.channel === PROVIDER_OFFICIAL) {
250
+ setPhoneNumberId('');
251
+ setAccessToken('');
252
+ }
253
+ }, []);
296
254
 
297
255
  if (!providerId) {
298
256
  return (
@@ -300,91 +258,217 @@ export default function WhatsAppConnectionPage() {
300
258
  <View style={styles.centerState}>
301
259
  <Icon name="building" size={32} color="#94A3B8" />
302
260
  <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>
303
278
  </View>
304
279
  </SafeAreaView>
305
280
  );
306
281
  }
307
282
 
308
283
  return (
309
- <SafeAreaView
310
- style={[styles.container, { backgroundColor: brandColors.background }]}
311
- edges={['bottom']}>
284
+ <SafeAreaView style={[styles.container, { backgroundColor: brandColors.background }]} edges={['bottom']}>
312
285
  <ScrollView
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>
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} />
329
301
  </View>
330
- ) : null}
302
+ </View>
331
303
 
332
- {selectedId ? (
333
- <Text style={styles.selectedHint}>
334
- Editando conexao #{selectedId}
335
- {providerMode === PROVIDER_OFFICIAL ? ' · modo oficial' : ''}
336
- </Text>
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} />
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>
315
+ </View>
316
+
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>
367
351
  </View>
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}
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()}
387
366
  />
367
+
368
+ <Text style={styles.helperText}>
369
+ Numero atual: {completePhone || 'Nao informado'}
370
+ </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>
381
+ </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
+ )}
388
472
  </View>
389
473
  </ScrollView>
390
474
  </SafeAreaView>