@controleonline/ui-common 1.2.132 → 1.2.133

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,14 +1,14 @@
1
1
  {
2
- "version": "1.2.132",
2
+ "version": "1.2.133",
3
3
  "rc": 1,
4
- "branch": "rc/1.2.132-rc.1",
5
- "baseMaster": "6ca50f9716ba2ff370dce15669b68777271b7e99",
6
- "baseTag": "v1.2.131",
4
+ "branch": "rc/1.2.133-rc.1",
5
+ "baseMaster": "9578ce116c022a5329dd30d4572f169fe3a67cc5",
6
+ "baseTag": "v1.2.132",
7
7
  "tasks": [
8
8
  98
9
9
  ],
10
10
  "frozen": true,
11
11
  "repositories": {
12
- "ControleOnline/ui-common": "07ca4291f5553015f8cc898f015b4f3df68057cc"
12
+ "ControleOnline/ui-common": "ebbce08b5fa24c9026e9e5aa387cd6b0a7d89240"
13
13
  }
14
14
  }
package/package.json CHANGED
@@ -1,16 +1,18 @@
1
1
  {
2
2
  "name": "@controleonline/ui-common",
3
- "version": "1.2.132",
3
+ "version": "1.2.133",
4
4
  "author": "ControleOnline",
5
5
  "description": "ControleOnline Common Quasar UI Component",
6
6
  "license": "MIT",
7
7
  "main": "src/react/index.js",
8
8
  "scripts": {
9
- "test": "npm run test:receita-federal && npm run test:imports-status && npm run test:runtime-language && npm run test:runtime-footer && npm run test:runtime-footer-marquee && npm run test:invoice-presentation && npm run test:system-error-message && npm run test:bottom-navigation-toolbar && npm run test:copy-device-configs && npm run test:print-routing && npm run test:device-detail-dependencies && npm run test:runtime-zoom && npm run test:cash-register-summary && npm run test:linked-order-payload && npm run test:document-file-content",
9
+ "test": "npm run test:receita-federal && npm run test:imports-status && npm run test:runtime-language && npm run test:runtime-footer && npm run test:runtime-footer-marquee && npm run test:invoice-presentation && npm run test:system-error-message && npm run test:bottom-navigation-toolbar && npm run test:copy-device-configs && npm run test:print-routing && npm run test:device-detail-dependencies && npm run test:runtime-zoom && npm run test:cash-register-summary && npm run test:linked-order-payload && npm run test:document-file-content && npm run test:order-products-summary && npm run test:client-portfolio",
10
10
  "test:receita-federal": "node --test src/tests/react/pages/receitaFederalIntegrationContract.test.mjs",
11
11
  "test:imports-status": "mkdir -p node_modules/@controleonline && rm -rf node_modules/@controleonline/ui-common && ln -s ../.. node_modules/@controleonline/ui-common && node --test src/tests/react/utils/importStatus.test.js",
12
12
  "test:cash-register-summary": "node --test src/tests/react/utils/cashRegisterSummary.test.js",
13
13
  "test:linked-order-payload": "node --test src/tests/react/utils/linkedOrderPayload.test.js",
14
+ "test:order-products-summary": "node --test src/tests/react/utils/orderProductsSummary.test.js",
15
+ "test:client-portfolio": "node --test src/tests/react/utils/clientPortfolioParams.test.js",
14
16
  "test:document-file-content": "node --test src/tests/react/utils/documentFileContent.test.js",
15
17
  "test:runtime-language": "node --test src/tests/react/utils/runtimeLanguage.test.js",
16
18
  "test:runtime-footer": "node --test src/tests/react/utils/runtimeFooter.test.js src/tests/react/utils/runtimeFooterText.test.js",
@@ -64,6 +64,8 @@ const LinkedOrderProductsTab = ({
64
64
  searchPlaceholder = 'Buscar produto para adicionar...',
65
65
  // Called after products change so the parent can regenerate/reload the document.
66
66
  onProductsChanged,
67
+ // Rendered inside a sheet that already has its own title.
68
+ embedded = false,
67
69
  }) => {
68
70
  const peopleStore = useStore('people');
69
71
  const { currentCompany } = peopleStore.getters;
@@ -246,11 +248,11 @@ const LinkedOrderProductsTab = ({
246
248
  return (
247
249
  <ScrollView
248
250
  style={styles.container}
249
- contentContainerStyle={styles.content}
251
+ contentContainerStyle={embedded ? styles.contentEmbedded : styles.content}
250
252
  keyboardShouldPersistTaps="handled">
251
- <View style={styles.section}>
252
- <View style={styles.headerRow}>
253
- <View>
253
+ <View style={embedded ? styles.sectionEmbedded : styles.section}>
254
+ <View style={[styles.headerRow, embedded && styles.headerRowEmbedded]}>
255
+ <View style={embedded ? styles.hidden : null}>
254
256
  <Text style={styles.title}>Produtos</Text>
255
257
  <Text style={styles.subtitle}>
256
258
  {orderId
@@ -8,6 +8,21 @@ const styles = StyleSheet.create({
8
8
  padding: 16,
9
9
  paddingBottom: 36,
10
10
  },
11
+ contentEmbedded: {
12
+ paddingHorizontal: 20,
13
+ paddingTop: 12,
14
+ paddingBottom: 24,
15
+ },
16
+ sectionEmbedded: {
17
+ backgroundColor: 'transparent',
18
+ },
19
+ headerRowEmbedded: {
20
+ marginBottom: 0,
21
+ minHeight: 0,
22
+ },
23
+ hidden: {
24
+ display: 'none',
25
+ },
11
26
  section: {
12
27
  backgroundColor: '#FFFFFF',
13
28
  borderRadius: 14,
@@ -0,0 +1,147 @@
1
+ import React from 'react';
2
+ import {
3
+ ActivityIndicator,
4
+ ScrollView,
5
+ Text,
6
+ TouchableOpacity,
7
+ useWindowDimensions,
8
+ View,
9
+ } from 'react-native';
10
+ import { SafeAreaView } from 'react-native-safe-area-context';
11
+ import Icon from 'react-native-vector-icons/MaterialIcons';
12
+ import { createDocumentDetailsStyles, resolveDocumentDetailsTheme } from './DocumentDetailsShell.styles';
13
+
14
+ const WIDE_BREAKPOINT = 768;
15
+
16
+ /**
17
+ * Shared layout for proposal/contract details.
18
+ * The header and the action bar stay fixed so the seller always sees who the
19
+ * document is for, its value and the main action, while the document itself
20
+ * gets the rest of the screen. Secondary data (products, signers) open in sheets.
21
+ */
22
+ const DocumentDetailsShell = ({
23
+ theme,
24
+ title,
25
+ clientName,
26
+ meta,
27
+ totalLabel,
28
+ statusLabel,
29
+ statusColor,
30
+ onBack,
31
+ loading,
32
+ children,
33
+ secondaryActions = [],
34
+ primaryAction,
35
+ footerNote,
36
+ }) => {
37
+ const { width } = useWindowDimensions();
38
+ const isWide = width >= WIDE_BREAKPOINT;
39
+ const colors = resolveDocumentDetailsTheme(theme);
40
+ const styles = createDocumentDetailsStyles(colors, isWide);
41
+ const chipColor = statusColor || colors.muted;
42
+
43
+ return (
44
+ <SafeAreaView style={styles.container} edges={['top', 'left', 'right']}>
45
+ <View style={styles.header}>
46
+ <View style={styles.headerInner}>
47
+ {onBack ? (
48
+ <TouchableOpacity
49
+ accessibilityRole="button"
50
+ accessibilityLabel="Voltar"
51
+ onPress={onBack}
52
+ style={styles.backButton}>
53
+ <Icon name="arrow-back" size={20} color={colors.text} />
54
+ </TouchableOpacity>
55
+ ) : null}
56
+
57
+ <View style={styles.headerText}>
58
+ <View style={styles.titleRow}>
59
+ <Text style={styles.title} numberOfLines={1}>
60
+ {title}
61
+ </Text>
62
+ {statusLabel ? (
63
+ <View style={[styles.statusChip, { borderColor: `${chipColor}55`, backgroundColor: `${chipColor}14` }]}>
64
+ <View style={[styles.statusDot, { backgroundColor: chipColor }]} />
65
+ <Text style={[styles.statusText, { color: chipColor }]} numberOfLines={1}>
66
+ {statusLabel}
67
+ </Text>
68
+ </View>
69
+ ) : null}
70
+ </View>
71
+ <Text style={styles.subtitle} numberOfLines={1}>
72
+ {[clientName, meta].filter(Boolean).join(' · ')}
73
+ </Text>
74
+ </View>
75
+
76
+ {totalLabel ? (
77
+ <View style={styles.totalBox}>
78
+ <Text style={styles.totalCaption}>Total</Text>
79
+ <Text style={styles.totalValue} numberOfLines={1}>
80
+ {totalLabel}
81
+ </Text>
82
+ </View>
83
+ ) : null}
84
+ </View>
85
+ </View>
86
+
87
+ <ScrollView style={styles.body} contentContainerStyle={styles.bodyContent}>
88
+ <View style={styles.paper}>
89
+ {loading ? (
90
+ <View style={styles.loading}>
91
+ <ActivityIndicator color={colors.primary} />
92
+ </View>
93
+ ) : (
94
+ children
95
+ )}
96
+ </View>
97
+ </ScrollView>
98
+
99
+ <View style={styles.footer}>
100
+ <View style={styles.footerInner}>
101
+ <View style={styles.secondaryActions}>
102
+ {secondaryActions.map(action => (
103
+ <TouchableOpacity
104
+ key={action.key}
105
+ accessibilityRole="button"
106
+ accessibilityLabel={action.label}
107
+ onPress={action.onPress}
108
+ style={styles.secondaryButton}>
109
+ <Icon name={action.icon} size={18} color={colors.text} />
110
+ {isWide ? <Text style={styles.secondaryLabel}>{action.label}</Text> : null}
111
+ {Number.isFinite(action.count) ? (
112
+ <View style={styles.countBadge}>
113
+ <Text style={styles.countText}>{action.count}</Text>
114
+ </View>
115
+ ) : null}
116
+ </TouchableOpacity>
117
+ ))}
118
+ </View>
119
+
120
+ {primaryAction ? (
121
+ <TouchableOpacity
122
+ accessibilityRole="button"
123
+ accessibilityLabel={primaryAction.label}
124
+ disabled={primaryAction.disabled || primaryAction.loading}
125
+ onPress={primaryAction.onPress}
126
+ style={[
127
+ styles.primaryButton,
128
+ (primaryAction.disabled || primaryAction.loading) && styles.primaryButtonDisabled,
129
+ ]}>
130
+ {primaryAction.loading ? (
131
+ <ActivityIndicator color={colors.onPrimary} size="small" />
132
+ ) : (
133
+ <Icon name={primaryAction.icon || 'check'} size={18} color={colors.onPrimary} />
134
+ )}
135
+ <Text style={styles.primaryLabel} numberOfLines={1}>
136
+ {primaryAction.label}
137
+ </Text>
138
+ </TouchableOpacity>
139
+ ) : null}
140
+ </View>
141
+ {footerNote ? <Text style={styles.footerNote}>{footerNote}</Text> : null}
142
+ </View>
143
+ </SafeAreaView>
144
+ );
145
+ };
146
+
147
+ export default DocumentDetailsShell;
@@ -0,0 +1,163 @@
1
+ import { Platform, StyleSheet } from 'react-native';
2
+
3
+ const DEFAULT_THEME = {
4
+ primary: '#1f6feb',
5
+ onPrimary: '#ffffff',
6
+ background: '#f3f5f8',
7
+ surface: '#ffffff',
8
+ text: '#0f172a',
9
+ muted: '#64748b',
10
+ border: '#e5e9f0',
11
+ };
12
+
13
+ export const resolveDocumentDetailsTheme = theme => ({ ...DEFAULT_THEME, ...(theme || {}) });
14
+
15
+ const softShadow = Platform.select({
16
+ web: { boxShadow: '0 1px 2px rgba(15, 23, 42, 0.06), 0 8px 24px rgba(15, 23, 42, 0.06)' },
17
+ default: {
18
+ shadowColor: '#0f172a',
19
+ shadowOpacity: 0.08,
20
+ shadowRadius: 12,
21
+ shadowOffset: { width: 0, height: 4 },
22
+ elevation: 2,
23
+ },
24
+ });
25
+
26
+ const MAX_CONTENT_WIDTH = 920;
27
+
28
+ export const createDocumentDetailsStyles = (colors, isWide) =>
29
+ StyleSheet.create({
30
+ container: { flex: 1, backgroundColor: colors.background },
31
+
32
+ header: {
33
+ backgroundColor: colors.surface,
34
+ borderBottomWidth: 1,
35
+ borderBottomColor: colors.border,
36
+ paddingHorizontal: isWide ? 24 : 12,
37
+ paddingVertical: isWide ? 12 : 10,
38
+ },
39
+ headerInner: {
40
+ flexDirection: 'row',
41
+ alignItems: 'center',
42
+ width: '100%',
43
+ maxWidth: MAX_CONTENT_WIDTH,
44
+ alignSelf: 'center',
45
+ },
46
+ backButton: {
47
+ width: 36,
48
+ height: 36,
49
+ borderRadius: 18,
50
+ alignItems: 'center',
51
+ justifyContent: 'center',
52
+ backgroundColor: colors.background,
53
+ marginRight: 12,
54
+ },
55
+ headerText: { flex: 1, minWidth: 0 },
56
+ titleRow: { flexDirection: 'row', alignItems: 'center' },
57
+ title: {
58
+ flexShrink: 1,
59
+ fontSize: isWide ? 17 : 15,
60
+ fontWeight: '700',
61
+ color: colors.text,
62
+ letterSpacing: -0.2,
63
+ },
64
+ subtitle: { marginTop: 2, fontSize: 12.5, color: colors.muted },
65
+ statusChip: {
66
+ flexDirection: 'row',
67
+ alignItems: 'center',
68
+ marginLeft: 8,
69
+ paddingHorizontal: 8,
70
+ paddingVertical: 2,
71
+ borderRadius: 999,
72
+ borderWidth: 1,
73
+ },
74
+ statusDot: { width: 6, height: 6, borderRadius: 3, marginRight: 5 },
75
+ statusText: { fontSize: 11.5, fontWeight: '700' },
76
+ totalBox: { marginLeft: 12, alignItems: 'flex-end' },
77
+ totalCaption: {
78
+ fontSize: 10.5,
79
+ fontWeight: '600',
80
+ color: colors.muted,
81
+ textTransform: 'uppercase',
82
+ letterSpacing: 0.6,
83
+ },
84
+ totalValue: { fontSize: isWide ? 18 : 15, fontWeight: '800', color: colors.text },
85
+
86
+ body: { flex: 1 },
87
+ bodyContent: {
88
+ paddingHorizontal: isWide ? 24 : 0,
89
+ paddingVertical: isWide ? 24 : 0,
90
+ paddingBottom: isWide ? 32 : 16,
91
+ },
92
+ paper: {
93
+ width: '100%',
94
+ maxWidth: MAX_CONTENT_WIDTH,
95
+ alignSelf: 'center',
96
+ backgroundColor: colors.surface,
97
+ borderRadius: isWide ? 14 : 0,
98
+ paddingHorizontal: isWide ? 40 : 16,
99
+ paddingVertical: isWide ? 36 : 16,
100
+ minHeight: 240,
101
+ ...(isWide ? softShadow : {}),
102
+ },
103
+ loading: { paddingVertical: 48, alignItems: 'center' },
104
+
105
+ footer: {
106
+ backgroundColor: colors.surface,
107
+ borderTopWidth: 1,
108
+ borderTopColor: colors.border,
109
+ paddingHorizontal: isWide ? 24 : 12,
110
+ paddingTop: 10,
111
+ paddingBottom: Platform.OS === 'ios' ? 28 : 10,
112
+ },
113
+ footerInner: {
114
+ flexDirection: 'row',
115
+ alignItems: 'center',
116
+ width: '100%',
117
+ maxWidth: MAX_CONTENT_WIDTH,
118
+ alignSelf: 'center',
119
+ },
120
+ secondaryActions: { flexDirection: 'row', alignItems: 'center', flexShrink: 0 },
121
+ secondaryButton: {
122
+ flexDirection: 'row',
123
+ alignItems: 'center',
124
+ height: 42,
125
+ paddingHorizontal: isWide ? 14 : 12,
126
+ marginRight: 8,
127
+ borderRadius: 10,
128
+ borderWidth: 1,
129
+ borderColor: colors.border,
130
+ backgroundColor: colors.surface,
131
+ },
132
+ secondaryLabel: { marginLeft: 6, fontSize: 14, fontWeight: '600', color: colors.text },
133
+ countBadge: {
134
+ minWidth: 20,
135
+ height: 20,
136
+ paddingHorizontal: 6,
137
+ marginLeft: 6,
138
+ borderRadius: 10,
139
+ alignItems: 'center',
140
+ justifyContent: 'center',
141
+ backgroundColor: colors.background,
142
+ },
143
+ countText: { fontSize: 11.5, fontWeight: '700', color: colors.text },
144
+ primaryButton: {
145
+ flex: 1,
146
+ flexDirection: 'row',
147
+ alignItems: 'center',
148
+ justifyContent: 'center',
149
+ height: 44,
150
+ paddingHorizontal: 18,
151
+ borderRadius: 10,
152
+ backgroundColor: colors.primary,
153
+ ...(isWide ? { flex: 0, minWidth: 220, marginLeft: 'auto' } : {}),
154
+ },
155
+ primaryButtonDisabled: { opacity: 0.5 },
156
+ primaryLabel: { marginLeft: 8, fontSize: 15, fontWeight: '700', color: colors.onPrimary },
157
+ footerNote: {
158
+ marginTop: 6,
159
+ fontSize: 12,
160
+ color: colors.muted,
161
+ textAlign: 'center',
162
+ },
163
+ });
@@ -0,0 +1,87 @@
1
+ import React from 'react';
2
+ import { Platform, Pressable, StyleSheet, Text, TouchableOpacity, useWindowDimensions, View } from 'react-native';
3
+ import Icon from 'react-native-vector-icons/MaterialIcons';
4
+ import AnimatedModal from '@controleonline/ui-common/src/react/components/AnimatedModal';
5
+ import { resolveDocumentDetailsTheme } from './DocumentDetailsShell.styles';
6
+
7
+ /**
8
+ * Bottom sheet (centered panel on wide screens) for secondary document data,
9
+ * such as products and signers, so they don't take space from the document.
10
+ */
11
+ const DocumentSheet = ({ visible, onClose, title, subtitle, theme, children }) => {
12
+ const { width, height } = useWindowDimensions();
13
+ const isWide = width >= 768;
14
+ const colors = resolveDocumentDetailsTheme(theme);
15
+
16
+ return (
17
+ <AnimatedModal visible={visible} onRequestClose={onClose}>
18
+ <Pressable style={styles.backdrop} onPress={onClose} accessibilityLabel="Fechar" />
19
+ <View
20
+ style={[
21
+ styles.sheet,
22
+ {
23
+ backgroundColor: colors.surface,
24
+ maxHeight: Math.round(height * (isWide ? 0.8 : 0.86)),
25
+ },
26
+ isWide ? styles.sheetWide : null,
27
+ ]}>
28
+ <View style={styles.handleWrap}>
29
+ <View style={[styles.handle, { backgroundColor: colors.border }]} />
30
+ </View>
31
+ <View style={[styles.header, { borderBottomColor: colors.border }]}>
32
+ <View style={styles.headerText}>
33
+ <Text style={[styles.title, { color: colors.text }]} numberOfLines={1}>
34
+ {title}
35
+ </Text>
36
+ {subtitle ? (
37
+ <Text style={[styles.subtitle, { color: colors.muted }]} numberOfLines={1}>
38
+ {subtitle}
39
+ </Text>
40
+ ) : null}
41
+ </View>
42
+ <TouchableOpacity
43
+ accessibilityRole="button"
44
+ accessibilityLabel="Fechar"
45
+ onPress={onClose}
46
+ style={[styles.close, { backgroundColor: colors.background }]}>
47
+ <Icon name="close" size={20} color={colors.text} />
48
+ </TouchableOpacity>
49
+ </View>
50
+ <View style={styles.body}>{children}</View>
51
+ </View>
52
+ </AnimatedModal>
53
+ );
54
+ };
55
+
56
+ const styles = StyleSheet.create({
57
+ backdrop: { flex: 1 },
58
+ sheet: {
59
+ width: '100%',
60
+ borderTopLeftRadius: 18,
61
+ borderTopRightRadius: 18,
62
+ overflow: 'hidden',
63
+ paddingBottom: Platform.OS === 'ios' ? 24 : 8,
64
+ },
65
+ sheetWide: {
66
+ maxWidth: 760,
67
+ alignSelf: 'center',
68
+ borderRadius: 18,
69
+ marginBottom: 32,
70
+ },
71
+ handleWrap: { alignItems: 'center', paddingTop: 8 },
72
+ handle: { width: 40, height: 4, borderRadius: 2 },
73
+ header: {
74
+ flexDirection: 'row',
75
+ alignItems: 'center',
76
+ paddingHorizontal: 20,
77
+ paddingVertical: 12,
78
+ borderBottomWidth: 1,
79
+ },
80
+ headerText: { flex: 1, minWidth: 0 },
81
+ title: { fontSize: 17, fontWeight: '700', letterSpacing: -0.2 },
82
+ subtitle: { fontSize: 12.5, marginTop: 2 },
83
+ close: { width: 34, height: 34, borderRadius: 17, alignItems: 'center', justifyContent: 'center' },
84
+ body: { flexShrink: 1 },
85
+ });
86
+
87
+ export default DocumentSheet;
@@ -0,0 +1,41 @@
1
+ import { useCallback, useEffect, useState } from 'react';
2
+ import {
3
+ fetchLinkedOrder,
4
+ fetchOrderProducts,
5
+ } from '@controleonline/ui-common/src/react/utils/commercialDocumentOrders';
6
+ import { formatBRL, summarizeOrderProducts } from '@controleonline/ui-common/src/react/utils/orderProductsSummary';
7
+
8
+ /**
9
+ * Product count and total of the order linked to a proposal/contract, for the
10
+ * fixed document header. Call `reload` after products change.
11
+ */
12
+ const useLinkedOrderSummary = contractRef => {
13
+ const [summary, setSummary] = useState({ count: 0, total: 0, loaded: false });
14
+
15
+ const reload = useCallback(async () => {
16
+ if (!contractRef) {
17
+ setSummary({ count: 0, total: 0, loaded: true });
18
+ return;
19
+ }
20
+
21
+ try {
22
+ const order = await fetchLinkedOrder(contractRef);
23
+ const items = order ? await fetchOrderProducts(order['@id'] || order.id) : [];
24
+ setSummary({ ...summarizeOrderProducts(items), loaded: true });
25
+ } catch {
26
+ setSummary(current => ({ ...current, loaded: true }));
27
+ }
28
+ }, [contractRef]);
29
+
30
+ useEffect(() => {
31
+ reload();
32
+ }, [reload]);
33
+
34
+ return {
35
+ ...summary,
36
+ totalLabel: summary.loaded && summary.count > 0 ? formatBRL(summary.total) : null,
37
+ reload,
38
+ };
39
+ };
40
+
41
+ export default useLinkedOrderSummary;
@@ -0,0 +1,42 @@
1
+ // Which clients a user may pick when creating proposals/contracts.
2
+ // Mirrors the backend contract security filter (ContractService::securityFilter):
3
+ // owners/managers of the company see every client; a seller only sees the
4
+ // clients of his own portfolio (PeopleLink linkType "sellers-client", whose
5
+ // company is the seller). Offering other clients would create a document the
6
+ // seller cannot open afterwards.
7
+
8
+ const MANAGEMENT_PERMISSIONS = ['owner', 'manager'];
9
+
10
+ const normalizeEntityId = value => String(value ?? '').replace(/\D/g, '');
11
+
12
+ const normalizePermissions = permissions =>
13
+ (Array.isArray(permissions) ? permissions : [permissions])
14
+ .map(permission => String(permission || '').trim().toLowerCase())
15
+ .filter(Boolean);
16
+
17
+ const resolveClientPortfolioParams = ({ currentCompanyId, permissions, sellerPeopleId } = {}) => {
18
+ const companyId = normalizeEntityId(currentCompanyId);
19
+ if (!companyId) {
20
+ return null;
21
+ }
22
+
23
+ const normalized = normalizePermissions(permissions);
24
+ const manages = normalized.some(permission => MANAGEMENT_PERMISSIONS.includes(permission));
25
+ const sellerId = normalizeEntityId(sellerPeopleId);
26
+
27
+ if (!manages && normalized.includes('salesman') && sellerId) {
28
+ return {
29
+ 'link.company': `/people/${sellerId}`,
30
+ 'link.linkType': 'sellers-client',
31
+ };
32
+ }
33
+
34
+ return {
35
+ 'link.company': `/people/${companyId}`,
36
+ 'link.linkType': 'client',
37
+ };
38
+ };
39
+
40
+ module.exports = {
41
+ resolveClientPortfolioParams,
42
+ };
@@ -1,26 +1,27 @@
1
1
  // File.content comes base64 encoded from the API (File::getContent()). Contract
2
- // and proposal documents are HTML generated from Twig models, while signed
3
- // documents may be PDFs. Decode before deciding how to render.
2
+ // and proposal documents are generated from Twig models (HTML or plain text;
3
+ // plain text must be rendered as native text, not through RenderHTML),
4
+ // while signed documents may be PDFs. Decode before deciding how to render.
4
5
 
5
6
  const BASE64_PATTERN = /^[A-Za-z0-9+/=\r\n]+$/;
6
7
 
7
- const decodeBase64Utf8 = value => {
8
- const binary =
9
- typeof globalThis.atob === 'function'
10
- ? globalThis.atob(value)
11
- : typeof Buffer !== 'undefined'
12
- ? Buffer.from(value, 'base64').toString('binary')
13
- : null;
14
- if (binary === null) {
15
- return null;
8
+ const decodeBase64Binary = value => {
9
+ if (typeof globalThis.atob === 'function') {
10
+ return globalThis.atob(value);
16
11
  }
17
-
18
- const percentEncoded = Array.from(binary)
19
- .map(char => `%${char.charCodeAt(0).toString(16).padStart(2, '0')}`)
20
- .join('');
21
- return decodeURIComponent(percentEncoded);
12
+ if (typeof Buffer !== 'undefined') {
13
+ return Buffer.from(value, 'base64').toString('binary');
14
+ }
15
+ return null;
22
16
  };
23
17
 
18
+ const binaryToUtf8 = binary =>
19
+ decodeURIComponent(
20
+ Array.from(binary)
21
+ .map(char => `%${char.charCodeAt(0).toString(16).padStart(2, '0')}`)
22
+ .join(''),
23
+ );
24
+
24
25
  const looksLikeHtml = value => String(value || '').trim().startsWith('<');
25
26
 
26
27
  const resolveDocumentFileContent = content => {
@@ -35,15 +36,20 @@ const resolveDocumentFileContent = content => {
35
36
 
36
37
  const compact = raw.trim();
37
38
  if (BASE64_PATTERN.test(compact)) {
38
- try {
39
- const decoded = decodeBase64Utf8(compact.replace(/[\r\n]/g, ''));
40
- if (decoded !== null && looksLikeHtml(decoded)) {
41
- return { kind: 'html', content: decoded };
39
+ const binary = decodeBase64Binary(compact.replace(/[\r\n]/g, ''));
40
+ if (binary !== null) {
41
+ if (binary.startsWith('%PDF')) {
42
+ return { kind: 'pdf', content: compact };
43
+ }
44
+ try {
45
+ const decoded = binaryToUtf8(binary);
46
+ return looksLikeHtml(decoded)
47
+ ? { kind: 'html', content: decoded }
48
+ : { kind: 'text', content: decoded };
49
+ } catch {
50
+ // Not UTF-8 text: keep the binary payload for a viewer.
42
51
  }
43
- } catch {
44
- // Not UTF-8 text: binary payload such as a PDF.
45
52
  }
46
-
47
53
  return { kind: 'pdf', content: compact };
48
54
  }
49
55
 
@@ -0,0 +1,28 @@
1
+ // Summary shown in proposal/contract headers: only top-level lines count;
2
+ // component/addition rows are already priced inside their parent line.
3
+
4
+ const isTopLevelOrderProduct = item => !item?.orderProduct && !item?.parentProduct;
5
+
6
+ const summarizeOrderProducts = items => {
7
+ const lines = (Array.isArray(items) ? items : []).filter(isTopLevelOrderProduct);
8
+ const total = lines.reduce((sum, item) => {
9
+ const lineTotal = Number(item?.total);
10
+ if (Number.isFinite(lineTotal)) {
11
+ return sum + lineTotal;
12
+ }
13
+ return sum + Number(item?.price || 0) * Number(item?.quantity || 0);
14
+ }, 0);
15
+
16
+ return { count: lines.length, total: Math.round(total * 100) / 100 };
17
+ };
18
+
19
+ const formatBRL = value =>
20
+ `R$ ${Number(value || 0)
21
+ .toFixed(2)
22
+ .replace('.', ',')
23
+ .replace(/\B(?=(\d{3})+(?!\d))/g, '.')}`;
24
+
25
+ module.exports = {
26
+ formatBRL,
27
+ summarizeOrderProducts,
28
+ };
@@ -1,3 +1,5 @@
1
+ import { resolveClientPortfolioParams } from '@controleonline/ui-common/src/react/utils/clientPortfolioParams';
2
+
1
3
  const normalizeText = value => String(value || '').trim();
2
4
 
3
5
  const normalizeEntityId = value => String(value || '').replace(/\D/g, '');
@@ -24,16 +26,9 @@ export const getPeopleDisplayName = person => {
24
26
  return responsibleLabel || companyLabel;
25
27
  };
26
28
 
27
- export const buildOwnedClientsParams = ({
28
- currentCompanyId,
29
- }) => {
30
- const ownerId = normalizeEntityId(currentCompanyId);
31
- if (!ownerId) {
32
- return null;
33
- }
34
-
35
- return {
36
- 'link.company': `/people/${ownerId}`,
37
- 'link.linkType': 'client',
38
- };
39
- };
29
+ // Sellers only get their own portfolio; see clientPortfolioParams.js.
30
+ export const buildOwnedClientsParams = ({
31
+ currentCompanyId,
32
+ permissions,
33
+ sellerPeopleId,
34
+ }) => resolveClientPortfolioParams({ currentCompanyId, permissions, sellerPeopleId });
@@ -0,0 +1,30 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const { resolveClientPortfolioParams } = require('../../../react/utils/clientPortfolioParams');
4
+
5
+ test('seller only sees his own portfolio', () => {
6
+ assert.deepEqual(
7
+ resolveClientPortfolioParams({ currentCompanyId: 1, permissions: ['salesman'], sellerPeopleId: 31487 }),
8
+ { 'link.company': '/people/31487', 'link.linkType': 'sellers-client' },
9
+ );
10
+ });
11
+
12
+ test('owners and managers see every company client', () => {
13
+ const expected = { 'link.company': '/people/1', 'link.linkType': 'client' };
14
+ assert.deepEqual(
15
+ resolveClientPortfolioParams({ currentCompanyId: 1, permissions: ['salesman', 'owner'], sellerPeopleId: 7 }),
16
+ expected,
17
+ );
18
+ assert.deepEqual(
19
+ resolveClientPortfolioParams({ currentCompanyId: '/people/1', permissions: 'manager', sellerPeopleId: 7 }),
20
+ expected,
21
+ );
22
+ });
23
+
24
+ test('without seller data falls back to company clients, without company returns null', () => {
25
+ assert.deepEqual(
26
+ resolveClientPortfolioParams({ currentCompanyId: 1, permissions: ['salesman'] }),
27
+ { 'link.company': '/people/1', 'link.linkType': 'client' },
28
+ );
29
+ assert.equal(resolveClientPortfolioParams({ permissions: ['salesman'], sellerPeopleId: 1 }), null);
30
+ });
@@ -13,16 +13,17 @@ test('keeps plain HTML as is', () => {
13
13
  assert.deepEqual(resolveDocumentFileContent(' <p>ok</p>'), { kind: 'html', content: ' <p>ok</p>' });
14
14
  });
15
15
 
16
- test('treats non-HTML base64 payloads as PDF', () => {
17
- const pdf = Buffer.from([0x25, 0x50, 0x44, 0x46, 0x2d, 0xff, 0xfe, 0x00]).toString('base64');
16
+ test('plain-text models are returned decoded as text', () => {
17
+ const text = 'CONTRATO PADRÃO\nCláusula 1 – <nome_contratante> & mais';
18
+ assert.deepEqual(resolveDocumentFileContent(toBase64(text)), { kind: 'text', content: text });
19
+ });
20
+
21
+ test('PDF payloads stay base64 for the viewer', () => {
22
+ const pdf = Buffer.from('%PDF-1.7\n\xff\xfe binary', 'binary').toString('base64');
18
23
  assert.deepEqual(resolveDocumentFileContent(pdf), { kind: 'pdf', content: pdf });
19
24
  });
20
25
 
21
- test('empty and plain text contents', () => {
26
+ test('empty contents', () => {
22
27
  assert.deepEqual(resolveDocumentFileContent(''), { kind: 'empty', content: '' });
23
28
  assert.deepEqual(resolveDocumentFileContent(null), { kind: 'empty', content: '' });
24
- assert.deepEqual(resolveDocumentFileContent('Contrato simples, sem HTML.'), {
25
- kind: 'text',
26
- content: 'Contrato simples, sem HTML.',
27
- });
28
29
  });
@@ -0,0 +1,24 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const { formatBRL, summarizeOrderProducts } = require('../../../react/utils/orderProductsSummary');
4
+
5
+ test('sums only top-level lines', () => {
6
+ const items = [
7
+ { id: 1, quantity: 2, price: 130, total: 260 },
8
+ { id: 2, quantity: 1, price: 0.01, total: 0.01 },
9
+ { id: 3, quantity: 1, price: 10, total: 10, orderProduct: '/order_products/1' },
10
+ ];
11
+ assert.deepEqual(summarizeOrderProducts(items), { count: 2, total: 260.01 });
12
+ });
13
+
14
+ test('falls back to price x quantity and handles empty input', () => {
15
+ assert.deepEqual(summarizeOrderProducts([{ quantity: 3, price: 2.5 }]), { count: 1, total: 7.5 });
16
+ assert.deepEqual(summarizeOrderProducts(null), { count: 0, total: 0 });
17
+ });
18
+
19
+ test('formats Brazilian currency', () => {
20
+ assert.equal(formatBRL(1260), 'R$ 1.260,00');
21
+ assert.equal(formatBRL(260.01), 'R$ 260,01');
22
+ assert.equal(formatBRL(0), 'R$ 0,00');
23
+ assert.equal(formatBRL(1234567.8), 'R$ 1.234.567,80');
24
+ });