@controleonline/ui-crm 1.0.84 → 1.0.87

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,12 @@
1
1
  {
2
- "version": "1.0.83",
2
+ "version": "1.0.87",
3
3
  "rc": 1,
4
- "branch": "rc/1.0.83-rc.1",
5
- "baseMaster": "88cc75124408d23d332ad1497f2ebfe89574b386",
6
- "tasks": [
7
- 92
8
- ],
4
+ "branch": "rc/1.0.87-rc.1",
5
+ "baseMaster": "e21f04e30423240b1a6294719d11bd2e5ce0e997",
6
+ "baseTag": "v1.0.86",
7
+ "tasks": [105],
9
8
  "frozen": true,
10
9
  "repositories": {
11
- "ControleOnline/ui-crm": "7e1b71beb980e5963fc0cd7908c8f045145a348c"
10
+ "ControleOnline/ui-crm": "2783818d7c529320fa8584006de36af15afb91d0"
12
11
  }
13
- }
12
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@controleonline/ui-crm",
3
- "version": "1.0.84",
3
+ "version": "1.0.87",
4
4
  "author": "ControleOnline",
5
5
  "description": "ControleOnline CRM Quasar UI Component",
6
6
  "license": "MIT",
@@ -1,18 +1,23 @@
1
1
  /*
2
- * @agents One message, WhatsApp-like: avatar + name for others, own messages on the right with
3
- * time and delivery ticks, internal notes highlighted. Text uses RichText; files use Attachment.
2
+ * @agents One message, WhatsApp group-like: requests are group conversations, so every other participant
3
+ * (customer, team member, the AI person) has an avatar (photo or initials) beside the bubble with the
4
+ * name below it, when the speaker changes. My own messages: no avatar, ticks. Internal notes highlighted.
4
5
  */
5
6
  import React from 'react';
6
7
  import {Text, View} from 'react-native';
7
8
  import Attachment from './Attachment';
9
+ import PeopleAvatar from './PeopleAvatar';
10
+ import {fileIdOf} from './fileApi';
8
11
  import RichText from './RichText';
9
12
 
10
- const {initialsOf, timeLabel} = require('./formatText');
13
+ const {timeLabel} = require('./formatText');
11
14
 
12
15
  const TICKS = {pending: '🕓', processing: '🕓', done: '✓✓', error: '⚠'};
13
16
 
14
17
  export default function MessageBubble({item, side, kind, author, showAuthor, palette}) {
15
18
  const mine = side === 'right';
19
+ // "Você" (describe) or a message still being sent: my own, no avatar.
20
+ const self = author === 'Você' || Boolean(item?.localId);
16
21
  const note = kind === 'note';
17
22
  const bg = note ? palette.noteBubble : mine ? palette.mineBubble : palette.otherBubble;
18
23
  const fg = mine && !note ? palette.mineText : palette.otherText;
@@ -21,22 +26,8 @@ export default function MessageBubble({item, side, kind, author, showAuthor, pal
21
26
  const isFileLabel = item?.file && /^Anexo(:|$)/.test(body);
22
27
 
23
28
  return (
24
- <View style={{flexDirection: 'row', justifyContent: mine ? 'flex-end' : 'flex-start', marginVertical: 2, paddingHorizontal: 8}}>
25
- {!mine ? (
26
- <View
27
- style={{
28
- width: 32,
29
- height: 32,
30
- borderRadius: 16,
31
- marginRight: 6,
32
- marginTop: 2,
33
- alignItems: 'center',
34
- justifyContent: 'center',
35
- backgroundColor: showAuthor ? palette.chipActive : 'transparent',
36
- }}>
37
- {showAuthor ? <Text style={{color: palette.chipActiveText, fontWeight: '700', fontSize: 12}}>{initialsOf(author)}</Text> : null}
38
- </View>
39
- ) : null}
29
+ <View style={{flexDirection: mine ? 'row-reverse' : 'row', alignItems: 'flex-start', gap: 4, marginVertical: 2, paddingHorizontal: 8}}>
30
+ {!self ? (showAuthor ? <PeopleAvatar peopleId={fileIdOf(item?.registeredBy)} name={author} palette={palette} /> : <View style={{width: 56}} />) : null}
40
31
  <View
41
32
  style={{
42
33
  maxWidth: '78%',
@@ -51,10 +42,8 @@ export default function MessageBubble({item, side, kind, author, showAuthor, pal
51
42
  paddingTop: 6,
52
43
  paddingBottom: 4,
53
44
  }}>
54
- {showAuthor && (!mine || note) ? (
55
- <Text style={{color: note ? palette.noteBorder : palette.chipActive, fontWeight: '700', fontSize: 12, marginBottom: 2}}>
56
- {note ? `${author} · nota interna` : author}
57
- </Text>
45
+ {showAuthor && note ? (
46
+ <Text style={{color: palette.noteBorder, fontWeight: '700', fontSize: 12, marginBottom: 2}}>nota interna</Text>
58
47
  ) : null}
59
48
  {item?.file ? <Attachment file={item.file} color={fg} /> : null}
60
49
  {body && !isFileLabel ? <RichText value={body} style={{color: fg, fontSize: 15, lineHeight: 20}} linkColor={fg} /> : null}
@@ -0,0 +1,55 @@
1
+ /*
2
+ * @agents Avatar of a conversation participant (group chat look): the person's photo (people_media,
3
+ * cached per person for the whole app) or their initials; the name goes right below.
4
+ */
5
+ import React, {useEffect, useState} from 'react';
6
+ import {Image, Text, View} from 'react-native';
7
+ import {api} from '@controleonline/ui-common/src/api';
8
+ import {fileIdOf, fileSource} from './fileApi';
9
+ import {toItems} from './requestApi';
10
+
11
+ const {initialsOf} = require('./formatText');
12
+
13
+ const photoCache = new Map();
14
+
15
+ const photoOf = peopleId => {
16
+ if (!photoCache.has(peopleId)) {
17
+ photoCache.set(
18
+ peopleId,
19
+ api
20
+ .fetch('/people_media', {params: {people: peopleId, itemsPerPage: 1, 'order[id]': 'DESC'}})
21
+ .then(res => {
22
+ const fileId = fileIdOf(toItems(res)[0]?.file);
23
+ return fileId ? fileSource(fileId) : null;
24
+ })
25
+ .catch(() => null),
26
+ );
27
+ }
28
+ return photoCache.get(peopleId);
29
+ };
30
+
31
+ export default function PeopleAvatar({peopleId, name, palette, size = 34}) {
32
+ const [source, setSource] = useState(null);
33
+ useEffect(() => {
34
+ let alive = true;
35
+ if (peopleId) photoOf(peopleId).then(s => alive && setSource(s));
36
+ return () => {
37
+ alive = false;
38
+ };
39
+ }, [peopleId]);
40
+
41
+ return (
42
+ <View style={{width: 56, alignItems: 'center'}}>
43
+ {source ? (
44
+ <Image source={source} style={{width: size, height: size, borderRadius: size / 2}} />
45
+ ) : (
46
+ <View style={{width: size, height: size, borderRadius: size / 2, alignItems: 'center', justifyContent: 'center', backgroundColor: palette.chipActive}}>
47
+ <Text style={{color: palette.chipActiveText, fontWeight: '700', fontSize: 12}}>{initialsOf(name)}</Text>
48
+ </View>
49
+ )}
50
+ <Text numberOfLines={2} style={{color: palette.muted, fontSize: 10, textAlign: 'center', marginTop: 2}}>
51
+ {name}
52
+ </Text>
53
+ </View>
54
+ );
55
+ }
@@ -0,0 +1,85 @@
1
+ /*
2
+ * @agents Right-side marketing integration status (ga4/ads/adsense) for #100.
3
+ * Reads the same /integrations/google-marketing/status endpoint used by the
4
+ * settings cards; a non-connected scope links to Settings → Integrations.
5
+ */
6
+ import React, {useCallback, useEffect, useState} from 'react';
7
+ import {StyleSheet, Text, TouchableOpacity, View} from 'react-native';
8
+
9
+ import {api} from '@controleonline/ui-common/src/api';
10
+ import useChatPalette from '../../components/conversation/useChatPalette';
11
+
12
+ const SCOPES = [
13
+ {key: 'analytics', label: 'Google Analytics'},
14
+ {key: 'ads', label: 'Google Ads'},
15
+ {key: 'adsense', label: 'Google AdSense'},
16
+ ];
17
+
18
+ export default function IntegrationStatusPanel({companyId}) {
19
+ const palette = useChatPalette();
20
+ const styles = useLocalStyles(palette);
21
+ const [statuses, setStatuses] = useState({});
22
+
23
+ const load = useCallback(async () => {
24
+ if (!companyId) return;
25
+ const next = {};
26
+ await Promise.all(
27
+ SCOPES.map(async scope => {
28
+ try {
29
+ const status = await api.fetch('/integrations/google-marketing/status', {
30
+ params: {provider_id: companyId, scope_set: scope.key},
31
+ });
32
+ next[scope.key] = Boolean(status?.connected);
33
+ } catch {
34
+ next[scope.key] = false;
35
+ }
36
+ }),
37
+ );
38
+ setStatuses(next);
39
+ }, [companyId]);
40
+
41
+ useEffect(() => {
42
+ load();
43
+ }, [load]);
44
+
45
+ return (
46
+ <View>
47
+ <Text style={styles.title}>
48
+ {global.t?.t('marketing', 'ai', 'statusTitle', 'Conexões')}
49
+ </Text>
50
+ {SCOPES.map(scope => {
51
+ const connected = !!statuses[scope.key];
52
+ return (
53
+ <View key={scope.key} style={styles.row}>
54
+ <View style={[styles.dot, connected ? styles.dotOk : styles.dotOff]} />
55
+ <Text style={styles.label}>{scope.label}</Text>
56
+ </View>
57
+ );
58
+ })}
59
+ <TouchableOpacity style={styles.manageButton} onPress={() => load()}>
60
+ <Text style={styles.manageButtonText}>
61
+ {global.t?.t('marketing', 'ai', 'refresh', 'Atualizar')}
62
+ </Text>
63
+ </TouchableOpacity>
64
+ </View>
65
+ );
66
+ }
67
+
68
+ const useLocalStyles = palette =>
69
+ StyleSheet.create({
70
+ title: {color: palette.text, fontWeight: '700', fontSize: 14, marginBottom: 8},
71
+ row: {flexDirection: 'row', alignItems: 'center', marginBottom: 6},
72
+ dot: {width: 10, height: 10, borderRadius: 5, marginRight: 8},
73
+ dotOk: {backgroundColor: palette.success || palette.primary},
74
+ dotOff: {backgroundColor: palette.muted},
75
+ label: {color: palette.text, fontSize: 13},
76
+ manageButton: {
77
+ marginTop: 10,
78
+ paddingVertical: 8,
79
+ paddingHorizontal: 12,
80
+ backgroundColor: palette.chip,
81
+ borderRadius: 8,
82
+ alignSelf: 'flex-start',
83
+ },
84
+ manageButtonText: {color: palette.text, fontSize: 12, fontWeight: '600'},
85
+ });
@@ -0,0 +1,190 @@
1
+ /*
2
+ * @agents Marketing AI chat for APP_TYPE=MKT (#100). Reuses /mcp/chat
3
+ * (McpChatController) and the McpMarketingTools of #105. The LLM reads
4
+ * ga4/ads/adsense via tool-calls and the UI confirms mutations (pause/
5
+ * resume/update_budget) before letting force=true be sent.
6
+ */
7
+ import React, {useCallback, useEffect, useState} from 'react';
8
+ import {ActivityIndicator, ScrollView, Text, TextInput, TouchableOpacity, View, StyleSheet} from 'react-native';
9
+
10
+ import useToastMessage from '../../hooks/useToastMessage';
11
+ import useChatPalette from '../../components/conversation/useChatPalette';
12
+ import {sendRequestMessage, fetchMessages} from '../../components/conversation/requestApi';
13
+
14
+ import IntegrationStatusPanel from './IntegrationStatusPanel';
15
+
16
+ export default function MarketingAiPage({companyId}) {
17
+ const palette = useChatPalette();
18
+ const {showError} = useToastMessage();
19
+ const localStyles = useLocalStyles(palette);
20
+
21
+ const [taskId, setTaskId] = useState(null);
22
+ const [messages, setMessages] = useState([]);
23
+ const [input, setInput] = useState('');
24
+ const [sending, setSending] = useState(false);
25
+ const [loading, setLoading] = useState(false);
26
+
27
+ const loadHistory = useCallback(
28
+ async id => {
29
+ if (!id) return;
30
+ setLoading(true);
31
+ try {
32
+ const items = await fetchMessages(id);
33
+ setMessages(Array.isArray(items) ? items : []);
34
+ } catch (err) {
35
+ showError(err?.message || String(err));
36
+ } finally {
37
+ setLoading(false);
38
+ }
39
+ },
40
+ [showError],
41
+ );
42
+
43
+ useEffect(() => {
44
+ loadHistory(taskId);
45
+ }, [taskId, loadHistory]);
46
+
47
+ const send = useCallback(async () => {
48
+ const text = input.trim();
49
+ if (!text || sending) return;
50
+ setSending(true);
51
+ try {
52
+ const response = await sendRequestMessage({
53
+ taskId,
54
+ type: taskId ? undefined : 'ia',
55
+ text,
56
+ companyId,
57
+ });
58
+ const nextTaskId = response?.task_id || response?.taskId || taskId;
59
+ if (nextTaskId && nextTaskId !== taskId) {
60
+ setTaskId(nextTaskId);
61
+ } else if (nextTaskId) {
62
+ loadHistory(nextTaskId);
63
+ }
64
+ setInput('');
65
+ } catch (err) {
66
+ showError(err?.message || String(err));
67
+ } finally {
68
+ setSending(false);
69
+ }
70
+ }, [companyId, input, loadHistory, sending, showError, taskId]);
71
+
72
+ return (
73
+ <View style={localStyles.container}>
74
+ <View style={localStyles.sidebar}>
75
+ <Text style={localStyles.sidebarTitle}>
76
+ {global.t?.t('marketing', 'ai', 'title', 'Marketing · IA')}
77
+ </Text>
78
+ <IntegrationStatusPanel companyId={companyId} />
79
+ </View>
80
+
81
+ <View style={localStyles.chatArea}>
82
+ <ScrollView contentContainerStyle={localStyles.messagesContainer}>
83
+ {loading ? <ActivityIndicator color={palette.primary} /> : null}
84
+ {!loading && messages.length === 0 ? (
85
+ <Text style={localStyles.emptyText}>
86
+ {global.t?.t(
87
+ 'marketing',
88
+ 'ai',
89
+ 'empty',
90
+ 'Pergunte sobre desempenho ou peça para a IA agir (pausar campanha, ajustar orçamento). Mudanças sensíveis pedem sua confirmação.',
91
+ )}
92
+ </Text>
93
+ ) : null}
94
+ {messages.map(message => (
95
+ <View
96
+ key={String(message.id || message['@id'])}
97
+ style={[
98
+ localStyles.messageBubble,
99
+ message.registeredBy?.type === 'ia' || message.author === 'ia'
100
+ ? localStyles.messageAi
101
+ : localStyles.messageUser,
102
+ ]}>
103
+ <Text style={localStyles.messageText}>{message.body || ''}</Text>
104
+ </View>
105
+ ))}
106
+ </ScrollView>
107
+
108
+ <View style={localStyles.composer}>
109
+ <TextInput
110
+ style={localStyles.composerInput}
111
+ value={input}
112
+ onChangeText={setInput}
113
+ placeholder={global.t?.t(
114
+ 'marketing',
115
+ 'ai',
116
+ 'inputPlaceholder',
117
+ 'Como está o Google Ads esta semana?',
118
+ )}
119
+ placeholderTextColor={palette.muted}
120
+ multiline
121
+ />
122
+ <TouchableOpacity
123
+ onPress={send}
124
+ disabled={sending || !input.trim()}
125
+ style={[
126
+ localStyles.composerButton,
127
+ (sending || !input.trim()) && localStyles.composerButtonDisabled,
128
+ ]}>
129
+ <Text style={localStyles.composerButtonText}>
130
+ {sending
131
+ ? global.t?.t('marketing', 'ai', 'sending', 'Enviando…')
132
+ : global.t?.t('marketing', 'ai', 'send', 'Enviar')}
133
+ </Text>
134
+ </TouchableOpacity>
135
+ </View>
136
+ </View>
137
+ </View>
138
+ );
139
+ }
140
+
141
+ const useLocalStyles = palette =>
142
+ StyleSheet.create({
143
+ container: {flex: 1, flexDirection: 'row', backgroundColor: palette.background},
144
+ sidebar: {
145
+ width: 300,
146
+ borderRightWidth: 1,
147
+ borderRightColor: palette.border,
148
+ backgroundColor: palette.panel,
149
+ padding: 16,
150
+ },
151
+ sidebarTitle: {color: palette.text, fontWeight: '700', fontSize: 17, marginBottom: 16},
152
+ chatArea: {flex: 1, flexDirection: 'column'},
153
+ messagesContainer: {padding: 20, flexGrow: 1},
154
+ emptyText: {color: palette.muted, fontSize: 14},
155
+ messageBubble: {
156
+ padding: 12,
157
+ borderRadius: 10,
158
+ marginBottom: 10,
159
+ maxWidth: '80%',
160
+ },
161
+ messageUser: {alignSelf: 'flex-end', backgroundColor: palette.chipActive},
162
+ messageAi: {alignSelf: 'flex-start', backgroundColor: palette.chip},
163
+ messageText: {color: palette.text},
164
+ composer: {
165
+ flexDirection: 'row',
166
+ padding: 12,
167
+ borderTopWidth: 1,
168
+ borderTopColor: palette.border,
169
+ backgroundColor: palette.panel,
170
+ columnGap: 10,
171
+ },
172
+ composerInput: {
173
+ flex: 1,
174
+ minHeight: 44,
175
+ borderRadius: 10,
176
+ borderWidth: 1,
177
+ borderColor: palette.border,
178
+ paddingHorizontal: 12,
179
+ color: palette.text,
180
+ },
181
+ composerButton: {
182
+ backgroundColor: palette.chipActive,
183
+ borderRadius: 10,
184
+ paddingHorizontal: 18,
185
+ alignItems: 'center',
186
+ justifyContent: 'center',
187
+ },
188
+ composerButtonDisabled: {opacity: 0.6},
189
+ composerButtonText: {color: palette.chipActiveText, fontWeight: '700'},
190
+ });
@@ -0,0 +1,108 @@
1
+ /*
2
+ * @agents Home for APP_TYPE=MKT (#105). Tiles navegáveis para as telas
3
+ * da epic de marketing. Quando o admin configurar menus runtime do tipo
4
+ * 'home' para MKT, AppMenuGrid toma o lugar do fallback.
5
+ */
6
+ import React, {useMemo} from 'react';
7
+ import {ScrollView, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
8
+
9
+ import {useStore} from '@store';
10
+ import AppMenuGrid from '@controleonline/ui-layout/src/react/components/AppMenuGrid';
11
+
12
+ import useChatPalette from '../../components/conversation/useChatPalette';
13
+
14
+ const FALLBACK_TILES = [
15
+ {
16
+ key: 'marketing-ai',
17
+ labelFallback: 'Chat com IA',
18
+ icon: 'message-circle',
19
+ route: 'MarketingAiPage',
20
+ },
21
+ {
22
+ key: 'marketing-dashboard',
23
+ labelFallback: 'Dashboard',
24
+ icon: 'bar-chart-2',
25
+ route: 'MarketingDashboardPage',
26
+ },
27
+ {
28
+ key: 'marketing-integrations',
29
+ labelFallback: 'Conectar Google',
30
+ icon: 'link',
31
+ route: 'IntegrationsPage',
32
+ },
33
+ {
34
+ key: 'marketing-events',
35
+ labelFallback: 'Eventos de marketing',
36
+ icon: 'activity',
37
+ route: 'MarketingEventsPage',
38
+ },
39
+ ];
40
+
41
+ export default function MarketingHomePage({navigation}) {
42
+ const palette = useChatPalette();
43
+ const themeStore = useStore('theme');
44
+ const menus = themeStore?.getters?.menus || [];
45
+ const styles = useLocalStyles(palette);
46
+
47
+ const hasRuntimeMenus = useMemo(
48
+ () => Array.isArray(menus) && menus.some(m => (m?.menu_type || m?.menuType) === 'home'),
49
+ [menus],
50
+ );
51
+
52
+ if (hasRuntimeMenus) {
53
+ return (
54
+ <ScrollView style={styles.container}>
55
+ <AppMenuGrid menus={menus} navigation={navigation} menuType="home" />
56
+ </ScrollView>
57
+ );
58
+ }
59
+
60
+ return (
61
+ <ScrollView contentContainerStyle={styles.fallback}>
62
+ <Text style={styles.title}>
63
+ {global.t?.t('marketing', 'home', 'title', 'Marketing')}
64
+ </Text>
65
+ <Text style={styles.subtitle}>
66
+ {global.t?.t(
67
+ 'marketing',
68
+ 'home',
69
+ 'subtitle',
70
+ 'Escolha onde começar. Nenhum menu foi configurado pelo administrador ainda.',
71
+ )}
72
+ </Text>
73
+ <View style={styles.grid}>
74
+ {FALLBACK_TILES.map(tile => (
75
+ <TouchableOpacity
76
+ key={tile.key}
77
+ style={styles.tile}
78
+ onPress={() => navigation?.navigate?.(tile.route)}
79
+ accessibilityRole="button">
80
+ <Text style={styles.tileLabel}>
81
+ {global.t?.t('marketing', 'home', tile.key, tile.labelFallback)}
82
+ </Text>
83
+ </TouchableOpacity>
84
+ ))}
85
+ </View>
86
+ </ScrollView>
87
+ );
88
+ }
89
+
90
+ const useLocalStyles = palette =>
91
+ StyleSheet.create({
92
+ container: {flex: 1, backgroundColor: palette.background},
93
+ fallback: {padding: 24, backgroundColor: palette.background, flexGrow: 1},
94
+ title: {color: palette.text, fontSize: 22, fontWeight: '700'},
95
+ subtitle: {color: palette.muted, fontSize: 13, marginTop: 8, marginBottom: 20},
96
+ grid: {flexDirection: 'row', flexWrap: 'wrap', columnGap: 12, rowGap: 12},
97
+ tile: {
98
+ minWidth: 160,
99
+ flexGrow: 1,
100
+ maxWidth: 220,
101
+ backgroundColor: palette.panel,
102
+ borderWidth: 1,
103
+ borderColor: palette.border,
104
+ borderRadius: 12,
105
+ padding: 20,
106
+ },
107
+ tileLabel: {color: palette.text, fontWeight: '700', fontSize: 15},
108
+ });
@@ -0,0 +1,57 @@
1
+ /*
2
+ * @agents One kind of request (support / relationship): who attends first (AI by default, or a person),
3
+ * the AI's name (the AI is a person of the company, e.g. "Tião IA") and the welcome message sent in
4
+ * its name. Saved with PUT /tickets/settings {attendance: {[type]: {first, ai_name, welcome}}}.
5
+ */
6
+ import React, {useEffect, useState} from 'react';
7
+ import {Text, TextInput, TouchableOpacity, View} from 'react-native';
8
+
9
+ const FIRST = [
10
+ {value: 'ai', label: 'IA primeiro (encaminha para uma pessoa quando precisar)'},
11
+ {value: 'human', label: 'Pessoa primeiro'},
12
+ ];
13
+
14
+ export default function AttendanceSettings({type, value, onSave, palette, styles, Choice}) {
15
+ const [name, setName] = useState(value?.ai_name || '');
16
+ const [welcome, setWelcome] = useState(value?.welcome || '');
17
+ useEffect(() => {
18
+ setName(value?.ai_name || '');
19
+ setWelcome(value?.welcome || '');
20
+ }, [value?.ai_name, value?.welcome]);
21
+
22
+ const input = {
23
+ borderWidth: 1,
24
+ borderColor: palette.inputBorder || palette.cardBorder,
25
+ backgroundColor: palette.inputBackground || palette.cardBackground,
26
+ color: palette.inputText || palette.textPrimary,
27
+ borderRadius: 10,
28
+ paddingHorizontal: 12,
29
+ paddingVertical: 8,
30
+ marginBottom: 8,
31
+ };
32
+
33
+ return (
34
+ <View style={{marginBottom: 12}}>
35
+ <Text style={styles.sectionTitle}>Primeiro atendimento</Text>
36
+ {FIRST.map(o => (
37
+ <Choice key={o.value} palette={palette} active={(value?.first || 'ai') === o.value} label={o.label} onPress={() => onSave({[type]: {first: o.value}})} />
38
+ ))}
39
+ <Text style={[styles.sectionTitle, {marginTop: 8}]}>Nome da IA</Text>
40
+ <TextInput style={input} value={name} onChangeText={setName} maxLength={60} placeholder="Ex.: Tião IA" placeholderTextColor={palette.inputPlaceholderText || palette.textMuted} />
41
+ <Text style={styles.sectionTitle}>Mensagem de boas-vindas</Text>
42
+ <TextInput
43
+ style={[input, {minHeight: 70, textAlignVertical: 'top'}]}
44
+ value={welcome}
45
+ onChangeText={setWelcome}
46
+ multiline
47
+ placeholder="Enviada em nome da IA quando a solicitação começa (vazio = sem mensagem)"
48
+ placeholderTextColor={palette.inputPlaceholderText || palette.textMuted}
49
+ />
50
+ <TouchableOpacity
51
+ onPress={() => onSave({[type]: {ai_name: name, welcome}})}
52
+ style={{alignSelf: 'flex-start', paddingVertical: 8, paddingHorizontal: 14, borderRadius: 10, backgroundColor: palette.primary}}>
53
+ <Text style={{color: palette.buttonText || palette.cardBackground, fontWeight: '700'}}>Salvar nome e boas-vindas</Text>
54
+ </TouchableOpacity>
55
+ </View>
56
+ );
57
+ }
@@ -0,0 +1,287 @@
1
+ /*
2
+ * @agents Google Marketing integration cards (GA4 / Google Ads / AdSense).
3
+ * Backed by #84 (api-platform-integration). OAuth per scope set stays in
4
+ * /configs private (GOOGLE_SERVICE_<SET>), while the identifiers below live
5
+ * in GA4_PROPERTY_ID / GOOGLE_ADS_CUSTOMER / ADSENSE_ACCOUNT.
6
+ */
7
+ import React, {useCallback, useEffect, useState} from 'react';
8
+ import {Linking, StyleSheet, Text, TextInput, TouchableOpacity, View} from 'react-native';
9
+
10
+ import useToastMessage from '@controleonline/ui-crm/src/react/hooks/useToastMessage';
11
+ import {api} from '@controleonline/ui-common/src/api';
12
+
13
+ import {
14
+ useGeneralSettingsPalette,
15
+ useGeneralSettingsStyles,
16
+ } from '../GeneralSettings.styles';
17
+ import GeneralSettingsSection from '../GeneralSettingsSection';
18
+ import {
19
+ toConfigRequestValue,
20
+ useGeneralSettingsConfig,
21
+ } from '../GeneralSettings.shared';
22
+
23
+ const styles = StyleSheet.create({
24
+ buttonRow: {flexDirection: 'row', marginTop: 12, columnGap: 8},
25
+ });
26
+
27
+ const SCOPE_SETS = [
28
+ {
29
+ key: 'analytics',
30
+ title: global.t?.t('settings', 'googleMarketing', 'ga4.title', 'Google Analytics 4'),
31
+ description: global.t?.t('settings', 'googleMarketing', 'ga4.desc', 'Sessões, usuários, conversões e páginas vistas por campanha.'),
32
+ icon: 'bar-chart',
33
+ configKey: 'GA4_PROPERTY_ID',
34
+ fieldKey: 'PROPERTY_ID',
35
+ fieldPlaceholder: 'properties/123456789 ou 123456789',
36
+ },
37
+ {
38
+ key: 'ads',
39
+ title: global.t?.t('settings', 'googleMarketing', 'ads.title', 'Google Ads'),
40
+ description: global.t?.t('settings', 'googleMarketing', 'ads.desc', 'Campanhas, custo, cliques e conversões; permite pausar/retomar via chat IA.'),
41
+ icon: 'ads-click',
42
+ configKey: 'GOOGLE_ADS_CUSTOMER',
43
+ fieldKey: 'customer_id',
44
+ fieldPlaceholder: '1234567890',
45
+ },
46
+ {
47
+ key: 'adsense',
48
+ title: global.t?.t('settings', 'googleMarketing', 'adsense.title', 'Google AdSense'),
49
+ description: global.t?.t('settings', 'googleMarketing', 'adsense.desc', 'Receita, RPM e impressões por site e unidade.'),
50
+ icon: 'monetization-on',
51
+ configKey: 'ADSENSE_ACCOUNT',
52
+ fieldKey: 'ACCOUNT_NAME',
53
+ fieldPlaceholder: 'accounts/pub-0000000000000000',
54
+ },
55
+ {
56
+ key: 'webmasters',
57
+ title: global.t?.t('settings', 'googleMarketing', 'gsc.title', 'Google Search Console'),
58
+ description: global.t?.t('settings', 'googleMarketing', 'gsc.desc', 'Cliques, impressões, CTR e posição média orgânica.'),
59
+ icon: 'search',
60
+ configKey: 'SEARCH_CONSOLE_SITE',
61
+ fieldKey: 'SITE_URL',
62
+ fieldPlaceholder: 'sc-domain:exemplo.com ou https://exemplo.com/',
63
+ },
64
+ ];
65
+
66
+ const resolveTextConfig = (configs, key) => {
67
+ const raw = configs?.[key];
68
+ if (typeof raw === 'string') {
69
+ return raw.trim();
70
+ }
71
+ return '';
72
+ };
73
+
74
+ const resolveJsonConfig = (configs, key, field) => {
75
+ const raw = configs?.[key];
76
+ if (typeof raw !== 'string' || raw === '') {
77
+ return '';
78
+ }
79
+ try {
80
+ const parsed = JSON.parse(raw);
81
+ return String(parsed?.[field] || '').trim();
82
+ } catch {
83
+ return '';
84
+ }
85
+ };
86
+
87
+ const GoogleMarketingSection = () => {
88
+ const localStyles = useGeneralSettingsStyles();
89
+ const themePalette = useGeneralSettingsPalette();
90
+ const {showError, showSuccess} = useToastMessage();
91
+ const {
92
+ configActions,
93
+ mainCompany,
94
+ hasDefaultCompanyAccess,
95
+ isMainCompanySelected,
96
+ isSaving,
97
+ } = useGeneralSettingsConfig();
98
+
99
+ const [configs, setConfigs] = useState({});
100
+ const [statuses, setStatuses] = useState({});
101
+ const [fieldValues, setFieldValues] = useState({});
102
+ const [loading, setLoading] = useState(false);
103
+
104
+ const companyId = mainCompany?.id;
105
+ const editable = hasDefaultCompanyAccess && isMainCompanySelected && !isSaving && !loading;
106
+
107
+ const loadConfigs = useCallback(async () => {
108
+ if (!companyId) {
109
+ setConfigs({});
110
+ setStatuses({});
111
+ return;
112
+ }
113
+ setLoading(true);
114
+ try {
115
+ const response = await api.fetch('/configs', {
116
+ params: {people: '/people/' + companyId, visibility: 'private'},
117
+ });
118
+ const items = Array.isArray(response?.member)
119
+ ? response.member
120
+ : Array.isArray(response?.['hydra:member'])
121
+ ? response['hydra:member']
122
+ : [];
123
+ const mapped = items.reduce((acc, item) => {
124
+ const k = String(item?.configKey || '').trim();
125
+ if (k) acc[k] = item?.configValue;
126
+ return acc;
127
+ }, {});
128
+ setConfigs(mapped);
129
+
130
+ const nextStatuses = {};
131
+ await Promise.all(
132
+ SCOPE_SETS.map(async scope => {
133
+ try {
134
+ const status = await api.fetch('/integrations/google-marketing/status', {
135
+ params: {provider_id: companyId, scope_set: scope.key},
136
+ });
137
+ nextStatuses[scope.key] = status;
138
+ } catch {
139
+ nextStatuses[scope.key] = {connected: false};
140
+ }
141
+ }),
142
+ );
143
+ setStatuses(nextStatuses);
144
+ } catch (err) {
145
+ showError(err?.message || global.t?.t('settings', 'googleMarketing', 'loadFailed', 'Não foi possível carregar o status das integrações Google.'));
146
+ } finally {
147
+ setLoading(false);
148
+ }
149
+ }, [companyId, showError]);
150
+
151
+ useEffect(() => {
152
+ loadConfigs();
153
+ }, [loadConfigs]);
154
+
155
+ useEffect(() => {
156
+ const next = {};
157
+ SCOPE_SETS.forEach(scope => {
158
+ if (scope.key === 'ads') {
159
+ next[scope.key] = resolveJsonConfig(configs, scope.configKey, 'customer_id');
160
+ } else {
161
+ next[scope.key] = resolveTextConfig(configs, scope.configKey);
162
+ }
163
+ });
164
+ setFieldValues(next);
165
+ }, [configs]);
166
+
167
+ const connect = useCallback(
168
+ async scope => {
169
+ if (!editable) return;
170
+ try {
171
+ const result = await api.fetch('/integrations/google-marketing/authorization-page', {
172
+ method: 'POST',
173
+ body: {
174
+ provider_id: companyId,
175
+ scope_set: scope.key,
176
+ return_url: '/settings/integrations',
177
+ },
178
+ });
179
+ if (result?.authorization_url) {
180
+ Linking.openURL(result.authorization_url);
181
+ } else {
182
+ showError(String(result?.message || result?.error || 'authorization_failed'));
183
+ }
184
+ } catch (err) {
185
+ showError(err?.message || String(err));
186
+ }
187
+ },
188
+ [companyId, editable, showError],
189
+ );
190
+
191
+ const disconnect = useCallback(
192
+ async scope => {
193
+ if (!editable) return;
194
+ try {
195
+ await api.fetch('/integrations/google-marketing/disconnect', {
196
+ method: 'POST',
197
+ body: {provider_id: companyId, scope_set: scope.key},
198
+ });
199
+ showSuccess(global.t?.t('settings', 'googleMarketing', 'disconnected', 'Integração desconectada.'));
200
+ loadConfigs();
201
+ } catch (err) {
202
+ showError(err?.message || String(err));
203
+ }
204
+ },
205
+ [companyId, editable, loadConfigs, showError, showSuccess],
206
+ );
207
+
208
+ const saveField = useCallback(
209
+ async scope => {
210
+ if (!editable) return;
211
+ const value = fieldValues[scope.key] || '';
212
+ const configValue = scope.key === 'ads' ? {customer_id: value} : value;
213
+ configActions.addToQueue(() =>
214
+ configActions
215
+ .addConfigs({
216
+ configKey: scope.configKey,
217
+ configValue: toConfigRequestValue(configValue),
218
+ people: '/people/' + companyId,
219
+ module: 4,
220
+ visibility: 'private',
221
+ })
222
+ .then(() => {
223
+ showSuccess(global.t?.t('settings', 'googleMarketing', 'saved', 'Identificador salvo.'));
224
+ loadConfigs();
225
+ })
226
+ .catch(err => showError(err?.message || JSON.stringify(err))),
227
+ );
228
+ configActions.initQueue();
229
+ },
230
+ [configActions, companyId, editable, fieldValues, loadConfigs, showError, showSuccess],
231
+ );
232
+
233
+ return SCOPE_SETS.map(scope => {
234
+ const status = statuses[scope.key];
235
+ const connected = Boolean(status?.connected);
236
+ return (
237
+ <GeneralSettingsSection
238
+ key={scope.key}
239
+ description={scope.description}
240
+ icon={scope.icon}
241
+ iconBackgroundColor={themePalette.cardIconBackground}
242
+ iconColor={themePalette.cardIconColor}
243
+ title={scope.title}>
244
+ <Text style={localStyles.helperText}>
245
+ {connected
246
+ ? global.t?.t('settings', 'googleMarketing', 'connected', 'Conectado como ') + (status?.scopes?.join(' ') || '')
247
+ : global.t?.t('settings', 'googleMarketing', 'notConnected', 'Não conectado. Autorize a conta Google que administra esses dados.')}
248
+ </Text>
249
+ <Text style={localStyles.fieldLabel}>{scope.fieldKey}</Text>
250
+ <TextInput
251
+ style={[localStyles.input, !editable && localStyles.inputDisabled]}
252
+ value={fieldValues[scope.key] || ''}
253
+ onChangeText={next =>
254
+ setFieldValues(prev => ({...prev, [scope.key]: next}))
255
+ }
256
+ onBlur={() => saveField(scope)}
257
+ editable={editable}
258
+ autoCapitalize="none"
259
+ autoCorrect={false}
260
+ placeholder={scope.fieldPlaceholder}
261
+ />
262
+ <View style={styles.buttonRow}>
263
+ <TouchableOpacity
264
+ onPress={() => connect(scope)}
265
+ style={[localStyles.selectorListButton, !editable && localStyles.inputDisabled]}
266
+ disabled={!editable}>
267
+ <Text style={localStyles.selectorListButtonText}>
268
+ {global.t?.t('settings', 'googleMarketing', 'connect', 'Conectar com Google')}
269
+ </Text>
270
+ </TouchableOpacity>
271
+ {connected ? (
272
+ <TouchableOpacity
273
+ onPress={() => disconnect(scope)}
274
+ style={[localStyles.selectorListButton, !editable && localStyles.inputDisabled]}
275
+ disabled={!editable}>
276
+ <Text style={localStyles.selectorListButtonText}>
277
+ {global.t?.t('settings', 'googleMarketing', 'disconnect', 'Desconectar')}
278
+ </Text>
279
+ </TouchableOpacity>
280
+ ) : null}
281
+ </View>
282
+ </GeneralSettingsSection>
283
+ );
284
+ });
285
+ };
286
+
287
+ export default GoogleMarketingSection;
@@ -24,6 +24,7 @@ import {
24
24
  useGeneralSettingsStyles,
25
25
  } from '../GeneralSettings.styles';
26
26
  import GeneralSettingsSection from '../GeneralSettingsSection';
27
+ import GoogleMarketingSection from './GoogleMarketingSection';
27
28
  import LoginSection from './LoginSection';
28
29
  import {
29
30
  toConfigCacheValue,
@@ -385,6 +386,8 @@ const IntegrationsSection = () => {
385
386
  styles={localStyles}
386
387
  />
387
388
  </GeneralSettingsSection>
389
+
390
+ <GoogleMarketingSection />
388
391
  </>
389
392
  );
390
393
  };
@@ -12,6 +12,7 @@ import useToastMessage from '@controleonline/ui-crm/src/react/hooks/useToastMess
12
12
  import {fetchTicketSettings, saveTicketSettings} from '../../../components/conversation/requestApi';
13
13
  import {useGeneralSettingsPalette, useGeneralSettingsStyles} from '../GeneralSettings.styles';
14
14
  import GeneralSettingsSection from '../GeneralSettingsSection';
15
+ import AttendanceSettings from './AttendanceSettings';
15
16
  import {useGeneralSettingsConfig} from '../GeneralSettings.shared';
16
17
 
17
18
  const STRATEGIES = [
@@ -41,7 +42,7 @@ const Choice = ({active, label, onPress, palette, multi}) => (
41
42
  borderWidth: 2,
42
43
  marginRight: 10,
43
44
  borderColor: palette.primary,
44
- backgroundColor: active ? palette.primary : 'transparent',
45
+ backgroundColor: active ? palette.primary : palette.cardBackground,
45
46
  }}
46
47
  />
47
48
  <Text style={{color: palette.textPrimary, flex: 1}}>{label}</Text>
@@ -90,12 +91,16 @@ export default function TicketSettingsSection() {
90
91
 
91
92
  if (!settings) return <ActivityIndicator style={{marginTop: 16}} />;
92
93
  const employees = settings.employees || [];
94
+ const attendance = type => (
95
+ <AttendanceSettings type={type} value={settings.attendance?.[type]} onSave={patch => save({attendance: patch})} palette={palette} styles={styles} Choice={Choice} />
96
+ );
93
97
 
94
98
  return (
95
99
  <View>
96
100
  <GeneralSettingsSection
97
101
  title="Suporte"
98
- description="Chamados de suporte nascem sem responsável e são distribuídos entre as pessoas marcadas abaixo. Só elas respondem e aparecem como responsáveis em Atendimento de suporte.">
102
+ description="Com IA primeiro, o chamado fica com a IA (sem responsável) até ela resolver ou encaminhar. Pessoas: distribuição entre as marcadas abaixo, que respondem e aparecem como responsáveis em Atendimento de suporte.">
103
+ {attendance('support')}
99
104
  <Text style={styles.sectionTitle}>Regra de distribuição</Text>
100
105
  {STRATEGIES.map(s => (
101
106
  <Choice key={s.value} palette={palette} active={settings.support_strategy === s.value} label={s.label} onPress={() => save({support_strategy: s.value})} />
@@ -109,8 +114,8 @@ export default function TicketSettingsSection() {
109
114
 
110
115
  <GeneralSettingsSection
111
116
  title="Comercial (CRM)"
112
- description="Solicitações comerciais seguem a distribuição de clientes do CRM: cada cliente é atendido pelo seu vendedor; clientes sem vendedor recebem um pela estratégia configurada na aba CRM.">
113
- <Text style={styles.helperText}>Nada a configurar aqui.</Text>
117
+ description="Quando vai para uma pessoa, segue a distribuição de clientes do CRM: cada cliente é atendido pelo seu vendedor; clientes sem vendedor recebem um pela estratégia da aba CRM.">
118
+ {attendance('relationship')}
114
119
  </GeneralSettingsSection>
115
120
  {saving ? <ActivityIndicator style={{marginTop: 8}} /> : null}
116
121
  </View>