@controleonline/ui-common 1.2.70

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 (203) hide show
  1. package/.github/agents/developer.agent.md +30 -0
  2. package/.github/agents/devops.agent.md +30 -0
  3. package/.github/agents/qa.agent.md +30 -0
  4. package/.github/agents/security.agent.md +30 -0
  5. package/.github/workflows/npmjs.yml +35 -0
  6. package/.github/workflows/pull-request-checks.yml +19 -0
  7. package/.scrutinizer.yml +24 -0
  8. package/FUNDING.yml +1 -0
  9. package/package.json +28 -0
  10. package/src/api/fetch.js +74 -0
  11. package/src/api/index.js +155 -0
  12. package/src/api/localDB.js +131 -0
  13. package/src/api/queue.js +66 -0
  14. package/src/react/assets/tap.mp3 +0 -0
  15. package/src/react/components/AddImportModal.js +157 -0
  16. package/src/react/components/AddImportModal.styles.js +81 -0
  17. package/src/react/components/BackgroundRuntimeBridge.js +219 -0
  18. package/src/react/components/BottomNavigationBar.config.js +238 -0
  19. package/src/react/components/BottomNavigationBar.js +120 -0
  20. package/src/react/components/BottomNavigationBar.styles.js +110 -0
  21. package/src/react/components/CategoryForm.js +572 -0
  22. package/src/react/components/CategoryForm.styles.js +334 -0
  23. package/src/react/components/ConfirmModal.js +24 -0
  24. package/src/react/components/ConfirmModal.styles.js +43 -0
  25. package/src/react/components/ContextHelpButton.js +69 -0
  26. package/src/react/components/ContextHelpButton.styles.js +62 -0
  27. package/src/react/components/DefaultProvider.native.js +848 -0
  28. package/src/react/components/DefaultProvider.styles.js +21 -0
  29. package/src/react/components/DefaultProvider.web.js +909 -0
  30. package/src/react/components/DeliveryPushBridge.native.js +314 -0
  31. package/src/react/components/DeliveryPushBridge.web.js +5 -0
  32. package/src/react/components/DeviceAlertSoundService.js +499 -0
  33. package/src/react/components/EntityLogContent.js +909 -0
  34. package/src/react/components/EntityLogContent.styles.js +400 -0
  35. package/src/react/components/EventBus.js +12 -0
  36. package/src/react/components/KioskModeBridge.js +65 -0
  37. package/src/react/components/LauncherModeBridge.js +47 -0
  38. package/src/react/components/LinkedOrderProductsTab.js +388 -0
  39. package/src/react/components/LinkedOrderProductsTab.styles.js +180 -0
  40. package/src/react/components/ManagerPushBridge.native.js +345 -0
  41. package/src/react/components/MessageService.js +314 -0
  42. package/src/react/components/Paywall/Google.js +89 -0
  43. package/src/react/components/PrintService.js +778 -0
  44. package/src/react/components/ProductCatalogCacheService.js +45 -0
  45. package/src/react/components/RemoteCheckoutService.js +292 -0
  46. package/src/react/components/RuntimeBottomNavigationBar.js +151 -0
  47. package/src/react/components/RuntimeInfoFooter.js +214 -0
  48. package/src/react/components/RuntimeInfoFooter.styles.js +56 -0
  49. package/src/react/components/SystemErrorToast.js +29 -0
  50. package/src/react/components/SystemErrorToast.styles.js +38 -0
  51. package/src/react/components/TouchFeedbackProvider.js +65 -0
  52. package/src/react/components/UnifiedPaymentBar.js +155 -0
  53. package/src/react/components/UnifiedPaymentBar.styles.js +174 -0
  54. package/src/react/components/WebsocketListener.native.js +487 -0
  55. package/src/react/components/WebsocketListener.web.js +102 -0
  56. package/src/react/components/inputs/IdInput.js +49 -0
  57. package/src/react/components/inputs/IdInput.styles.js +26 -0
  58. package/src/react/components/inputs/InvoiceDueDateFilterInput.js +74 -0
  59. package/src/react/components/inputs/InvoiceDueDateFilterInput.styles.js +34 -0
  60. package/src/react/components/inputs/InvoiceDueDateRangeFilterInput.js +115 -0
  61. package/src/react/components/inputs/InvoiceDueDateRangeFilterInput.styles.js +39 -0
  62. package/src/react/components/lists/CategoriesList.js +56 -0
  63. package/src/react/components/lists/PaymentTypeList.js +55 -0
  64. package/src/react/components/lists/ReceiverList.js +56 -0
  65. package/src/react/components/lists/SelectList.styles.js +18 -0
  66. package/src/react/components/lists/StatusList.js +55 -0
  67. package/src/react/components/lists/WalletList.js +54 -0
  68. package/src/react/components/radio/Spotify.js +144 -0
  69. package/src/react/components/radio/Spotify.styles.js +32 -0
  70. package/src/react/components/radio/YouTube.js +82 -0
  71. package/src/react/components/radio/YouTube.styles.js +16 -0
  72. package/src/react/components/toastConfig.js +16 -0
  73. package/src/react/config/deviceConfigBootstrap.js +571 -0
  74. package/src/react/index.js +4 -0
  75. package/src/react/localStorage.js +30 -0
  76. package/src/react/pages/EntityLogPage.js +124 -0
  77. package/src/react/pages/EntityLogPage.styles.js +17 -0
  78. package/src/react/pages/GenericLogPage.js +760 -0
  79. package/src/react/pages/GenericLogPage.styles.js +401 -0
  80. package/src/react/pages/Imports.js +361 -0
  81. package/src/react/pages/Imports.styles.js +223 -0
  82. package/src/react/pages/SettingsPage/PaymentTypesByWalletTab.js +462 -0
  83. package/src/react/pages/SettingsPage/index.js +1171 -0
  84. package/src/react/pages/SettingsPage/index.styles.js +122 -0
  85. package/src/react/print/jobs.js +147 -0
  86. package/src/react/print/providers/local.js +53 -0
  87. package/src/react/print/providers/remote.js +81 -0
  88. package/src/react/print/selection.js +296 -0
  89. package/src/react/print/usePrintButtonController.js +474 -0
  90. package/src/react/router/routes.js +42 -0
  91. package/src/react/services/NetworkPrinterService.native.js +391 -0
  92. package/src/react/services/NetworkPrinterService.web.js +15 -0
  93. package/src/react/stores/index.js +128 -0
  94. package/src/react/stores/storeErrorBridge.js +36 -0
  95. package/src/react/utils/backgroundRuntimeRegistration.js +69 -0
  96. package/src/react/utils/cashPayment.js +87 -0
  97. package/src/react/utils/commercialDocumentOrders.js +269 -0
  98. package/src/react/utils/dateRangeFilter.js +264 -0
  99. package/src/react/utils/deviceRuntime.js +193 -0
  100. package/src/react/utils/entityDisplay.js +231 -0
  101. package/src/react/utils/entityLog.js +649 -0
  102. package/src/react/utils/fileUrl.js +102 -0
  103. package/src/react/utils/frontendDebugLog.js +45 -0
  104. package/src/react/utils/googleMapsConfig.js +49 -0
  105. package/src/react/utils/importStatus.js +100 -0
  106. package/src/react/utils/invoiceDueDateMessages.js +14 -0
  107. package/src/react/utils/invoicePresentation.js +46 -0
  108. package/src/react/utils/logSettings.js +143 -0
  109. package/src/react/utils/maintenanceSettings.js +53 -0
  110. package/src/react/utils/managerOrderNotifications.js +523 -0
  111. package/src/react/utils/mapNavigation.js +76 -0
  112. package/src/react/utils/menuCatalogConfig.js +8 -0
  113. package/src/react/utils/menuCatalogDownload.js +157 -0
  114. package/src/react/utils/networkCameraDevices.js +175 -0
  115. package/src/react/utils/networkDeviceProfiles.js +135 -0
  116. package/src/react/utils/normalizedCatalogDownload.js +157 -0
  117. package/src/react/utils/notificationNavigation.js +94 -0
  118. package/src/react/utils/notificationSound.js +42 -0
  119. package/src/react/utils/paymentDevices.js +397 -0
  120. package/src/react/utils/paymentGatewayExecution.js +91 -0
  121. package/src/react/utils/paymentOptions.js +88 -0
  122. package/src/react/utils/peopleDisplay.js +39 -0
  123. package/src/react/utils/printerDevices.js +465 -0
  124. package/src/react/utils/remotePayment.js +61 -0
  125. package/src/react/utils/runtimeFooter.js +475 -0
  126. package/src/react/utils/runtimeLanguage.js +50 -0
  127. package/src/react/utils/runtimeMenu.js +224 -0
  128. package/src/react/utils/screenMetrics.js +30 -0
  129. package/src/react/utils/shopConfig.js +294 -0
  130. package/src/react/utils/shopFranchises.js +114 -0
  131. package/src/react/utils/socketRuntimePipeline.js +454 -0
  132. package/src/react/utils/spoolAckTracker.js +77 -0
  133. package/src/react/utils/storeColumns.js +427 -0
  134. package/src/react/utils/systemErrorChannel.js +109 -0
  135. package/src/react/utils/systemErrorMessage.js +67 -0
  136. package/src/react/utils/toastPresentation.js +53 -0
  137. package/src/react/utils/websocketSharedRuntime.js +826 -0
  138. package/src/store/acl/getters.js +4 -0
  139. package/src/store/acl/index.js +19 -0
  140. package/src/store/acl/mutation_types.js +4 -0
  141. package/src/store/acl/mutations.js +17 -0
  142. package/src/store/address/city.js +22 -0
  143. package/src/store/categories/category_file/index.js +25 -0
  144. package/src/store/categories/index.js +93 -0
  145. package/src/store/configs/customActions.js +131 -0
  146. package/src/store/configs/index.js +25 -0
  147. package/src/store/connections/customActions.js +26 -0
  148. package/src/store/connections/index.js +124 -0
  149. package/src/store/device/index.js +22 -0
  150. package/src/store/device_config/customActions.js +190 -0
  151. package/src/store/device_config/index.js +28 -0
  152. package/src/store/entity_log/customActions.js +63 -0
  153. package/src/store/entity_log/index.js +25 -0
  154. package/src/store/extra/data.js +85 -0
  155. package/src/store/extra/fields.js +88 -0
  156. package/src/store/file/actions.js +27 -0
  157. package/src/store/file/index.js +24 -0
  158. package/src/store/imports/index.js +88 -0
  159. package/src/store/print/customActions.js +251 -0
  160. package/src/store/print/index.js +28 -0
  161. package/src/store/printer/customActions.js +54 -0
  162. package/src/store/printer/index.js +26 -0
  163. package/src/store/runtime_debug/customActions.js +71 -0
  164. package/src/store/runtime_debug/index.js +30 -0
  165. package/src/store/status/index.js +65 -0
  166. package/src/store/timezones/index.js +43 -0
  167. package/src/store/websocket/customActions.js +24 -0
  168. package/src/store/websocket/index.js +28 -0
  169. package/src/tests/react/components/LauncherModeBridge.test.js +93 -0
  170. package/src/tests/react/config/deviceConfigBootstrap.test.js +337 -0
  171. package/src/tests/react/print/localPrintProvider.test.js +45 -0
  172. package/src/tests/react/utils/backgroundRuntimeRegistration.test.js +123 -0
  173. package/src/tests/react/utils/cashPayment.test.js +41 -0
  174. package/src/tests/react/utils/dateRangeFilter.test.mjs +29 -0
  175. package/src/tests/react/utils/entityDisplay.test.js +18 -0
  176. package/src/tests/react/utils/googleMapsConfig.test.js +32 -0
  177. package/src/tests/react/utils/importStatus.test.js +85 -0
  178. package/src/tests/react/utils/invoicePresentation.test.mjs +40 -0
  179. package/src/tests/react/utils/managerOrderNotifications.test.js +127 -0
  180. package/src/tests/react/utils/mapNavigation.test.js +58 -0
  181. package/src/tests/react/utils/notificationNavigation.test.js +39 -0
  182. package/src/tests/react/utils/notificationSound.test.js +27 -0
  183. package/src/tests/react/utils/paymentDevices.test.js +88 -0
  184. package/src/tests/react/utils/runtimeFooter.test.js +429 -0
  185. package/src/tests/react/utils/runtimeLanguage.test.js +80 -0
  186. package/src/tests/react/utils/runtimeMenu.test.js +174 -0
  187. package/src/tests/react/utils/shopFranchises.test.js +82 -0
  188. package/src/tests/react/utils/socketRuntimePipeline.test.js +124 -0
  189. package/src/tests/react/utils/spoolAckTracker.test.js +40 -0
  190. package/src/tests/react/utils/storeErrorBridge.test.js +66 -0
  191. package/src/tests/react/utils/systemErrorChannel.test.js +58 -0
  192. package/src/tests/react/utils/systemErrorMessage.test.js +59 -0
  193. package/src/tests/react/utils/toastPresentation.test.js +75 -0
  194. package/src/tests/react/utils/translate.test.mjs +396 -0
  195. package/src/tests/react/utils/websocketSharedRuntime.test.js +245 -0
  196. package/src/utils/apiEntryPoint.js +31 -0
  197. package/src/utils/appDomain.js +50 -0
  198. package/src/utils/config.js +14 -0
  199. package/src/utils/formatter.js +419 -0
  200. package/src/utils/integrationConfigs.js +79 -0
  201. package/src/utils/methods.js +23 -0
  202. package/src/utils/oauth.js +42 -0
  203. package/src/utils/translate.js +620 -0
@@ -0,0 +1,487 @@
1
+ import React, {useEffect, useRef} from 'react';
2
+ import TcpSocket from 'react-native-tcp-socket';
3
+ import {useStore, getAllStores} from '@store';
4
+
5
+ const LOCAL_RUNTIME_HOST = '127.0.0.1';
6
+ const LOCAL_RUNTIME_PORT = 41572;
7
+
8
+ const normalizeText = value => String(value || '').trim();
9
+
10
+ const formatClock = value => {
11
+ const normalized = normalizeText(value);
12
+ if (!normalized) {
13
+ return '--';
14
+ }
15
+
16
+ try {
17
+ const date = new Date(normalized);
18
+ if (Number.isNaN(date.getTime())) {
19
+ return '--';
20
+ }
21
+
22
+ const pad = entry => String(entry).padStart(2, '0');
23
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(
24
+ date.getSeconds(),
25
+ )}`;
26
+ } catch {
27
+ return '--';
28
+ }
29
+ };
30
+
31
+ const truncateText = (value, max = 44) => {
32
+ const normalized = normalizeText(value);
33
+ if (!normalized || normalized.length <= max) {
34
+ return normalized || '--';
35
+ }
36
+
37
+ return `${normalized.slice(0, max - 3)}...`;
38
+ };
39
+
40
+ const isFilledObject = value =>
41
+ !!value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0;
42
+
43
+ export const WebsocketListener = () => {
44
+ const socketRef = useRef(null);
45
+ const reconnectTimeoutRef = useRef(null);
46
+ const connectTimeoutRef = useRef(null);
47
+ const pendingMessagesRef = useRef({});
48
+ const flushMessagesPromiseRef = useRef(null);
49
+ const reconnectAttempts = useRef(0);
50
+ const isIdentifyingRef = useRef(false);
51
+ const manualCloseRef = useRef(false);
52
+ const connectionTokenRef = useRef(0);
53
+ const inboundBufferRef = useRef('');
54
+
55
+ const deviceStore = useStore('device');
56
+ const peopleStore = useStore('people');
57
+ const websocketStore = useStore('websocket');
58
+ const runtimeDebugStore = useStore('runtime_debug');
59
+ const {item: device} = deviceStore.getters;
60
+ const {currentCompany} = peopleStore.getters;
61
+ const websocketActions = websocketStore.actions;
62
+ const runtimeDebugActions = runtimeDebugStore.actions;
63
+
64
+ const stores = getAllStores();
65
+ const getStoreByName = name => stores[name];
66
+
67
+ const publishSocketFooterEntry = (state = {}) => {
68
+ const socketConnected = Boolean(state?.connected);
69
+ const socketIdentified = Boolean(state?.identified);
70
+ const normalizedStatus = normalizeText(state?.status).toLowerCase();
71
+ const stateLabel = socketConnected
72
+ ? socketIdentified
73
+ ? 'socket:on'
74
+ : 'socket:open'
75
+ : `socket:${normalizedStatus || 'off'}`;
76
+
77
+ const indicatorColor =
78
+ socketConnected && socketIdentified
79
+ ? '#10b981'
80
+ : (socketConnected || ['connecting', 'identifying', 'open', 'reconnecting'].includes(normalizedStatus))
81
+ ? '#e67e22'
82
+ : '#c10015';
83
+ const lastSocketStores = Array.isArray(state?.lastStores)
84
+ ? state.lastStores.filter(Boolean).join(', ')
85
+ : '';
86
+ const lastSocketCompanies = Array.isArray(state?.lastCompanies)
87
+ ? state.lastCompanies.filter(Boolean).join(', ')
88
+ : '';
89
+
90
+ runtimeDebugActions.setFooterEntry({
91
+ key: 'socket',
92
+ order: 10,
93
+ indicatorColor,
94
+ updatedAt: state?.updatedAt || new Date().toISOString(),
95
+ lines: [
96
+ `Realtime ${stateLabel} | empresa: ${normalizeText(
97
+ currentCompany?.id,
98
+ ) || '--'} | device: ${truncateText(state?.device || device?.id || '--', 34)}`,
99
+ `ultimo socket: ${formatClock(state?.lastEventAt)} | eventos: ${Number(
100
+ state?.lastEventCount || 0,
101
+ )} | stores: ${truncateText(lastSocketStores || '--', 28)} | empresas: ${truncateText(
102
+ lastSocketCompanies || '--',
103
+ 18,
104
+ )}`,
105
+ ],
106
+ });
107
+ };
108
+
109
+ const updateConnectionState = (state = {}) => {
110
+ const nextState = {
111
+ connected: false,
112
+ identified: false,
113
+ status: 'idle',
114
+ attempts: reconnectAttempts.current,
115
+ updatedAt: new Date().toISOString(),
116
+ ...state,
117
+ };
118
+
119
+ websocketActions.setSummary(nextState);
120
+ publishSocketFooterEntry(nextState);
121
+ };
122
+
123
+ const isActiveSocket = (socket, connectionToken) =>
124
+ socketRef.current === socket && connectionTokenRef.current === connectionToken;
125
+
126
+ const flushPendingMessages = () => {
127
+ flushMessagesPromiseRef.current = null;
128
+ const pendingMessages = pendingMessagesRef.current;
129
+ pendingMessagesRef.current = {};
130
+ const deliveredStores = [];
131
+ const deliveredCompanies = new Set();
132
+
133
+ let deliveredMessages = 0;
134
+ Object.entries(pendingMessages).forEach(([storeName, messages]) => {
135
+ if (!Array.isArray(messages) || messages.length === 0) {
136
+ return;
137
+ }
138
+
139
+ const storeModule = getStoreByName(storeName);
140
+ if (!storeModule) {
141
+ return;
142
+ }
143
+
144
+ const messageGetters = storeModule?.getters || {};
145
+ const messageActions = storeModule?.actions || {};
146
+ if (typeof messageActions?.setMessages !== 'function') {
147
+ return;
148
+ }
149
+
150
+ const currentMessages = Array.isArray(messageGetters?.messages)
151
+ ? messageGetters.messages
152
+ : [];
153
+
154
+ messageActions.setMessages([...currentMessages, ...messages]);
155
+ deliveredMessages += messages.length;
156
+ deliveredStores.push(storeName);
157
+ messages.forEach(message => {
158
+ const companyId = String(
159
+ message?.company?.id || message?.companyId || message?.company || '',
160
+ ).trim();
161
+ if (companyId) {
162
+ deliveredCompanies.add(companyId);
163
+ }
164
+ });
165
+ });
166
+
167
+ if (deliveredMessages > 0) {
168
+ updateConnectionState({
169
+ status: 'connected',
170
+ connected: true,
171
+ identified: true,
172
+ device: device?.id || null,
173
+ error: null,
174
+ lastEventAt: new Date().toISOString(),
175
+ lastEventCount: deliveredMessages,
176
+ lastStores: deliveredStores,
177
+ lastCompanies: Array.from(deliveredCompanies),
178
+ });
179
+ }
180
+ };
181
+
182
+ const appendMessageToStore = data => {
183
+ if (!data?.store) {
184
+ return;
185
+ }
186
+
187
+ const storeModule = getStoreByName(data.store);
188
+ if (!storeModule?.actions || typeof storeModule.actions.setMessages !== 'function') {
189
+ return;
190
+ }
191
+
192
+ if (!Array.isArray(pendingMessagesRef.current[data.store])) {
193
+ pendingMessagesRef.current[data.store] = [];
194
+ }
195
+
196
+ pendingMessagesRef.current[data.store].push({
197
+ ...data,
198
+ source: 'background-runtime',
199
+ });
200
+
201
+ if (!flushMessagesPromiseRef.current) {
202
+ flushMessagesPromiseRef.current = Promise.resolve().then(() => {
203
+ flushPendingMessages();
204
+ });
205
+ }
206
+ };
207
+
208
+ const processIncomingPayload = payload => {
209
+ if (!payload) {
210
+ return;
211
+ }
212
+
213
+ if (payload.type === 'socket-state') {
214
+ isIdentifyingRef.current = false;
215
+ updateConnectionState({
216
+ connected: Boolean(payload.connected),
217
+ identified: Boolean(payload.identified),
218
+ status: normalizeText(payload.status) || 'connected',
219
+ attempts: Number(payload.attempts || 0),
220
+ updatedAt: payload.updatedAt || new Date().toISOString(),
221
+ device: payload.device || device?.id || null,
222
+ error: payload.error || null,
223
+ code: payload.code || null,
224
+ reason: payload.reason || '',
225
+ lastEventAt: payload.lastEventAt || null,
226
+ lastEventCount: Number(payload.lastEventCount || 0),
227
+ lastStores: Array.isArray(payload.lastStores) ? payload.lastStores : [],
228
+ lastCompanies: Array.isArray(payload.lastCompanies)
229
+ ? payload.lastCompanies
230
+ : [],
231
+ });
232
+ return;
233
+ }
234
+
235
+ if (payload.status === 'identified') {
236
+ isIdentifyingRef.current = false;
237
+ updateConnectionState({
238
+ status: 'connected',
239
+ connected: true,
240
+ identified: true,
241
+ device: payload.device || device?.id,
242
+ error: null,
243
+ });
244
+ return;
245
+ }
246
+
247
+ if (payload.status === 'error') {
248
+ isIdentifyingRef.current = false;
249
+ updateConnectionState({
250
+ status: 'error',
251
+ connected: false,
252
+ identified: false,
253
+ error: payload.message || 'Background runtime identify failed',
254
+ });
255
+ return;
256
+ }
257
+
258
+ const events = Array.isArray(payload) ? payload : [payload];
259
+ events.filter(isFilledObject).forEach(appendMessageToStore);
260
+ };
261
+
262
+ const processIncomingLine = line => {
263
+ const normalizedLine = normalizeText(line);
264
+ if (!normalizedLine) {
265
+ return;
266
+ }
267
+
268
+ try {
269
+ processIncomingPayload(JSON.parse(normalizedLine));
270
+ } catch {
271
+ // Ignora linhas incompletas ou nao JSON.
272
+ }
273
+ };
274
+
275
+ const clearActiveSocket = () => {
276
+ const activeSocket = socketRef.current;
277
+ socketRef.current = null;
278
+
279
+ if (activeSocket) {
280
+ try {
281
+ activeSocket.removeAllListeners?.();
282
+ } catch {
283
+ // noop
284
+ }
285
+
286
+ try {
287
+ activeSocket.end?.();
288
+ } catch {
289
+ // noop
290
+ }
291
+
292
+ try {
293
+ activeSocket.destroy?.();
294
+ } catch {
295
+ // noop
296
+ }
297
+ }
298
+ };
299
+
300
+ const scheduleReconnect = () => {
301
+ if (
302
+ manualCloseRef.current ||
303
+ reconnectTimeoutRef.current ||
304
+ connectTimeoutRef.current ||
305
+ socketRef.current
306
+ ) {
307
+ return;
308
+ }
309
+
310
+ const delay = Math.min(10000 * Math.pow(2, reconnectAttempts.current), 12000);
311
+ reconnectAttempts.current += 1;
312
+ updateConnectionState({
313
+ status: 'reconnecting',
314
+ connected: false,
315
+ identified: false,
316
+ attempts: reconnectAttempts.current,
317
+ });
318
+
319
+ reconnectTimeoutRef.current = setTimeout(() => {
320
+ reconnectTimeoutRef.current = null;
321
+ if (device?.id) {
322
+ connect();
323
+ }
324
+ }, delay);
325
+ };
326
+
327
+ const connect = () => {
328
+ if (connectTimeoutRef.current || socketRef.current) {
329
+ return;
330
+ }
331
+
332
+ manualCloseRef.current = false;
333
+ updateConnectionState({
334
+ status: 'connecting',
335
+ connected: false,
336
+ identified: false,
337
+ error: null,
338
+ });
339
+
340
+ const connectionToken = connectionTokenRef.current + 1;
341
+ connectionTokenRef.current = connectionToken;
342
+
343
+ connectTimeoutRef.current = setTimeout(() => {
344
+ connectTimeoutRef.current = null;
345
+
346
+ if (manualCloseRef.current || !device?.id) {
347
+ return;
348
+ }
349
+
350
+ if (socketRef.current) {
351
+ return;
352
+ }
353
+
354
+ const socket = TcpSocket.createConnection(
355
+ {
356
+ host: LOCAL_RUNTIME_HOST,
357
+ port: LOCAL_RUNTIME_PORT,
358
+ reuseAddress: true,
359
+ connectTimeout: 1500,
360
+ },
361
+ () => {
362
+ if (!isActiveSocket(socket, connectionToken)) {
363
+ return;
364
+ }
365
+
366
+ reconnectAttempts.current = 0;
367
+ isIdentifyingRef.current = true;
368
+ updateConnectionState({
369
+ status: 'open',
370
+ connected: false,
371
+ identified: false,
372
+ error: null,
373
+ });
374
+ },
375
+ );
376
+
377
+ socketRef.current = socket;
378
+ socket.setNoDelay?.(true);
379
+
380
+ socket.on('data', chunk => {
381
+ if (!isActiveSocket(socket, connectionToken)) {
382
+ return;
383
+ }
384
+
385
+ const chunkText =
386
+ typeof chunk === 'string'
387
+ ? chunk
388
+ : chunk?.toString?.('utf8') || String(chunk || '');
389
+
390
+ if (!chunkText) {
391
+ return;
392
+ }
393
+
394
+ inboundBufferRef.current += chunkText;
395
+ const lines = inboundBufferRef.current.split(/\r?\n/);
396
+ inboundBufferRef.current = lines.pop() || '';
397
+ lines.forEach(processIncomingLine);
398
+ });
399
+
400
+ socket.on('error', () => {
401
+ if (!isActiveSocket(socket, connectionToken) || manualCloseRef.current) {
402
+ return;
403
+ }
404
+
405
+ updateConnectionState({
406
+ status: 'error',
407
+ connected: false,
408
+ identified: false,
409
+ });
410
+
411
+ try {
412
+ socket.destroy();
413
+ } catch {
414
+ // noop
415
+ }
416
+ });
417
+
418
+ socket.on('close', () => {
419
+ const isCurrentSocket = isActiveSocket(socket, connectionToken);
420
+
421
+ if (isCurrentSocket) {
422
+ clearActiveSocket();
423
+ }
424
+
425
+ if (!isCurrentSocket) {
426
+ return;
427
+ }
428
+
429
+ isIdentifyingRef.current = false;
430
+ updateConnectionState({
431
+ status: manualCloseRef.current ? 'closed' : 'disconnected',
432
+ connected: false,
433
+ identified: false,
434
+ device: device?.id || null,
435
+ });
436
+
437
+ if (!manualCloseRef.current) {
438
+ scheduleReconnect();
439
+ }
440
+ });
441
+ }, 80);
442
+ };
443
+
444
+ const close = () => {
445
+ manualCloseRef.current = true;
446
+ connectionTokenRef.current += 1;
447
+
448
+ if (connectTimeoutRef.current) {
449
+ clearTimeout(connectTimeoutRef.current);
450
+ connectTimeoutRef.current = null;
451
+ }
452
+
453
+ clearActiveSocket();
454
+
455
+ if (reconnectTimeoutRef.current) {
456
+ clearTimeout(reconnectTimeoutRef.current);
457
+ reconnectTimeoutRef.current = null;
458
+ }
459
+
460
+ pendingMessagesRef.current = {};
461
+ flushMessagesPromiseRef.current = null;
462
+ inboundBufferRef.current = '';
463
+ isIdentifyingRef.current = false;
464
+
465
+ updateConnectionState({
466
+ status: device?.id ? 'closed' : 'idle',
467
+ connected: false,
468
+ identified: false,
469
+ device: device?.id || null,
470
+ });
471
+ };
472
+
473
+ useEffect(() => {
474
+ if (device?.id) {
475
+ manualCloseRef.current = false;
476
+ connect();
477
+ } else {
478
+ close();
479
+ }
480
+
481
+ return close;
482
+ }, [device?.id]);
483
+
484
+ return null;
485
+ };
486
+
487
+ export default WebsocketListener;
@@ -0,0 +1,102 @@
1
+ import React, {useEffect, useRef} from 'react';
2
+ import {useStore, getAllStores} from '@store';
3
+ import {env} from '@env';
4
+ import {createSocketRuntimePipeline} from '@controleonline/ui-common/src/react/utils/socketRuntimePipeline';
5
+ import {createWebsocketSharedRuntime} from '@controleonline/ui-common/src/react/utils/websocketSharedRuntime';
6
+
7
+ export const WebsocketListener = () => {
8
+ const deviceStore = useStore('device');
9
+ const peopleStore = useStore('people');
10
+ const websocketStore = useStore('websocket');
11
+ const runtimeDebugStore = useStore('runtime_debug');
12
+
13
+ const {item: device} = deviceStore.getters;
14
+ const {currentCompany} = peopleStore.getters;
15
+ const websocketActions = websocketStore.actions;
16
+ const runtimeDebugActions = runtimeDebugStore.actions;
17
+
18
+ const storesRef = useRef(getAllStores());
19
+ const contextRef = useRef({
20
+ deviceId: '',
21
+ companyId: '',
22
+ });
23
+ const pipelineRef = useRef(null);
24
+ const runtimeRef = useRef(null);
25
+
26
+ useEffect(() => {
27
+ if (typeof global === 'undefined') {
28
+ return undefined;
29
+ }
30
+
31
+ global.__codexInjectInvoiceMessage = message => {
32
+ const stores = getAllStores();
33
+ const invoiceStore = stores?.invoice;
34
+
35
+ if (!invoiceStore?.actions?.setMessages) {
36
+ return false;
37
+ }
38
+
39
+ const currentMessages = Array.isArray(invoiceStore.getters?.messages)
40
+ ? invoiceStore.getters.messages
41
+ : [];
42
+
43
+ invoiceStore.actions.setMessages([...currentMessages, message]);
44
+ return true;
45
+ };
46
+
47
+ return () => {
48
+ if (global.__codexInjectInvoiceMessage) {
49
+ delete global.__codexInjectInvoiceMessage;
50
+ }
51
+ };
52
+ }, []);
53
+
54
+ contextRef.current = {
55
+ deviceId: String(device?.id || '').trim(),
56
+ companyId: String(currentCompany?.id || '').trim(),
57
+ };
58
+
59
+ useEffect(() => {
60
+ const socketUrl = String(env.SOCKET || '').trim();
61
+
62
+ if (!device?.id || !socketUrl) {
63
+ runtimeRef.current?.stop?.();
64
+ runtimeRef.current = null;
65
+ pipelineRef.current = null;
66
+ return undefined;
67
+ }
68
+
69
+ const pipeline = createSocketRuntimePipeline({
70
+ getDeviceId: () => contextRef.current.deviceId,
71
+ getCurrentCompanyId: () => contextRef.current.companyId,
72
+ websocketActions,
73
+ runtimeDebugActions,
74
+ getStoreByName: name => storesRef.current[name],
75
+ });
76
+
77
+ pipelineRef.current = pipeline;
78
+
79
+ const runtime = createWebsocketSharedRuntime({
80
+ socketUrl,
81
+ getDeviceId: () => contextRef.current.deviceId,
82
+ pipeline,
83
+ });
84
+
85
+ runtimeRef.current = runtime;
86
+ runtime.start();
87
+
88
+ return () => {
89
+ runtime.stop();
90
+ runtimeRef.current = null;
91
+ pipelineRef.current = null;
92
+ };
93
+ }, [device?.id, runtimeDebugActions, websocketActions]);
94
+
95
+ useEffect(() => {
96
+ pipelineRef.current?.refreshFooter?.();
97
+ }, [currentCompany?.alias, currentCompany?.id, currentCompany?.name, device?.id]);
98
+
99
+ return null;
100
+ };
101
+
102
+ export default WebsocketListener;
@@ -0,0 +1,49 @@
1
+ import React, { useEffect, useState } from 'react'
2
+ import { View, Text, TextInput } from 'react-native'
3
+ import { useStore } from '@store'
4
+ import styles from './IdInput.styles'
5
+
6
+ const IdInput = ({ onSearch }) => {
7
+ const invoiceStore = useStore('invoice')
8
+ const { actions: invoiceActions, getters: invoiceGetters } = invoiceStore
9
+ const [inputValue, setInputValue] = useState('')
10
+
11
+ useEffect(() => {
12
+ setInputValue(invoiceGetters?.filters?.id ? String(invoiceGetters.filters.id) : '')
13
+ }, [invoiceGetters?.filters?.id])
14
+
15
+ const handleTextChange = (value) => {
16
+ setInputValue(value)
17
+ invoiceActions.setFilterId(value)
18
+ }
19
+
20
+ const handleBlur = () => {
21
+ if (typeof onSearch === 'function') onSearch()
22
+ }
23
+
24
+ const handleSubmit = () => {
25
+ if (typeof onSearch === 'function') onSearch()
26
+ }
27
+
28
+ return (
29
+ <View style={styles.container}>
30
+ <Text style={styles.label}>
31
+ {global.t?.t("invoice", "label", "id")}
32
+ </Text>
33
+
34
+ <TextInput
35
+ style={styles.input}
36
+ placeholder={global.t?.t("idInput", "label", "Insert id")}
37
+ value={inputValue}
38
+ onChangeText={handleTextChange}
39
+ onBlur={handleBlur}
40
+ onSubmitEditing={handleSubmit}
41
+ placeholderTextColor="#999"
42
+ keyboardType="number-pad"
43
+ returnKeyType="search"
44
+ />
45
+ </View>
46
+ )
47
+ }
48
+
49
+ export default IdInput
@@ -0,0 +1,26 @@
1
+ import { StyleSheet } from 'react-native'
2
+
3
+ const styles = StyleSheet.create({
4
+ container: {
5
+ marginVertical: 10,
6
+ marginHorizontal: 8,
7
+ flex: 1,
8
+ },
9
+ label: {
10
+ fontSize: 14,
11
+ fontWeight: '600',
12
+ marginBottom: 5,
13
+ color: '#333',
14
+ },
15
+ input: {
16
+ borderWidth: 1,
17
+ borderColor: '#ccc',
18
+ borderRadius: 6,
19
+ paddingHorizontal: 12,
20
+ paddingVertical: 8,
21
+ fontSize: 14,
22
+ backgroundColor: '#fff',
23
+ },
24
+ })
25
+
26
+ export default styles