@controleonline/ui-crm 1.0.42

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 (141) hide show
  1. package/.github/actions/workers/manager/action.yml +147 -0
  2. package/.github/actions/workers/qa/action.yml +44 -0
  3. package/.github/actions/workers/security/action.yml +44 -0
  4. package/.github/actions/workers/technical-documenter/action.yml +51 -0
  5. package/.github/workflows/manager-worker.yml +167 -0
  6. package/.github/workflows/publish-npm.yml +40 -0
  7. package/.github/workflows/pull-request-checks.yml +29 -0
  8. package/.scrutinizer.yml +24 -0
  9. package/AGENTS.md +56 -0
  10. package/FUNDING.yml +1 -0
  11. package/docs/technical/Cliente-Vendedor-Vinculo-e-Permissoes.md +121 -0
  12. package/docs/technical/Income-Statements-Demonstrativo.md +38 -0
  13. package/docs/technical/Oportunidades-Ordenacao-por-Data-de-Retorno.md +134 -0
  14. package/docs/technical/Propostas-Filtro-de-Status.md +147 -0
  15. package/docs/technical/Royalties-a-pagar-Franqueado.md +51 -0
  16. package/docs/technical/Visao-Vendedor-Comissoes.md +58 -0
  17. package/docs/wiki.md +1 -0
  18. package/package.json +43 -0
  19. package/scripts/validate-wiki-pointer.cjs +13 -0
  20. package/src/react/components/AnimatedModal.js +149 -0
  21. package/src/react/components/AnimatedModal.styles.js +21 -0
  22. package/src/react/components/CreateContractModal.js +151 -0
  23. package/src/react/components/CreateContractModal.styles.js +43 -0
  24. package/src/react/hooks/useToastMessage.js +59 -0
  25. package/src/react/index.js +4 -0
  26. package/src/react/pages/ModelTemplatesPage.js +1461 -0
  27. package/src/react/pages/ModelTemplatesPage.styles.js +441 -0
  28. package/src/react/pages/comissions/IncomeStatementDetailsModal.js +102 -0
  29. package/src/react/pages/comissions/IncomeStatementsFilters.js +120 -0
  30. package/src/react/pages/comissions/SellerCommissionsPage.js +368 -0
  31. package/src/react/pages/comissions/SellerCommissionsPage.styles.js +219 -0
  32. package/src/react/pages/comissions/incomeStatementsHelpers.js +233 -0
  33. package/src/react/pages/comissions/index.js +309 -0
  34. package/src/react/pages/comissions/index.styles.js +381 -0
  35. package/src/react/pages/comissions/sellerCommissionsHelpers.js +222 -0
  36. package/src/react/pages/crm/components/CrmHeader.js +117 -0
  37. package/src/react/pages/crm/components/MarketingEventsSection.js +142 -0
  38. package/src/react/pages/crm/components/MarketingEventsSection.styles.js +105 -0
  39. package/src/react/pages/crm/components/OpportunityCard.js +138 -0
  40. package/src/react/pages/crm/components/OpportunityFormModal.js +279 -0
  41. package/src/react/pages/crm/components/OpportunityList.js +113 -0
  42. package/src/react/pages/crm/components/OpportunitySkeletons.js +53 -0
  43. package/src/react/pages/crm/components/ProviderSelectModal.js +166 -0
  44. package/src/react/pages/crm/components/SelectModal.js +178 -0
  45. package/src/react/pages/crm/conversation.js +342 -0
  46. package/src/react/pages/crm/conversation.styles.js +206 -0
  47. package/src/react/pages/crm/hooks/useCrmData.js +494 -0
  48. package/src/react/pages/crm/hooks/useOpportunityForms.js +306 -0
  49. package/src/react/pages/crm/index.js +262 -0
  50. package/src/react/pages/crm/index.styles.js +13 -0
  51. package/src/react/pages/crm/marketingEventsHelpers.js +41 -0
  52. package/src/react/pages/crm/styles/card.styles.js +178 -0
  53. package/src/react/pages/crm/styles/layout.styles.js +184 -0
  54. package/src/react/pages/crm/styles/modal.styles.js +347 -0
  55. package/src/react/pages/home/index.js +559 -0
  56. package/src/react/pages/home/index.styles.js +268 -0
  57. package/src/react/pages/proposals/CreateProposalsModal.js +466 -0
  58. package/src/react/pages/proposals/CreateProposalsModal.styles.js +344 -0
  59. package/src/react/pages/proposals/CreateProposalsPickers.js +187 -0
  60. package/src/react/pages/proposals/CreateProposalsProductSection.js +117 -0
  61. package/src/react/pages/proposals/ProposalCard.js +112 -0
  62. package/src/react/pages/proposals/ProposalDetails.js +263 -0
  63. package/src/react/pages/proposals/ProposalDetails.styles.js +195 -0
  64. package/src/react/pages/proposals/index.js +488 -0
  65. package/src/react/pages/proposals/index.styles.js +248 -0
  66. package/src/react/pages/proposals/proposalListHelpers.js +216 -0
  67. package/src/react/pages/proposals/proposalNavigation.js +26 -0
  68. package/src/react/pages/royalties/ReceivablePage.js +233 -0
  69. package/src/react/pages/royalties/RoyaltiesPayablePage.js +260 -0
  70. package/src/react/pages/royalties/index.js +2 -0
  71. package/src/react/pages/royalties/royaltiesReceivableHelpers.js +68 -0
  72. package/src/react/pages/settings/GeneralSettings.js +317 -0
  73. package/src/react/pages/settings/GeneralSettings.shared.js +490 -0
  74. package/src/react/pages/settings/GeneralSettings.styles.js +746 -0
  75. package/src/react/pages/settings/GeneralSettingsSection.js +57 -0
  76. package/src/react/pages/settings/generalSettingsActiveTab.js +85 -0
  77. package/src/react/pages/settings/sections/CrmSection.js +281 -0
  78. package/src/react/pages/settings/sections/DeviceRuntimeFooterSection.js +128 -0
  79. package/src/react/pages/settings/sections/DisplayPreparationSection.js +155 -0
  80. package/src/react/pages/settings/sections/IntegrationsSection.js +392 -0
  81. package/src/react/pages/settings/sections/LogSection.js +322 -0
  82. package/src/react/pages/settings/sections/LoginSection.js +137 -0
  83. package/src/react/pages/settings/sections/LoyaltyProductPicker.js +230 -0
  84. package/src/react/pages/settings/sections/LoyaltySection.js +451 -0
  85. package/src/react/pages/settings/sections/MaintenanceSection.js +205 -0
  86. package/src/react/pages/settings/sections/MapsSection.js +629 -0
  87. package/src/react/pages/settings/sections/MenuCatalogSection.js +405 -0
  88. package/src/react/pages/settings/sections/OperationsSection.js +303 -0
  89. package/src/react/pages/settings/sections/OrderPaymentSection.js +379 -0
  90. package/src/react/pages/settings/sections/OrderPrintSection.js +308 -0
  91. package/src/react/pages/settings/sections/ShopSection.js +490 -0
  92. package/src/react/pages/settings/sections/shop/FranchiseMapPreview.js +124 -0
  93. package/src/react/pages/settings/sections/shop/ShopDomainCreateForm.js +57 -0
  94. package/src/react/pages/settings/sections/shop/ShopDomainPanel.js +184 -0
  95. package/src/react/pages/settings/sections/shop/ShopDomainShowcasesSection.js +237 -0
  96. package/src/react/pages/settings/sections/shop/ShopDomainShowcasesSection.styles.js +256 -0
  97. package/src/react/pages/settings/sections/shop/ShopDomainTabs.js +61 -0
  98. package/src/react/pages/settings/sections/shop/ShopFranchiseLocatorSection.js +526 -0
  99. package/src/react/pages/settings/sections/shop/ShopLoyaltySection.js +426 -0
  100. package/src/react/pages/settings/sections/shop/ShopSettingsSection.js +10 -0
  101. package/src/react/pages/settings/sections/shop/mapsFranchiseMapHelpers.js +163 -0
  102. package/src/react/pages/settings/sections/shop/shopDomainShowcasesUtils.js +68 -0
  103. package/src/react/pages/settings/sections/shop/shopFranchiseVisibility.js +158 -0
  104. package/src/react/pages/settings/sections/shop/shopSettingsShared.js +427 -0
  105. package/src/react/router/routes.js +135 -0
  106. package/src/react/utils/opportunityDate.js +82 -0
  107. package/src/react/utils/opportunityEditorReferences.js +76 -0
  108. package/src/react/utils/opportunityEmptyState.js +20 -0
  109. package/src/react/utils/opportunityPeople.js +111 -0
  110. package/src/react/utils/opportunityPhone.js +82 -0
  111. package/src/react/utils/opportunityStage.js +30 -0
  112. package/src/react/utils/opportunityStatusFilter.js +54 -0
  113. package/src/react/utils/proposalCreateHelpers.js +61 -0
  114. package/src/react/utils/proposalProductSelection.js +71 -0
  115. package/src/react/utils/royaltiesPayableParams.js +37 -0
  116. package/src/react/utils/translateWithFallback.js +42 -0
  117. package/src/store/crm/index.js +2 -0
  118. package/src/store/model/index.js +104 -0
  119. package/src/tests/browser/crm/create-proposal-product-category-filter.spec.js +149 -0
  120. package/src/tests/browser/crm/crm-index-status-filter.spec.js +263 -0
  121. package/src/tests/browser/crm/crm-opportunity-category-editor.spec.js +269 -0
  122. package/src/tests/browser/crm/royalties-payable.spec.js +122 -0
  123. package/src/tests/browser/crm/royalties-receivable.spec.js +121 -0
  124. package/src/tests/browser/crm/seller-commissions.spec.js +214 -0
  125. package/src/tests/browser/manager/general-settings-maps.spec.js +400 -0
  126. package/src/tests/react/pages/comissions/incomeStatementsHelpers.test.js +181 -0
  127. package/src/tests/react/pages/comissions/sellerCommissionsHelpers.test.js +132 -0
  128. package/src/tests/react/pages/crm/marketingEventsHelpers.test.cjs +53 -0
  129. package/src/tests/react/pages/crm/opportunitySearchParams.test.cjs +44 -0
  130. package/src/tests/react/pages/proposals/navigation.test.js +71 -0
  131. package/src/tests/react/pages/proposals/proposalListHelpers.test.js +42 -0
  132. package/src/tests/react/pages/royalties/royaltiesReceivableHelpers.test.js +60 -0
  133. package/src/tests/react/pages/settings/generalSettings.shared.test.js +102 -0
  134. package/src/tests/react/pages/settings/sections/shop/shopDomainShowcasesUtils.test.js +60 -0
  135. package/src/tests/react/pages/settings/sections/shop/shopFranchiseVisibility.test.js +80 -0
  136. package/src/tests/react/utils/opportunityEditorReferences.test.js +70 -0
  137. package/src/tests/react/utils/opportunityEmptyState.test.js +39 -0
  138. package/src/tests/react/utils/opportunityStatusFilter.test.cjs +81 -0
  139. package/src/tests/react/utils/proposalCreateHelpers.test.js +25 -0
  140. package/src/tests/react/utils/proposalProductSelection.test.js +76 -0
  141. package/src/tests/react/utils/royaltiesPayableParams.test.js +44 -0
@@ -0,0 +1,1461 @@
1
+ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import { ActivityIndicator, Alert, Platform, ScrollView, Text, TextInput, TouchableOpacity, View, useWindowDimensions } from 'react-native';
3
+ import { SafeAreaView } from 'react-native-safe-area-context';
4
+ import { Picker } from '@react-native-picker/picker';
5
+ import { useFocusEffect } from '@react-navigation/native';
6
+ import RenderHTML from 'react-native-render-html';
7
+ import Icon from 'react-native-vector-icons/Feather';
8
+ import { useStore } from '@store';
9
+ import { api } from '@controleonline/ui-common/src/api';
10
+ import useToastMessage from '@controleonline/ui-crm/src/react/hooks/useToastMessage';
11
+
12
+ import {
13
+ getCategoryContextForDocument,
14
+ } from '@controleonline/ui-common/src/react/utils/categoryContexts';
15
+
16
+ import { resolveThemePalette, withOpacity } from '@controleonline/../../src/styles/branding';
17
+ import { colors } from '@controleonline/../../src/styles/colors';
18
+ import styles from './ModelTemplatesPage.styles';
19
+ import { inlineStyle_1012_59, inlineStyle_1068_14 } from './ModelTemplatesPage.styles';
20
+
21
+ const cardShadow = Platform.select({
22
+ ios: {
23
+ shadowColor: '#0F172A',
24
+ shadowOffset: { width: 0, height: 6 },
25
+ shadowOpacity: 0.06,
26
+ shadowRadius: 16,
27
+ },
28
+ android: { elevation: 3 },
29
+ web: { boxShadow: '0 6px 18px rgba(15,23,42,0.08)' },
30
+ });
31
+
32
+ const CONTEXT_OPTIONS = [
33
+ { value: 'proposal', label: 'Propostas', newLabel: 'Nova proposta', icon: 'briefcase', color: '#8B5CF6' },
34
+ { value: 'contract', label: 'Contratos', newLabel: 'Novo contrato', icon: 'file-text', color: '#0EA5E9' },
35
+ { value: 'email', label: 'E-mails', newLabel: 'Novo e-mail', icon: 'mail', color: '#10b981' },
36
+ { value: 'menu', label: 'Cardapios', newLabel: 'Novo cardapio', icon: 'book-open', color: '#e67e22' },
37
+ ];
38
+
39
+ const FILTER_OPTIONS = [{ value: 'all', label: 'Todos os tipos' }, ...CONTEXT_OPTIONS];
40
+
41
+ const CONTEXT_HELP = {
42
+ proposal:
43
+ 'Use para propostas comerciais. O backend costuma renderizar este tipo com as variáveis `contract` e `service`.',
44
+ contract:
45
+ 'Use para contratos. O arquivo Twig/HTML é salvo em `files.content` e vinculado ao registro de `models`.',
46
+ email:
47
+ 'Use para e-mails HTML. As variáveis finais dependem do fluxo que renderiza este template.',
48
+ menu:
49
+ 'Use para cardápios. O backend disponibiliza `company`, `companyName`, `columns`, `generatedAt`, `catalog` e `service`. Para PDF, prefira tabelas, cores sólidas, espaçamentos simples e poucas imagens; evite gradientes, flex, pills, sombras e miniaturas em massa.',
50
+ };
51
+
52
+ const COMMON_SNIPPETS = [
53
+ { label: 'Variável', value: '{{ variavel }}' },
54
+ { label: 'Condicional', value: '{% if condicao %}\n <p>Conteudo</p>\n{% endif %}' },
55
+ { label: 'Loop', value: '{% for item in itens %}\n <p>{{ item }}</p>\n{% endfor %}' },
56
+ { label: 'Quebra de página', value: '<div style="page-break-after: always;"></div>' },
57
+ ];
58
+
59
+ const CONTEXT_SNIPPETS = {
60
+ proposal: [
61
+ { label: 'Título', value: '<h1>{{ contract.contractModel.model|default(\'Proposta comercial\') }}</h1>' },
62
+ { label: 'Cliente', value: '{{ contract.client.alias|default(contract.client.name|default(\'\')) }}' },
63
+ { label: 'Fornecedor', value: '{{ contract.provider.alias|default(contract.provider.name|default(\'\')) }}' },
64
+ ],
65
+ contract: [
66
+ { label: 'Título', value: '<h1>{{ contract.contractModel.model|default(\'Contrato\') }}</h1>' },
67
+ { label: 'Início', value: '{{ contract.startDate|date(\'d/m/Y\') }}' },
68
+ { label: 'Assinatura', value: '<div class="signature-line">Assinatura</div>' },
69
+ ],
70
+ email: [
71
+ { label: 'Assunto', value: '{{ subject|default(\'Mensagem importante\') }}' },
72
+ { label: 'Destinatário', value: '{{ recipientName|default(\'Cliente\') }}' },
73
+ { label: 'Botão CTA', value: '{% if ctaUrl %}<a href="{{ ctaUrl }}">{{ ctaLabel|default(\'Abrir link\') }}</a>{% endif %}' },
74
+ ],
75
+ menu: [
76
+ { label: 'Empresa', value: '{{ companyName|default(menuModelName|default(\'Cardápio\')) }}' },
77
+ { label: 'Loop categorias', value: '{% for column in columns %}\n {% for category in column %}\n <h2>{{ category.name }}</h2>\n {% endfor %}\n{% endfor %}' },
78
+ { label: 'Loop produtos', value: '{% for product in category.products %}\n <p>{{ product.name }} - {{ product.priceLabel }}</p>\n{% endfor %}' },
79
+ ],
80
+ };
81
+
82
+ const DEFAULT_CATEGORY_NAMES = {
83
+ proposal: 'Propostas',
84
+ contract: 'Contratos',
85
+ email: 'E-mails',
86
+ menu: 'Cardápios',
87
+ };
88
+
89
+ const formatApiError = error => {
90
+ if (!error) return 'Não foi possível concluir a operação.';
91
+ if (typeof error === 'string') return error;
92
+ if (Array.isArray(error?.message)) {
93
+ return error.message
94
+ .map(item => item?.message || item?.toString?.() || '')
95
+ .filter(Boolean)
96
+ .join(', ');
97
+ }
98
+
99
+ return error?.message || error?.description || error?.errmsg || 'Não foi possível concluir a operação.';
100
+ };
101
+
102
+ const normalizeId = value => String(value || '').replace(/\D/g, '');
103
+
104
+ const toIri = (value, resource) => {
105
+ if (!value) return null;
106
+ if (typeof value === 'string') {
107
+ const normalized = String(value).trim();
108
+ if (!normalized) return null;
109
+ if (normalized.startsWith('/')) return normalized;
110
+ const id = normalizeId(normalized);
111
+ return id ? `/${resource}/${id}` : null;
112
+ }
113
+
114
+ if (value?.['@id']) return value['@id'];
115
+ if (value?.id) return `/${resource}/${value.id}`;
116
+ return null;
117
+ };
118
+
119
+ const getContextMeta = context =>
120
+ CONTEXT_OPTIONS.find(option => option.value === context) || CONTEXT_OPTIONS[0];
121
+
122
+ const slugify = value =>
123
+ String(value || '')
124
+ .normalize('NFD')
125
+ .replace(/[\u0300-\u036f]/g, '')
126
+ .toLowerCase()
127
+ .replace(/[^a-z0-9]+/g, '-')
128
+ .replace(/(^-|-$)/g, '');
129
+
130
+ const buildFileName = (modelName, context) => {
131
+ const base = slugify(modelName) || `modelo-${context}`;
132
+ return `${base}.html`;
133
+ };
134
+
135
+ const decodeBase64Text = value => {
136
+ if (!value) return '';
137
+
138
+ try {
139
+ if (typeof globalThis?.Buffer !== 'undefined') {
140
+ return globalThis.Buffer.from(String(value), 'base64').toString('utf-8');
141
+ }
142
+ } catch (_) {
143
+ // fallback below
144
+ }
145
+
146
+ try {
147
+ if (typeof globalThis?.atob === 'function') {
148
+ const binary = globalThis.atob(String(value));
149
+ if (typeof globalThis?.TextDecoder !== 'undefined') {
150
+ const bytes = Uint8Array.from(binary, char => char.charCodeAt(0));
151
+ return new globalThis.TextDecoder('utf-8').decode(bytes);
152
+ }
153
+
154
+ return binary;
155
+ }
156
+ } catch (_) {
157
+ // final fallback below
158
+ }
159
+
160
+ return String(value);
161
+ };
162
+
163
+ const getStoredSession = () => {
164
+ try {
165
+ if (typeof localStorage === 'undefined') {
166
+ return {};
167
+ }
168
+ return JSON.parse(localStorage.getItem('session') || '{}');
169
+ } catch (_) {
170
+ return {};
171
+ }
172
+ };
173
+
174
+ const toPeopleIri = value => {
175
+ if (!value) return null;
176
+
177
+ if (typeof value === 'string' || typeof value === 'number') {
178
+ return toIri(value, 'people');
179
+ }
180
+
181
+ return (
182
+ toIri(value?.people, 'people') ||
183
+ toIri(value?.person, 'people') ||
184
+ toIri(value?.peopleId, 'people') ||
185
+ toIri(value?.people_id, 'people') ||
186
+ toIri(value?.personId, 'people') ||
187
+ toIri(value?.person_id, 'people') ||
188
+ (typeof value?.['@id'] === 'string' && value['@id'].includes('/people/') ? value['@id'] : null) ||
189
+ (value?.peopleType ? toIri(value?.id, 'people') : null)
190
+ );
191
+ };
192
+
193
+ const resolveDefaultSignerIri = (signers, preferredSignerIri) => {
194
+ const safeSigners = Array.isArray(signers) ? signers : [];
195
+ if (safeSigners.length === 0) return null;
196
+
197
+ if (preferredSignerIri) {
198
+ const preferredMatch = safeSigners.find(person => toIri(person, 'people') === preferredSignerIri);
199
+ if (preferredMatch) {
200
+ return toIri(preferredMatch, 'people');
201
+ }
202
+ }
203
+
204
+ return toIri(safeSigners[0], 'people');
205
+ };
206
+
207
+ const FieldLabel = ({ label, required = false, suffix = '' }) => (
208
+ <Text style={styles.fieldLabel}>
209
+ {label}
210
+ {suffix ? ` ${suffix}` : ''}
211
+ {required ? <Text style={styles.fieldRequiredMark}> *</Text> : null}
212
+ </Text>
213
+ );
214
+
215
+ const buildStarterTemplate = context => {
216
+ if (context === 'contract') {
217
+ return `<!DOCTYPE html>
218
+ <html lang="pt-BR">
219
+ <head>
220
+ <meta charset="UTF-8" />
221
+ <style>
222
+ body { font-family: Arial, sans-serif; color: #0f172a; line-height: 1.6; padding: 40px; }
223
+ h1, h2 { margin-bottom: 8px; }
224
+ .muted { color: #64748b; }
225
+ .signature-line { margin-top: 48px; padding-top: 24px; border-top: 1px solid #94a3b8; width: 260px; }
226
+ </style>
227
+ </head>
228
+ <body>
229
+ <h1>{{ contract.contractModel.model|default('Contrato') }}</h1>
230
+ <p class="muted">Documento #{{ contract.id|default('') }}</p>
231
+
232
+ <p>
233
+ Contratante:
234
+ <strong>{{ contract.provider.alias|default(contract.provider.name|default('')) }}</strong>
235
+ </p>
236
+ <p>
237
+ Cliente:
238
+ <strong>{{ contract.client.alias|default(contract.client.name|default('')) }}</strong>
239
+ </p>
240
+ <p>Inicio: {{ contract.startDate|date('d/m/Y') }}</p>
241
+
242
+ <h2>Objeto</h2>
243
+ <p>Descreva aqui as clausulas e regras deste contrato.</p>
244
+
245
+ <div class="signature-line">Assinatura</div>
246
+ </body>
247
+ </html>`;
248
+ }
249
+
250
+ if (context === 'email') {
251
+ return `<!DOCTYPE html>
252
+ <html lang="pt-BR">
253
+ <head>
254
+ <meta charset="UTF-8" />
255
+ </head>
256
+ <body style="margin:0; padding:24px; background:#f8fafc; font-family:Arial, sans-serif; color:#0f172a;">
257
+ <table width="100%" cellpadding="0" cellspacing="0" style="max-width:640px; margin:0 auto; background:#ffffff; border-radius:20px; padding:32px;">
258
+ <tr>
259
+ <td>
260
+ <p style="margin:0 0 8px; color:#64748b;">{{ recipientName|default('Cliente') }}</p>
261
+ <h1 style="margin:0 0 16px; font-size:28px;">{{ subject|default('Mensagem importante') }}</h1>
262
+ <p style="margin:0 0 24px; line-height:1.7;">{{ message|default('Escreva aqui o corpo do e-mail.') }}</p>
263
+
264
+ {% if ctaUrl %}
265
+ <p style="margin:0 0 24px;">
266
+ <a href="{{ ctaUrl }}" style="display:inline-block; padding:14px 22px; border-radius:999px; background:#0f172a; color:#ffffff; text-decoration:none;">
267
+ {{ ctaLabel|default('Abrir link') }}
268
+ </a>
269
+ </p>
270
+ {% endif %}
271
+
272
+ <p style="margin:32px 0 0; color:#64748b;">{{ signature|default('Equipe Controle Online') }}</p>
273
+ </td>
274
+ </tr>
275
+ </table>
276
+ </body>
277
+ </html>`;
278
+ }
279
+
280
+ if (context === 'menu') {
281
+ return `<!DOCTYPE html>
282
+ <html lang="pt-BR">
283
+ <head>
284
+ <meta charset="UTF-8" />
285
+ <style>
286
+ @page { margin: 20px 16px; }
287
+ body { margin: 0; font-family: DejaVu Sans, Arial, sans-serif; font-size: 11px; color: #1f2937; background-color: #ffffff; }
288
+ table { border-collapse: collapse; }
289
+ .full { width: 100%; }
290
+ .header-box { width: 100%; border: 1px solid #d7dde5; margin-bottom: 12px; }
291
+ .header-copy { width: 66%; vertical-align: top; padding: 12px; }
292
+ .header-media { width: 34%; vertical-align: top; padding: 12px 12px 12px 0; }
293
+ .eyebrow { font-size: 9px; font-weight: bold; color: #9a3412; text-transform: uppercase; }
294
+ .title { font-size: 20px; font-weight: bold; color: #111827; padding-top: 4px; }
295
+ .subtitle { font-size: 10px; color: #6b7280; line-height: 1.5; padding-top: 6px; }
296
+ .meta-table { width: 100%; padding-top: 8px; }
297
+ .meta-cell { width: 33.33%; border: 1px solid #e5e7eb; background-color: #f8fafc; padding: 6px; text-align: center; font-size: 9px; color: #475569; }
298
+ .hero-frame { border: 1px solid #d7dde5; text-align: center; }
299
+ .hero-frame img { width: 100%; }
300
+ .hero-placeholder { padding: 28px 10px; font-size: 12px; font-weight: bold; color: #64748b; }
301
+ .columns-table { width: 100%; }
302
+ .column-left { width: 50%; vertical-align: top; padding-right: 6px; }
303
+ .column-right { width: 50%; vertical-align: top; padding-left: 6px; }
304
+ .category-box { width: 100%; border: 1px solid #d7dde5; margin-bottom: 10px; page-break-inside: avoid; }
305
+ .category-head { background-color: #f8fafc; border-bottom: 1px solid #e5e7eb; }
306
+ .category-head td { padding: 8px 10px; }
307
+ .category-index { width: 36px; font-size: 9px; font-weight: bold; color: #9a3412; text-align: center; }
308
+ .category-title { font-size: 14px; font-weight: bold; color: #111827; }
309
+ .category-description { padding: 8px 10px 0; font-size: 10px; color: #6b7280; line-height: 1.45; }
310
+ .category-image { padding: 8px 10px 0; text-align: center; }
311
+ .category-image img { width: 100%; }
312
+ .product-wrap { padding: 8px 10px 2px; }
313
+ .product-box { width: 100%; border: 1px solid #e5e7eb; margin-bottom: 8px; page-break-inside: avoid; }
314
+ .product-head td { padding: 7px 8px; background-color: #ffffff; }
315
+ .product-name { font-size: 11px; font-weight: bold; color: #111827; }
316
+ .product-price { width: 80px; text-align: right; font-size: 10px; font-weight: bold; color: #9a3412; }
317
+ .product-description-row td { padding: 0 8px 7px; font-size: 9px; color: #4b5563; line-height: 1.45; }
318
+ .group-row td { border-top: 1px solid #e5e7eb; padding: 6px 8px; }
319
+ .group-name { font-size: 9px; font-weight: bold; color: #1f2937; text-transform: uppercase; }
320
+ .group-meta { font-size: 9px; color: #6b7280; padding-top: 2px; }
321
+ .group-items { font-size: 9px; color: #334155; line-height: 1.5; padding-top: 4px; }
322
+ .footer { padding-top: 6px; text-align: center; font-size: 9px; color: #94a3b8; }
323
+ .empty-box { border: 1px solid #d7dde5; padding: 16px; font-size: 11px; color: #64748b; text-align: center; }
324
+ </style>
325
+ </head>
326
+ <body>
327
+ <table class="header-box">
328
+ <tr>
329
+ <td class="header-copy">
330
+ <div class="eyebrow">{{ menuModelName|default('Cardapio') }}</div>
331
+ <div class="title">{{ companyName|default(menuModelName|default('Cardapio')) }}</div>
332
+ <div class="subtitle">
333
+ Cardapio em PDF com layout simplificado para manter consistencia no renderizador.
334
+ </div>
335
+ <table class="meta-table">
336
+ <tr>
337
+ <td class="meta-cell">{{ categoryCount }} categoria(s)</td>
338
+ <td class="meta-cell">{{ productCount }} item(ns)</td>
339
+ <td class="meta-cell">{{ generatedAt|date('d/m/Y H:i') }}</td>
340
+ </tr>
341
+ </table>
342
+ </td>
343
+ <td class="header-media">
344
+ <table class="hero-frame full">
345
+ <tr>
346
+ <td>
347
+ {% if heroImage %}
348
+ <img src="{{ heroImage }}" alt="{{ companyName|default('Cardapio') }}">
349
+ {% else %}
350
+ <div class="hero-placeholder">{{ companyName|default('Cardapio') }}</div>
351
+ {% endif %}
352
+ </td>
353
+ </tr>
354
+ </table>
355
+ </td>
356
+ </tr>
357
+ </table>
358
+
359
+ {% if categoryCount == 0 %}
360
+ <div class="empty-box">Nenhum produto ativo e visivel foi encontrado para gerar o cardapio.</div>
361
+ {% else %}
362
+ <table class="columns-table">
363
+ <tr>
364
+ {% for column in columns %}
365
+ <td class="{{ loop.first ? 'column-left' : 'column-right' }}">
366
+ {% for category in column %}
367
+ <table class="category-box">
368
+ <tr class="category-head">
369
+ <td class="category-index">{{ category.position }}</td>
370
+ <td class="category-title">{{ category.name }}</td>
371
+ </tr>
372
+ <tr>
373
+ <td colspan="2">
374
+ {% if category.description %}
375
+ <div class="category-description">{{ category.description }}</div>
376
+ {% endif %}
377
+
378
+ {% if category.image %}
379
+ <div class="category-image">
380
+ <img src="{{ category.image }}" alt="{{ category.name }}">
381
+ </div>
382
+ {% endif %}
383
+
384
+ <div class="product-wrap">
385
+ {% for product in category.products %}
386
+ <table class="product-box">
387
+ <tr class="product-head">
388
+ <td class="product-name">{{ product.name }}</td>
389
+ <td class="product-price">
390
+ {% if product.priceLabel %}
391
+ {{ product.priceLabel }}
392
+ {% endif %}
393
+ </td>
394
+ </tr>
395
+
396
+ {% if product.description %}
397
+ <tr class="product-description-row">
398
+ <td colspan="2">{{ product.description }}</td>
399
+ </tr>
400
+ {% endif %}
401
+
402
+ {% for group in product.groups %}
403
+ <tr class="group-row">
404
+ <td colspan="2">
405
+ <div class="group-name">{{ group.name }}</div>
406
+ {% if group.meta %}
407
+ <div class="group-meta">{{ group.meta }}</div>
408
+ {% endif %}
409
+ <div class="group-items">
410
+ {% for item in group.items %}
411
+ {{ item.name }}{% if item.priceLabel %} {{ item.priceLabel }}{% endif %}{% if not loop.last %}<br>{% endif %}
412
+ {% endfor %}
413
+ </div>
414
+ </td>
415
+ </tr>
416
+ {% endfor %}
417
+ </table>
418
+ {% endfor %}
419
+ </div>
420
+ </td>
421
+ </tr>
422
+ </table>
423
+ {% endfor %}
424
+ </td>
425
+ {% endfor %}
426
+ </tr>
427
+ </table>
428
+ {% endif %}
429
+
430
+ <div class="footer">Arquivo gerado automaticamente pelo modulo de produtos.</div>
431
+ </body>
432
+ </html>`;
433
+ }
434
+
435
+ return `<!DOCTYPE html>
436
+ <html lang="pt-BR">
437
+ <head>
438
+ <meta charset="UTF-8" />
439
+ <style>
440
+ body { font-family: Arial, sans-serif; color: #0f172a; line-height: 1.6; padding: 40px; }
441
+ h1, h2 { margin-bottom: 8px; }
442
+ .muted { color: #64748b; }
443
+ </style>
444
+ </head>
445
+ <body>
446
+ <h1>{{ contract.contractModel.model|default('Proposta comercial') }}</h1>
447
+ <p class="muted">Documento #{{ contract.id|default('') }}</p>
448
+
449
+ <p>
450
+ Cliente:
451
+ <strong>{{ contract.client.alias|default(contract.client.name|default('')) }}</strong>
452
+ </p>
453
+ <p>
454
+ Responsavel:
455
+ <strong>{{ contract.provider.alias|default(contract.provider.name|default('')) }}</strong>
456
+ </p>
457
+
458
+ <h2>Escopo</h2>
459
+ <p>Descreva aqui os entregaveis, prazos, valores e observacoes da proposta.</p>
460
+ </body>
461
+ </html>`;
462
+ };
463
+
464
+ const buildDraftState = (context, peopleIri, overrides = {}) => {
465
+ const safeContext = CONTEXT_OPTIONS.some(option => option.value === context)
466
+ ? context
467
+ : 'proposal';
468
+ const defaultName = {
469
+ proposal: 'Nova proposta',
470
+ contract: 'Novo contrato',
471
+ email: 'Novo email',
472
+ menu: 'Novo cardapio',
473
+ }[safeContext];
474
+
475
+ const html = overrides.html ?? buildStarterTemplate(safeContext);
476
+ const modelName = overrides.model ?? defaultName;
477
+
478
+ return {
479
+ id: overrides.id || null,
480
+ model: modelName,
481
+ context: safeContext,
482
+ fileId: overrides.fileId || null,
483
+ html,
484
+ category: overrides.category || null,
485
+ signer: overrides.signer || null,
486
+ people: overrides.people || peopleIri || null,
487
+ fileName: overrides.fileName || buildFileName(modelName, safeContext),
488
+ fileContext: overrides.fileContext || safeContext,
489
+ fileType: overrides.fileType || 'text',
490
+ extension: overrides.extension || 'html',
491
+ };
492
+ };
493
+
494
+ const countByContext = items =>
495
+ CONTEXT_OPTIONS.reduce(
496
+ (acc, option) => ({
497
+ ...acc,
498
+ [option.value]: items.filter(item => item?.context === option.value).length,
499
+ }),
500
+ {},
501
+ );
502
+
503
+ export default function ModelTemplatesPage({ route, navigation }) {
504
+ const authStore = useStore('auth');
505
+ const peopleStore = useStore('people');
506
+ const themeStore = useStore('theme');
507
+ const modelsStore = useStore('models');
508
+ const fileStore = useStore('file');
509
+ const { user: authUser } = authStore.getters;
510
+ const { currentCompany } = peopleStore.getters;
511
+ const { colors: themeColors } = themeStore.getters;
512
+ const modelsActions = modelsStore.actions;
513
+ const fileActions = fileStore.actions;
514
+ const { items: modelItems = [] } = modelsStore.getters;
515
+ const { showError, showSuccess } = useToastMessage();
516
+ const editorRef = useRef(null);
517
+ const metadataRequestRef = useRef(0);
518
+ const { width } = useWindowDimensions();
519
+
520
+ const brandColors = useMemo(
521
+ () =>
522
+ resolveThemePalette(
523
+ {
524
+ ...themeColors,
525
+ ...(currentCompany?.theme?.colors || {}),
526
+ },
527
+ colors,
528
+ ),
529
+ [themeColors, currentCompany?.id],
530
+ );
531
+
532
+ const isDesktop = width >= 1100;
533
+ const peopleIri = useMemo(
534
+ () => (currentCompany?.id ? `/people/${normalizeId(currentCompany.id)}` : ''),
535
+ [currentCompany?.id],
536
+ );
537
+ const preferredSignerIri = useMemo(() => {
538
+ const session = getStoredSession();
539
+ return toPeopleIri(authUser) || toPeopleIri(session) || null;
540
+ }, [authUser]);
541
+
542
+ const initialContext = useMemo(() => {
543
+ const requested = route?.params?.presetContext || route?.params?.filterContext;
544
+ return CONTEXT_OPTIONS.some(option => option.value === requested)
545
+ ? requested
546
+ : 'proposal';
547
+ }, [route?.params?.filterContext, route?.params?.presetContext]);
548
+
549
+ const [loading, setLoading] = useState(true);
550
+ const [loadingFile, setLoadingFile] = useState(false);
551
+ const [saving, setSaving] = useState(false);
552
+ const [loadingMetadata, setLoadingMetadata] = useState(false);
553
+ const [search, setSearch] = useState('');
554
+ const [filterContext, setFilterContext] = useState(
555
+ route?.params?.filterContext && FILTER_OPTIONS.some(option => option.value === route.params.filterContext)
556
+ ? route.params.filterContext
557
+ : 'all',
558
+ );
559
+ const [selectedId, setSelectedId] = useState(null);
560
+ const [draft, setDraft] = useState(buildDraftState(initialContext, peopleIri));
561
+ const [isDirty, setIsDirty] = useState(false);
562
+ const [isCreating, setIsCreating] = useState(false);
563
+ const [viewMode, setViewMode] = useState('editor');
564
+ const [editorSelection, setEditorSelection] = useState({ start: 0, end: 0 });
565
+ const [signers, setSigners] = useState([]);
566
+ const [categories, setCategories] = useState([]);
567
+
568
+ const filteredModels = useMemo(() => {
569
+ const term = String(search || '').trim().toLowerCase();
570
+ if (!term) return modelItems;
571
+
572
+ return modelItems.filter(item => {
573
+ const label = String(item?.model || '').toLowerCase();
574
+ const contextLabel = String(getContextMeta(item?.context)?.label || '').toLowerCase();
575
+ return label.includes(term) || contextLabel.includes(term);
576
+ });
577
+ }, [modelItems, search]);
578
+
579
+ const counters = useMemo(() => countByContext(modelItems), [modelItems]);
580
+ const activeContextMeta = useMemo(() => getContextMeta(draft.context), [draft.context]);
581
+ const activeSnippets = useMemo(
582
+ () => [...COMMON_SNIPPETS, ...(CONTEXT_SNIPPETS[draft.context] || [])],
583
+ [draft.context],
584
+ );
585
+
586
+ const focusEditor = useCallback(() => {
587
+ const focus = () => editorRef.current?.focus?.();
588
+
589
+ if (typeof globalThis?.requestAnimationFrame === 'function') {
590
+ globalThis.requestAnimationFrame(focus);
591
+ return;
592
+ }
593
+
594
+ globalThis?.setTimeout?.(focus, 0);
595
+ }, []);
596
+
597
+ const confirmDiscardChanges = useCallback(async () => {
598
+ if (!isDirty) return true;
599
+
600
+ const message = 'Existem alteracoes nao salvas. Deseja descartar e continuar?';
601
+ const confirmFn = globalThis?.window?.confirm || globalThis?.confirm;
602
+
603
+ if (Platform.OS === 'web' && typeof confirmFn === 'function') {
604
+ return confirmFn(message);
605
+ }
606
+
607
+ return new Promise(resolve => {
608
+ Alert.alert(
609
+ 'Descartar alteracoes?',
610
+ message,
611
+ [
612
+ { text: 'Cancelar', style: 'cancel', onPress: () => resolve(false) },
613
+ { text: 'Descartar', style: 'destructive', onPress: () => resolve(true) },
614
+ ],
615
+ { cancelable: true },
616
+ );
617
+ });
618
+ }, [isDirty]);
619
+
620
+ const loadModels = useCallback(async () => {
621
+ if (!peopleIri) {
622
+ setLoading(false);
623
+ return;
624
+ }
625
+
626
+ setLoading(true);
627
+ try {
628
+ const params = {
629
+ people: peopleIri,
630
+ };
631
+
632
+ if (filterContext !== 'all') params.context = filterContext;
633
+ await modelsActions.getItems(params);
634
+ } catch (error) {
635
+ showError(formatApiError(error));
636
+ } finally {
637
+ setLoading(false);
638
+ }
639
+ }, [filterContext, modelsActions, peopleIri, showError]);
640
+
641
+ const loadMetadata = useCallback(async context => {
642
+ if (!peopleIri) {
643
+ setSigners([]);
644
+ setCategories([]);
645
+ return { signers: [], categories: [] };
646
+ }
647
+
648
+ const requestId = metadataRequestRef.current + 1;
649
+ metadataRequestRef.current = requestId;
650
+ setSigners([]);
651
+ setCategories([]);
652
+ setLoadingMetadata(true);
653
+ try {
654
+ const categoryContext = getCategoryContextForDocument(context);
655
+ const [signersResponse, categoriesResponse] = await Promise.all([
656
+ api.fetch('/people', {
657
+ params: {
658
+ 'link.company': peopleIri,
659
+ 'link.linkType': 'employee',
660
+ peopleType: 'F',
661
+ },
662
+ }).catch(() => null),
663
+ api.fetch('/categories', {
664
+ params: {
665
+ company: peopleIri,
666
+ context: categoryContext,
667
+ },
668
+ }).catch(() => null),
669
+ ]);
670
+
671
+ const nextSigners = Array.isArray(signersResponse?.member) ? signersResponse.member : [];
672
+ const nextCategories = Array.isArray(categoriesResponse?.member)
673
+ ? categoriesResponse.member
674
+ : [];
675
+
676
+ if (metadataRequestRef.current === requestId) {
677
+ setSigners(nextSigners);
678
+ setCategories(nextCategories);
679
+ }
680
+ return { signers: nextSigners, categories: nextCategories };
681
+ } finally {
682
+ if (metadataRequestRef.current === requestId) {
683
+ setLoadingMetadata(false);
684
+ }
685
+ }
686
+ }, [peopleIri]);
687
+
688
+ const ensureContextCategory = useCallback(
689
+ async (context, preferredCategoryIri, availableCategories = []) => {
690
+ if (preferredCategoryIri) return preferredCategoryIri;
691
+
692
+ const safeCategories = Array.isArray(availableCategories) ? availableCategories : [];
693
+ const firstCategoryIri = toIri(safeCategories[0], 'categories');
694
+ if (firstCategoryIri) return firstCategoryIri;
695
+
696
+ if (!peopleIri) return null;
697
+
698
+ const contextMeta = getContextMeta(context);
699
+ const categoryContext = getCategoryContextForDocument(context);
700
+ const createdCategory = await api.post('/categories', {
701
+ name: DEFAULT_CATEGORY_NAMES[context] || `Modelos de ${contextMeta.label.toLowerCase()}`,
702
+ context: categoryContext,
703
+ company: peopleIri,
704
+ color: contextMeta.color,
705
+ icon: contextMeta.icon,
706
+ });
707
+
708
+ if (createdCategory) {
709
+ setCategories(prev => {
710
+ const safePrev = Array.isArray(prev) ? prev : [];
711
+ const createdId = normalizeId(createdCategory?.id || createdCategory?.['@id']);
712
+ if (!createdId) return [createdCategory, ...safePrev];
713
+ if (safePrev.some(item => normalizeId(item?.id || item?.['@id']) === createdId)) {
714
+ return safePrev;
715
+ }
716
+ return [createdCategory, ...safePrev];
717
+ });
718
+ }
719
+
720
+ return toIri(createdCategory, 'categories');
721
+ },
722
+ [peopleIri],
723
+ );
724
+
725
+ const hydrateDraftFromModel = useCallback(
726
+ async (modelRecord, options = {}) => {
727
+ if (!modelRecord) return;
728
+
729
+ const skipConfirm = Boolean(options.skipConfirm);
730
+ const modelId = normalizeId(modelRecord?.id || modelRecord?.['@id']);
731
+
732
+ if (selectedId === modelId && !isCreating && !skipConfirm) return;
733
+
734
+ if (!skipConfirm) {
735
+ const canProceed = await confirmDiscardChanges();
736
+ if (!canProceed) return;
737
+ }
738
+
739
+ setLoadingFile(true);
740
+ try {
741
+ const fileId = normalizeId(modelRecord?.file?.id || modelRecord?.file?.['@id'] || modelRecord?.file);
742
+ let fileData = null;
743
+ let html = '';
744
+
745
+ if (fileId) {
746
+ fileData = await api.fetch(`/files/${fileId}`);
747
+ html = decodeBase64Text(fileData?.content);
748
+ }
749
+
750
+ const nextDraft = buildDraftState(modelRecord?.context, peopleIri, {
751
+ id: modelId,
752
+ model: String(modelRecord?.model || ''),
753
+ fileId,
754
+ html,
755
+ category: toIri(modelRecord?.category, 'categories'),
756
+ signer: toIri(modelRecord?.signer, 'people'),
757
+ people: toIri(modelRecord?.people, 'people') || peopleIri,
758
+ fileName: fileData?.fileName || modelRecord?.file?.fileName || buildFileName(modelRecord?.model, modelRecord?.context),
759
+ fileContext: fileData?.context || modelRecord?.context,
760
+ fileType: fileData?.fileType || 'text',
761
+ extension: fileData?.extension || 'html',
762
+ });
763
+
764
+ setSelectedId(modelId);
765
+ setDraft(nextDraft);
766
+ setIsDirty(false);
767
+ setIsCreating(false);
768
+ setViewMode('editor');
769
+ setEditorSelection({ start: nextDraft.html.length, end: nextDraft.html.length });
770
+ } catch (error) {
771
+ showError(formatApiError(error));
772
+ } finally {
773
+ setLoadingFile(false);
774
+ }
775
+ },
776
+ [confirmDiscardChanges, isCreating, peopleIri, selectedId, showError],
777
+ );
778
+
779
+ const startNewDraft = useCallback(
780
+ async (context, options = {}) => {
781
+ const skipConfirm = Boolean(options.skipConfirm);
782
+
783
+ if (!skipConfirm) {
784
+ const canProceed = await confirmDiscardChanges();
785
+ if (!canProceed) return;
786
+ }
787
+
788
+ const nextDraft = buildDraftState(context, peopleIri);
789
+ setDraft(nextDraft);
790
+ setSelectedId(null);
791
+ setIsDirty(Boolean(options.markDirty ?? true));
792
+ setIsCreating(true);
793
+ setViewMode('editor');
794
+ setEditorSelection({ start: nextDraft.html.length, end: nextDraft.html.length });
795
+ focusEditor();
796
+ },
797
+ [confirmDiscardChanges, focusEditor, peopleIri],
798
+ );
799
+
800
+ const updateDraft = useCallback(updater => {
801
+ setDraft(prev => {
802
+ const next =
803
+ typeof updater === 'function'
804
+ ? updater(prev)
805
+ : {
806
+ ...prev,
807
+ ...updater,
808
+ };
809
+
810
+ return {
811
+ ...next,
812
+ fileName: buildFileName(next.model, next.context),
813
+ };
814
+ });
815
+ setIsDirty(true);
816
+ }, []);
817
+
818
+ const insertSnippet = useCallback(
819
+ snippet => {
820
+ updateDraft(prev => {
821
+ const start = editorSelection?.start ?? prev.html.length;
822
+ const end = editorSelection?.end ?? start;
823
+ const nextHtml = `${prev.html.slice(0, start)}${snippet}${prev.html.slice(end)}`;
824
+ const nextCursor = start + snippet.length;
825
+ setEditorSelection({ start: nextCursor, end: nextCursor });
826
+
827
+ return {
828
+ ...prev,
829
+ html: nextHtml,
830
+ };
831
+ });
832
+
833
+ focusEditor();
834
+ },
835
+ [editorSelection?.end, editorSelection?.start, focusEditor, updateDraft],
836
+ );
837
+
838
+ const handleSave = useCallback(async () => {
839
+ const name = String(draft.model || '').trim();
840
+ const context = String(draft.context || '').trim();
841
+ const html = String(draft.html || '');
842
+
843
+ if (!peopleIri) {
844
+ showError('Selecione uma empresa para editar os modelos.');
845
+ return;
846
+ }
847
+
848
+ if (!name) {
849
+ showError('Informe o nome do modelo.');
850
+ return;
851
+ }
852
+
853
+ if (!CONTEXT_OPTIONS.some(option => option.value === context)) {
854
+ showError('Selecione um tipo de modelo valido.');
855
+ return;
856
+ }
857
+
858
+ if (!html.trim()) {
859
+ showError('Informe o HTML/Twig do modelo.');
860
+ return;
861
+ }
862
+
863
+ const metadata =
864
+ loadingMetadata || categories.length === 0 || signers.length === 0
865
+ ? await loadMetadata(context)
866
+ : { categories, signers };
867
+
868
+ const availableCategories = Array.isArray(metadata?.categories) ? metadata.categories : categories;
869
+ const availableSigners = Array.isArray(metadata?.signers) ? metadata.signers : signers;
870
+ const signerIri = draft.signer || resolveDefaultSignerIri(availableSigners, preferredSignerIri);
871
+ const categoryIri = await ensureContextCategory(context, draft.category, availableCategories);
872
+
873
+ if (!categoryIri) {
874
+ showError('Nao foi possivel definir a categoria do modelo. Verifique as categorias deste contexto.');
875
+ return;
876
+ }
877
+
878
+ if (!signerIri) {
879
+ showError('Cadastre ao menos um responsavel da empresa para assinar este modelo antes de salvar.');
880
+ return;
881
+ }
882
+
883
+ setSaving(true);
884
+ try {
885
+ const savedFile = await fileActions.save({
886
+ id: draft.fileId || undefined,
887
+ people: peopleIri,
888
+ context,
889
+ fileType: 'text',
890
+ fileName: buildFileName(name, context),
891
+ extension: 'html',
892
+ content: html,
893
+ });
894
+
895
+ const fileIri = toIri(savedFile, 'files');
896
+ const savedModel = await modelsActions.save({
897
+ id: draft.id || undefined,
898
+ model: name,
899
+ context,
900
+ people: peopleIri,
901
+ signer: signerIri,
902
+ category: categoryIri,
903
+ file: fileIri,
904
+ });
905
+
906
+ const nextDraft = buildDraftState(context, peopleIri, {
907
+ id: normalizeId(savedModel?.id || savedModel?.['@id']),
908
+ model: name,
909
+ fileId: normalizeId(savedFile?.id || savedFile?.['@id']),
910
+ html,
911
+ category: categoryIri,
912
+ signer: signerIri,
913
+ people: peopleIri,
914
+ fileName: savedFile?.fileName || buildFileName(name, context),
915
+ fileContext: savedFile?.context || context,
916
+ fileType: savedFile?.fileType || 'text',
917
+ extension: savedFile?.extension || 'html',
918
+ });
919
+
920
+ setDraft(nextDraft);
921
+ setSelectedId(nextDraft.id);
922
+ setIsDirty(false);
923
+ setIsCreating(false);
924
+ showSuccess(draft.id ? 'Modelo atualizado com sucesso.' : 'Modelo criado com sucesso.');
925
+
926
+ if (filterContext !== 'all' && filterContext !== context) {
927
+ setFilterContext(context);
928
+ } else {
929
+ await loadModels();
930
+ }
931
+ } catch (error) {
932
+ showError(formatApiError(error));
933
+ } finally {
934
+ setSaving(false);
935
+ }
936
+ }, [
937
+ categories,
938
+ draft,
939
+ ensureContextCategory,
940
+ fileActions,
941
+ filterContext,
942
+ loadMetadata,
943
+ loadModels,
944
+ loadingMetadata,
945
+ modelsActions,
946
+ peopleIri,
947
+ preferredSignerIri,
948
+ showError,
949
+ showSuccess,
950
+ signers,
951
+ ]);
952
+
953
+ const handleFilterChange = useCallback(
954
+ async nextContext => {
955
+ if (nextContext === filterContext) return;
956
+
957
+ const canProceed = await confirmDiscardChanges();
958
+ if (!canProceed) return;
959
+
960
+ setSelectedId(null);
961
+ setIsCreating(false);
962
+ setFilterContext(nextContext);
963
+ },
964
+ [confirmDiscardChanges, filterContext],
965
+ );
966
+
967
+ useFocusEffect(
968
+ useCallback(() => {
969
+ loadModels();
970
+ loadMetadata(draft.context);
971
+ }, [draft.context, loadMetadata, loadModels]),
972
+ );
973
+
974
+ useEffect(() => {
975
+ if (loading) return;
976
+ if (!peopleIri) return;
977
+
978
+ const visibleIds = new Set(modelItems.map(item => normalizeId(item?.id || item?.['@id'])));
979
+
980
+ if (selectedId && !visibleIds.has(selectedId) && !isCreating) {
981
+ setSelectedId(null);
982
+ }
983
+
984
+ if (isCreating) return;
985
+
986
+ if (!selectedId) {
987
+ if (modelItems.length > 0) {
988
+ hydrateDraftFromModel(modelItems[0], { skipConfirm: true });
989
+ } else {
990
+ const nextContext = filterContext !== 'all' ? filterContext : initialContext;
991
+ const nextDraft = buildDraftState(nextContext, peopleIri);
992
+ setDraft(nextDraft);
993
+ setIsDirty(false);
994
+ setIsCreating(true);
995
+ setViewMode('editor');
996
+ }
997
+ }
998
+ }, [
999
+ filterContext,
1000
+ hydrateDraftFromModel,
1001
+ initialContext,
1002
+ isCreating,
1003
+ loading,
1004
+ modelItems,
1005
+ peopleIri,
1006
+ selectedId,
1007
+ ]);
1008
+
1009
+ useEffect(() => {
1010
+ const actionKey = route?.params?.templateAction;
1011
+ if (!actionKey) return;
1012
+
1013
+ const requestedFilter = route?.params?.filterContext;
1014
+ if (requestedFilter && FILTER_OPTIONS.some(option => option.value === requestedFilter)) {
1015
+ setFilterContext(requestedFilter);
1016
+ }
1017
+
1018
+ if (route?.params?.startNew) {
1019
+ startNewDraft(route?.params?.presetContext || initialContext, {
1020
+ skipConfirm: true,
1021
+ markDirty: true,
1022
+ });
1023
+ }
1024
+ }, [
1025
+ initialContext,
1026
+ route?.params?.filterContext,
1027
+ route?.params?.presetContext,
1028
+ route?.params?.startNew,
1029
+ route?.params?.templateAction,
1030
+ startNewDraft,
1031
+ ]);
1032
+
1033
+ useEffect(() => {
1034
+ loadMetadata(draft.context);
1035
+ }, [draft.context, loadMetadata]);
1036
+
1037
+ useEffect(() => {
1038
+ const defaultCategoryIri = draft.category || toIri(categories[0], 'categories') || null;
1039
+ const defaultSignerIri = draft.signer || resolveDefaultSignerIri(signers, preferredSignerIri);
1040
+
1041
+ if (defaultCategoryIri === draft.category && defaultSignerIri === draft.signer) {
1042
+ return;
1043
+ }
1044
+
1045
+ setDraft(prev => ({
1046
+ ...prev,
1047
+ category: prev.category || defaultCategoryIri,
1048
+ signer: prev.signer || defaultSignerIri,
1049
+ }));
1050
+ }, [categories, draft.category, draft.signer, preferredSignerIri, signers]);
1051
+
1052
+ const renderSummary = () => (
1053
+ <View style={styles.summaryRow}>
1054
+ <View style={styles.summaryCard}>
1055
+ <Text style={styles.summaryLabel}>Modelos visiveis</Text>
1056
+ <Text style={styles.summaryValue}>{modelItems.length}</Text>
1057
+ </View>
1058
+ {CONTEXT_OPTIONS.map(option => (
1059
+ <View key={option.value} style={styles.summaryCard}>
1060
+ <Text style={styles.summaryLabel}>{option.label}</Text>
1061
+ <Text style={[styles.summaryValue, { color: option.color }]}>
1062
+ {counters[option.value] || 0}
1063
+ </Text>
1064
+ </View>
1065
+ ))}
1066
+ </View>
1067
+ );
1068
+
1069
+ const renderSidebar = () => (
1070
+ <View>
1071
+ <Text style={styles.panelTitle}>Biblioteca de modelos</Text>
1072
+ <Text style={styles.panelSub}>
1073
+ Edite HTML/Twig para proposal, contract, email e menu.
1074
+ </Text>
1075
+
1076
+ <TextInput
1077
+ value={search}
1078
+ onChangeText={setSearch}
1079
+ placeholder="Buscar modelo"
1080
+ placeholderTextColor="#94A3B8"
1081
+ style={styles.searchInput}
1082
+ />
1083
+
1084
+ <View style={styles.fieldBlock}>
1085
+ <Text style={styles.fieldLabel}>Filtro por tipo</Text>
1086
+ <View style={styles.pickerWrap}>
1087
+ <Picker
1088
+ selectedValue={filterContext}
1089
+ onValueChange={handleFilterChange}
1090
+ mode={Platform.OS === 'android' ? 'dropdown' : undefined}
1091
+ >
1092
+ {FILTER_OPTIONS.map(option => (
1093
+ <Picker.Item key={option.value} label={option.label} value={option.value} />
1094
+ ))}
1095
+ </Picker>
1096
+ </View>
1097
+ </View>
1098
+
1099
+ <View style={styles.quickActionsGrid}>
1100
+ {CONTEXT_OPTIONS.map(option => (
1101
+ <TouchableOpacity
1102
+ key={option.value}
1103
+ style={styles.quickActionCard}
1104
+ activeOpacity={0.88}
1105
+ onPress={() => startNewDraft(option.value)}
1106
+ >
1107
+ <View style={[styles.quickActionIcon, { backgroundColor: withOpacity(option.color, 0.12) }]}>
1108
+ <Icon name={option.icon} size={18} color={option.color} />
1109
+ </View>
1110
+ <Text style={styles.quickActionLabel}>{option.newLabel}</Text>
1111
+ </TouchableOpacity>
1112
+ ))}
1113
+ </View>
1114
+
1115
+ <View style={styles.listHeader}>
1116
+ <Text style={styles.listTitle}>Modelos</Text>
1117
+ {loading && <ActivityIndicator size="small" color={brandColors.primary} />}
1118
+ </View>
1119
+
1120
+ {filteredModels.length === 0 && !loading ? (
1121
+ <View style={styles.emptyBox}>
1122
+ <Icon name="file-text" size={28} color="#CBD5E1" style={inlineStyle_1012_59} />
1123
+ <Text style={styles.emptyTitle}>Nenhum modelo encontrado</Text>
1124
+ <Text style={styles.emptySub}>
1125
+ Crie um novo modelo a partir de um dos tipos disponiveis.
1126
+ </Text>
1127
+ </View>
1128
+ ) : (
1129
+ filteredModels.map(item => {
1130
+ const itemId = normalizeId(item?.id || item?.['@id']);
1131
+ const isActive = selectedId === itemId && !isCreating;
1132
+ const meta = getContextMeta(item?.context);
1133
+
1134
+ return (
1135
+ <TouchableOpacity
1136
+ key={itemId || item?.model}
1137
+ style={[
1138
+ styles.modelCard,
1139
+ isActive && {
1140
+ borderColor: meta.color,
1141
+ backgroundColor: withOpacity(meta.color, 0.06),
1142
+ },
1143
+ ]}
1144
+ activeOpacity={0.88}
1145
+ onPress={() => hydrateDraftFromModel(item)}
1146
+ >
1147
+ <View style={styles.modelCardHeader}>
1148
+ <Text style={styles.modelCardTitle} numberOfLines={2}>
1149
+ {item?.model || 'Modelo sem nome'}
1150
+ </Text>
1151
+ <View
1152
+ style={[
1153
+ styles.contextBadge,
1154
+ {
1155
+ backgroundColor: withOpacity(meta.color, 0.12),
1156
+ borderColor: withOpacity(meta.color, 0.28),
1157
+ },
1158
+ ]}
1159
+ >
1160
+ <Text style={[styles.contextBadgeText, { color: meta.color }]}>
1161
+ {meta.label}
1162
+ </Text>
1163
+ </View>
1164
+ </View>
1165
+ <Text style={styles.modelMeta}>
1166
+ Arquivo #{normalizeId(item?.file?.id || item?.file?.['@id'] || item?.file) || 'novo'}
1167
+ </Text>
1168
+ </TouchableOpacity>
1169
+ );
1170
+ })
1171
+ )}
1172
+ </View>
1173
+ );
1174
+
1175
+ const renderEditor = () => (
1176
+ <View>
1177
+ <View style={styles.editorHeader}>
1178
+ <View style={inlineStyle_1068_14}>
1179
+ <Text style={styles.panelTitle}>
1180
+ {draft.id ? 'Editar modelo' : 'Novo modelo'}
1181
+ </Text>
1182
+ <Text style={styles.panelSub}>
1183
+ {CONTEXT_HELP[draft.context]}
1184
+ </Text>
1185
+ <Text style={styles.requiredHint}>* Campos obrigatorios</Text>
1186
+ </View>
1187
+
1188
+ <TouchableOpacity
1189
+ style={[
1190
+ styles.saveButton,
1191
+ { backgroundColor: brandColors.primary, opacity: saving ? 0.7 : 1 },
1192
+ ]}
1193
+ disabled={saving}
1194
+ activeOpacity={0.88}
1195
+ onPress={handleSave}
1196
+ >
1197
+ {saving ? (
1198
+ <ActivityIndicator size="small" color="#fff" />
1199
+ ) : (
1200
+ <>
1201
+ <Icon name="save" size={16} color="#fff" />
1202
+ <Text style={styles.saveButtonText}>Salvar</Text>
1203
+ </>
1204
+ )}
1205
+ </TouchableOpacity>
1206
+ </View>
1207
+
1208
+ <View style={styles.statusRow}>
1209
+ <View
1210
+ style={[
1211
+ styles.statusBadge,
1212
+ {
1213
+ backgroundColor: withOpacity(activeContextMeta.color, 0.1),
1214
+ borderColor: withOpacity(activeContextMeta.color, 0.22),
1215
+ },
1216
+ ]}
1217
+ >
1218
+ <Icon name={activeContextMeta.icon} size={14} color={activeContextMeta.color} />
1219
+ <Text style={[styles.statusBadgeText, { color: activeContextMeta.color }]}>
1220
+ {activeContextMeta.label}
1221
+ </Text>
1222
+ </View>
1223
+
1224
+ <View style={styles.statusBadge}>
1225
+ <Icon name="file" size={14} color="#64748B" />
1226
+ <Text style={styles.statusBadgeText}>{draft.fileName}</Text>
1227
+ </View>
1228
+
1229
+ {isDirty && (
1230
+ <View style={[styles.statusBadge, { borderColor: '#e67e22', backgroundColor: withOpacity('#e67e22', 0.08) }]}>
1231
+ <Icon name="alert-circle" size={14} color="#e67e22" />
1232
+ <Text style={[styles.statusBadgeText, { color: '#B45309' }]}>Alteracoes pendentes</Text>
1233
+ </View>
1234
+ )}
1235
+ </View>
1236
+
1237
+ <View style={styles.formGrid}>
1238
+ <View style={[styles.fieldBlock, styles.formField]}>
1239
+ <FieldLabel label="Nome do modelo" required />
1240
+ <TextInput
1241
+ value={draft.model}
1242
+ onChangeText={value => updateDraft({ model: value })}
1243
+ placeholder="Ex.: Contrato padrao"
1244
+ placeholderTextColor="#94A3B8"
1245
+ style={styles.textInput}
1246
+ />
1247
+ </View>
1248
+
1249
+ <View style={[styles.fieldBlock, styles.formField]}>
1250
+ <FieldLabel label="Tipo" required />
1251
+ <View style={styles.pickerWrap}>
1252
+ <Picker
1253
+ selectedValue={draft.context}
1254
+ onValueChange={value => updateDraft(prev => {
1255
+ const shouldReplaceTemplate =
1256
+ !prev.id &&
1257
+ (prev.html === buildStarterTemplate(prev.context) || !String(prev.html || '').trim());
1258
+
1259
+ return {
1260
+ ...prev,
1261
+ context: value,
1262
+ category: null,
1263
+ html: shouldReplaceTemplate ? buildStarterTemplate(value) : prev.html,
1264
+ };
1265
+ })}
1266
+ mode={Platform.OS === 'android' ? 'dropdown' : undefined}
1267
+ >
1268
+ {CONTEXT_OPTIONS.map(option => (
1269
+ <Picker.Item key={option.value} label={option.label} value={option.value} />
1270
+ ))}
1271
+ </Picker>
1272
+ </View>
1273
+ </View>
1274
+
1275
+ <View style={[styles.fieldBlock, styles.formField]}>
1276
+ <View style={styles.fieldLabelRow}>
1277
+ <FieldLabel label="Categoria" suffix={loadingMetadata ? '(carregando...)' : ''} required />
1278
+ <TouchableOpacity
1279
+ style={styles.inlineAddButton}
1280
+ activeOpacity={0.88}
1281
+ onPress={() =>
1282
+ navigation.navigate('ManagerCategoriesPage', {
1283
+ categoryAction: Date.now(),
1284
+ startNew: true,
1285
+ lockContext: true,
1286
+ presetContext: getCategoryContextForDocument(draft.context),
1287
+ })
1288
+ }>
1289
+ <Icon name="plus" size={14} color="#FFFFFF" />
1290
+ </TouchableOpacity>
1291
+ </View>
1292
+ <View style={styles.pickerWrap}>
1293
+ <Picker
1294
+ selectedValue={draft.category || ''}
1295
+ onValueChange={value => updateDraft({ category: value || null })}
1296
+ mode={Platform.OS === 'android' ? 'dropdown' : undefined}
1297
+ >
1298
+ <Picker.Item label="Selecionar automaticamente" value="" />
1299
+ {categories.map(category => (
1300
+ <Picker.Item
1301
+ key={normalizeId(category?.id || category?.['@id']) || category?.name}
1302
+ label={category?.name || 'Categoria'}
1303
+ value={toIri(category, 'categories') || ''}
1304
+ />
1305
+ ))}
1306
+ </Picker>
1307
+ </View>
1308
+ </View>
1309
+
1310
+ <View style={[styles.fieldBlock, styles.formField]}>
1311
+ <FieldLabel
1312
+ label="Responsavel / signatario"
1313
+ suffix={loadingMetadata ? '(carregando...)' : ''}
1314
+ required
1315
+ />
1316
+ <View style={styles.pickerWrap}>
1317
+ <Picker
1318
+ selectedValue={draft.signer || ''}
1319
+ onValueChange={value => updateDraft({ signer: value || null })}
1320
+ mode={Platform.OS === 'android' ? 'dropdown' : undefined}
1321
+ >
1322
+ <Picker.Item label="Selecionar automaticamente" value="" />
1323
+ {signers.map(person => (
1324
+ <Picker.Item
1325
+ key={normalizeId(person?.id || person?.['@id']) || person?.name}
1326
+ label={person?.alias || person?.name || 'Pessoa'}
1327
+ value={toIri(person, 'people') || ''}
1328
+ />
1329
+ ))}
1330
+ </Picker>
1331
+ </View>
1332
+ </View>
1333
+ </View>
1334
+
1335
+ <View style={styles.snippetCard}>
1336
+ <Text style={styles.snippetTitle}>Snippets rapidos</Text>
1337
+ <Text style={styles.snippetSub}>
1338
+ Toque para inserir no cursor. O preview abaixo e estrutural e nao executa o Twig.
1339
+ </Text>
1340
+ <View style={styles.snippetWrap}>
1341
+ {activeSnippets.map(snippet => (
1342
+ <TouchableOpacity
1343
+ key={`${draft.context}-${snippet.label}`}
1344
+ style={styles.snippetButton}
1345
+ activeOpacity={0.85}
1346
+ onPress={() => insertSnippet(snippet.value)}
1347
+ >
1348
+ <Text style={styles.snippetButtonText}>{snippet.label}</Text>
1349
+ </TouchableOpacity>
1350
+ ))}
1351
+ </View>
1352
+ </View>
1353
+
1354
+ <View style={styles.modeSwitch}>
1355
+ <TouchableOpacity
1356
+ style={[styles.modeButton, viewMode === 'editor' && styles.modeButtonActive]}
1357
+ activeOpacity={0.88}
1358
+ onPress={() => setViewMode('editor')}
1359
+ >
1360
+ <Icon name="edit-3" size={15} color={viewMode === 'editor' ? '#0F172A' : '#64748B'} />
1361
+ <Text style={[styles.modeButtonText, viewMode === 'editor' && styles.modeButtonTextActive]}>
1362
+ Editor
1363
+ </Text>
1364
+ </TouchableOpacity>
1365
+
1366
+ <TouchableOpacity
1367
+ style={[styles.modeButton, viewMode === 'preview' && styles.modeButtonActive]}
1368
+ activeOpacity={0.88}
1369
+ onPress={() => setViewMode('preview')}
1370
+ >
1371
+ <Icon name="eye" size={15} color={viewMode === 'preview' ? '#0F172A' : '#64748B'} />
1372
+ <Text style={[styles.modeButtonText, viewMode === 'preview' && styles.modeButtonTextActive]}>
1373
+ Preview
1374
+ </Text>
1375
+ </TouchableOpacity>
1376
+ </View>
1377
+
1378
+ {loadingFile ? (
1379
+ <View style={styles.editorLoading}>
1380
+ <ActivityIndicator size="small" color={brandColors.primary} />
1381
+ <Text style={styles.editorLoadingText}>Carregando HTML/Twig do arquivo vinculado...</Text>
1382
+ </View>
1383
+ ) : viewMode === 'editor' ? (
1384
+ <View style={styles.editorFieldBlock}>
1385
+ <FieldLabel label="HTML / Twig do modelo" required />
1386
+ <TextInput
1387
+ ref={editorRef}
1388
+ multiline
1389
+ value={draft.html}
1390
+ onChangeText={value => updateDraft({ html: value })}
1391
+ onSelectionChange={event => setEditorSelection(event?.nativeEvent?.selection || { start: 0, end: 0 })}
1392
+ selection={editorSelection}
1393
+ textAlignVertical="top"
1394
+ autoCapitalize="none"
1395
+ autoCorrect={false}
1396
+ placeholder="Digite aqui o HTML/Twig do modelo"
1397
+ placeholderTextColor="#94A3B8"
1398
+ style={styles.editorInput}
1399
+ />
1400
+ </View>
1401
+ ) : (
1402
+ <View style={styles.previewBox}>
1403
+ {draft.html.trim() ? (
1404
+ <RenderHTML
1405
+ contentWidth={isDesktop ? width - 520 : Math.max(width - 72, 280)}
1406
+ source={{ html: draft.html }}
1407
+ />
1408
+ ) : (
1409
+ <Text style={styles.emptySub}>Adicione conteudo para visualizar o preview.</Text>
1410
+ )}
1411
+ </View>
1412
+ )}
1413
+ </View>
1414
+ );
1415
+
1416
+ return (
1417
+ <SafeAreaView style={[styles.container, { backgroundColor: brandColors.background }]}>
1418
+ {isDesktop ? (
1419
+ <View style={styles.desktopShell}>
1420
+ {renderSummary()}
1421
+
1422
+ <View style={styles.desktopColumns}>
1423
+ <View style={styles.sidebarPanel}>
1424
+ <ScrollView
1425
+ showsVerticalScrollIndicator={false}
1426
+ contentContainerStyle={styles.panelContent}
1427
+ >
1428
+ {renderSidebar()}
1429
+ </ScrollView>
1430
+ </View>
1431
+
1432
+ <View style={styles.editorPanel}>
1433
+ <ScrollView
1434
+ showsVerticalScrollIndicator={false}
1435
+ contentContainerStyle={styles.panelContent}
1436
+ >
1437
+ {renderEditor()}
1438
+ </ScrollView>
1439
+ </View>
1440
+ </View>
1441
+ </View>
1442
+ ) : (
1443
+ <ScrollView
1444
+ showsVerticalScrollIndicator={false}
1445
+ contentContainerStyle={styles.mobileShell}
1446
+ >
1447
+ {renderSummary()}
1448
+
1449
+ <View style={styles.mobileSidebarPanel}>
1450
+ {renderSidebar()}
1451
+ </View>
1452
+
1453
+ <View style={styles.mobileEditorPanel}>
1454
+ {renderEditor()}
1455
+ </View>
1456
+ </ScrollView>
1457
+ )}
1458
+ </SafeAreaView>
1459
+ );
1460
+ }
1461
+ // TODO(store-first): quando este arquivo for mexido, mover a leitura para stores, remover api.fetch e evitar repassar dados em objetos quando o store ja resolver isso.