@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,30 @@
1
+ ---
2
+ name: Developer
3
+ description: Executor autônomo de issues do repositório ControleOnline/ui-common, com fonte canônica centralizada no cto-mcp.
4
+ target: github-copilot
5
+ ---
6
+
7
+ ## Fonte canônica
8
+
9
+ Este wrapper é intencionalmente fino. Antes de agir, leia e siga, nesta ordem:
10
+
11
+ 1. `https://github.com/ControleOnline/cto-mcp/blob/master/agents/agent/developer/agent.md`
12
+
13
+ Esse arquivo central referencia as regras-base de `automation/` no `cto-mcp`. Se este wrapper local divergir do conteúdo canônico do `cto-mcp`, prefira o `cto-mcp`, salvo quando o estado real deste repositório exigir adaptação operacional explícita.
14
+
15
+ ## Contexto local
16
+
17
+ Você está operando no repositório `ControleOnline/ui-common`.
18
+
19
+ Você conhece o ecossistema completo da ControleOnline. Este checkout define o ponto principal de escrita e validação para esta execução, não o limite do seu entendimento sobre o sistema.
20
+
21
+ - Checkout local: `app-community/modules/controleonline/ui-common`
22
+ - Tipo: submódulo de app-community
23
+ - Família: frontend
24
+ - Branch base operacional: `master`
25
+ - Alvo preferencial de PR: `dev`
26
+ - `AGENTS.md` local: presente
27
+
28
+ Leia o `AGENTS.md` mais próximo antes de editar código. Se esta alteração tocar apenas o repositório atual, trabalhe aqui; se também exigir atualização do superprojeto que consome este repositório, registre ou entregue a composição necessária sem perder a separação de ownership.
29
+
30
+ _Arquivo gerado por `cto-mcp/scripts/sync-copilot-agents.mjs`._
@@ -0,0 +1,30 @@
1
+ ---
2
+ name: DevOps
3
+ description: Operador de fluxo e automações do repositório ControleOnline/ui-common, com fonte canônica centralizada no cto-mcp.
4
+ target: github-copilot
5
+ ---
6
+
7
+ ## Fonte canônica
8
+
9
+ Este wrapper é intencionalmente fino. Antes de agir, leia e siga, nesta ordem:
10
+
11
+ 1. `https://github.com/ControleOnline/cto-mcp/blob/master/agents/agent/devops/agent.md`
12
+
13
+ Esse arquivo central referencia as regras-base de `automation/` no `cto-mcp`. Se este wrapper local divergir do conteúdo canônico do `cto-mcp`, prefira o `cto-mcp`, salvo quando o estado real deste repositório exigir adaptação operacional explícita.
14
+
15
+ ## Contexto local
16
+
17
+ Você está operando no repositório `ControleOnline/ui-common`.
18
+
19
+ Você conhece o ecossistema completo da ControleOnline. Este checkout define o ponto principal de escrita e validação para esta execução, não o limite do seu entendimento sobre o sistema.
20
+
21
+ - Checkout local: `app-community/modules/controleonline/ui-common`
22
+ - Tipo: submódulo de app-community
23
+ - Família: frontend
24
+ - Branch base operacional: `master`
25
+ - Alvo preferencial de PR: `dev`
26
+ - `AGENTS.md` local: presente
27
+
28
+ Leia o `AGENTS.md` mais próximo antes de editar código. Se esta alteração tocar apenas o repositório atual, trabalhe aqui; se também exigir atualização do superprojeto que consome este repositório, registre ou entregue a composição necessária sem perder a separação de ownership.
29
+
30
+ _Arquivo gerado por `cto-mcp/scripts/sync-copilot-agents.mjs`._
@@ -0,0 +1,30 @@
1
+ ---
2
+ name: Quality Assurance
3
+ description: Revisor técnico de entregas do repositório ControleOnline/ui-common, com fonte canônica centralizada no cto-mcp.
4
+ target: github-copilot
5
+ ---
6
+
7
+ ## Fonte canônica
8
+
9
+ Este wrapper é intencionalmente fino. Antes de agir, leia e siga, nesta ordem:
10
+
11
+ 1. `https://github.com/ControleOnline/cto-mcp/blob/master/agents/agent/qa/agent.md`
12
+
13
+ Esse arquivo central referencia as regras-base de `automation/` no `cto-mcp`. Se este wrapper local divergir do conteúdo canônico do `cto-mcp`, prefira o `cto-mcp`, salvo quando o estado real deste repositório exigir adaptação operacional explícita.
14
+
15
+ ## Contexto local
16
+
17
+ Você está operando no repositório `ControleOnline/ui-common`.
18
+
19
+ Você conhece o ecossistema completo da ControleOnline. Este checkout define o ponto principal de escrita e validação para esta execução, não o limite do seu entendimento sobre o sistema.
20
+
21
+ - Checkout local: `app-community/modules/controleonline/ui-common`
22
+ - Tipo: submódulo de app-community
23
+ - Família: frontend
24
+ - Branch base operacional: `master`
25
+ - Alvo preferencial de PR: `dev`
26
+ - `AGENTS.md` local: presente
27
+
28
+ Leia o `AGENTS.md` mais próximo antes de editar código. Se esta alteração tocar apenas o repositório atual, trabalhe aqui; se também exigir atualização do superprojeto que consome este repositório, registre ou entregue a composição necessária sem perder a separação de ownership.
29
+
30
+ _Arquivo gerado por `cto-mcp/scripts/sync-copilot-agents.mjs`._
@@ -0,0 +1,30 @@
1
+ ---
2
+ name: Security
3
+ description: Revisor de segurança do repositório ControleOnline/ui-common, com fonte canônica centralizada no cto-mcp.
4
+ target: github-copilot
5
+ ---
6
+
7
+ ## Fonte canônica
8
+
9
+ Este wrapper é intencionalmente fino. Antes de agir, leia e siga, nesta ordem:
10
+
11
+ 1. `https://github.com/ControleOnline/cto-mcp/blob/master/agents/agent/security/agent.md`
12
+
13
+ Esse arquivo central referencia as regras-base de `automation/` no `cto-mcp`. Se este wrapper local divergir do conteúdo canônico do `cto-mcp`, prefira o `cto-mcp`, salvo quando o estado real deste repositório exigir adaptação operacional explícita.
14
+
15
+ ## Contexto local
16
+
17
+ Você está operando no repositório `ControleOnline/ui-common`.
18
+
19
+ Você conhece o ecossistema completo da ControleOnline. Este checkout define o ponto principal de escrita e validação para esta execução, não o limite do seu entendimento sobre o sistema.
20
+
21
+ - Checkout local: `app-community/modules/controleonline/ui-common`
22
+ - Tipo: submódulo de app-community
23
+ - Família: frontend
24
+ - Branch base operacional: `master`
25
+ - Alvo preferencial de PR: `dev`
26
+ - `AGENTS.md` local: presente
27
+
28
+ Leia o `AGENTS.md` mais próximo antes de editar código. Se esta alteração tocar apenas o repositório atual, trabalhe aqui; se também exigir atualização do superprojeto que consome este repositório, registre ou entregue a composição necessária sem perder a separação de ownership.
29
+
30
+ _Arquivo gerado por `cto-mcp/scripts/sync-copilot-agents.mjs`._
@@ -0,0 +1,35 @@
1
+ name: Publish Package to npmjs
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - master
7
+
8
+ jobs:
9
+ publish:
10
+ runs-on: ubuntu-latest
11
+ permissions:
12
+ contents: read
13
+ id-token: write
14
+ steps:
15
+ - uses: actions/checkout@v5
16
+ with:
17
+ fetch-depth: 2
18
+
19
+ - uses: actions/setup-node@v4
20
+ with:
21
+ node-version: '20.x'
22
+ registry-url: 'https://registry.npmjs.org'
23
+ scope: '@controleonline'
24
+
25
+ - run: npm install
26
+ - run: npm whoami || true
27
+ - run: |
28
+ rm -f ~/.npmrc
29
+ rm -f .npmrc
30
+ - run: |
31
+ CURRENT=$(node -p "require('./package.json').version")
32
+ PREVIOUS=$(git show HEAD~1:package.json | node -p "JSON.parse(require('fs').readFileSync(0)).version")
33
+ [ "$CURRENT" = "$PREVIOUS" ] && exit 0 || true
34
+
35
+ - run: npm publish --provenance --access public
@@ -0,0 +1,19 @@
1
+ name: Pull Request Checks
2
+
3
+ on:
4
+ pull_request:
5
+ push:
6
+ branches-ignore:
7
+ - master
8
+
9
+ jobs:
10
+ tests:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v5
14
+
15
+ - uses: actions/setup-node@v4
16
+ with:
17
+ node-version: '20.x'
18
+
19
+ - run: npm test
@@ -0,0 +1,24 @@
1
+ checks:
2
+ javascript: true
3
+
4
+ build:
5
+ nodes:
6
+ analysis:
7
+ environment:
8
+ node: v16
9
+ project_setup:
10
+ override: true
11
+ tests:
12
+ override:
13
+ - js-scrutinizer-run
14
+ - command: npm run test:coverage
15
+ coverage:
16
+ file: coverage/clover.xml
17
+ format: clover
18
+
19
+ filter:
20
+ excluded_paths:
21
+ - "build/*"
22
+ - "coverage/*"
23
+ - "dist/*"
24
+ - "node_modules/*"
package/FUNDING.yml ADDED
@@ -0,0 +1 @@
1
+ github: [controleonline]
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@controleonline/ui-common",
3
+ "version": "1.2.70",
4
+ "author": "ControleOnline",
5
+ "description": "ControleOnline Common Quasar UI Component",
6
+ "license": "MIT",
7
+ "main": "src/react/index.js",
8
+ "scripts": {
9
+ "test": "npm run test:imports-status && npm run test:runtime-language && npm run test:runtime-footer && npm run test:invoice-presentation",
10
+ "test:imports-status": "mkdir -p node_modules/@controleonline && ln -sfn ../.. node_modules/@controleonline/ui-common && node --test src/tests/react/utils/importStatus.test.js",
11
+ "test:runtime-language": "node --test src/tests/react/utils/runtimeLanguage.test.js",
12
+ "test:runtime-footer": "node --test src/tests/react/utils/runtimeFooter.test.js",
13
+ "test:invoice-presentation": "node --test src/tests/react/utils/invoicePresentation.test.mjs",
14
+ "test:coverage": "c8 --reporter=clover --report-dir coverage npm test"
15
+ },
16
+ "devDependencies": {
17
+ "c8": "^10.1.3"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "https://github.com/ControleOnline/ui-common.git"
22
+ },
23
+ "bugs": "",
24
+ "homepage": "https://www.controleonline.com/devs/plugins",
25
+ "browserslist": [
26
+ "last 1 version, not dead, ie >= 11"
27
+ ]
28
+ }
@@ -0,0 +1,74 @@
1
+ import { APP_ENV } from "../../../../../config/env.js";
2
+ import resolveSystemErrorMessage from '@controleonline/ui-common/src/react/utils/systemErrorMessage';
3
+ import {resolveApiEntryPoint} from '@controleonline/ui-common/src/utils/apiEntryPoint';
4
+
5
+ const buildHttpError = (response, body) => {
6
+ const message =
7
+ resolveSystemErrorMessage(body) ||
8
+ String(response.statusText || 'Request failed');
9
+
10
+ return {
11
+ message: message || 'Request failed',
12
+ code: response.status,
13
+ status: response.status,
14
+ body,
15
+ };
16
+ };
17
+
18
+ const readResponseBody = async (response, responseType) => {
19
+ if (responseType === 'text') {
20
+ return response.text();
21
+ }
22
+
23
+ const text = await response.text();
24
+ if (!text) {
25
+ return null;
26
+ }
27
+
28
+ try {
29
+ return JSON.parse(text);
30
+ } catch (error) {
31
+ return text;
32
+ }
33
+ };
34
+
35
+ export default function (resourceEndpoint, options = {}) {
36
+ const apiEntryPoint = resolveApiEntryPoint(APP_ENV.API_ENTRYPOINT);
37
+ const entryPoint =
38
+ apiEntryPoint + (apiEntryPoint.endsWith("/") ? "" : "/");
39
+
40
+ if (!resourceEndpoint || !entryPoint) return;
41
+
42
+ // if (resourceEndpoint == "/people/companies/my")
43
+ //console.log(entryPoint, resourceEndpoint, options);
44
+
45
+ //console.log(entryPoint, resourceEndpoint);
46
+
47
+ return fetch(new URL(resourceEndpoint, entryPoint), options).then(async response => {
48
+ const body = await readResponseBody(response, options.responseType);
49
+
50
+ if (options.method == "DELETE") {
51
+ if (!response.ok) {
52
+ throw buildHttpError(response, body);
53
+ }
54
+
55
+ return;
56
+ }
57
+
58
+ if (!response.ok) {
59
+ throw buildHttpError(response, body);
60
+ }
61
+
62
+ if (options.responseType == "text") {
63
+ return body;
64
+ }
65
+
66
+ if (body && typeof body === 'object') {
67
+ if (body["@type"] == "Error" || body["@type"] == "ConstraintViolationList") {
68
+ throw buildHttpError(response, body);
69
+ }
70
+ }
71
+
72
+ return body;
73
+ });
74
+ }
@@ -0,0 +1,155 @@
1
+ import myFetch from '@controleonline/ui-common/src/api/fetch';
2
+ import axios from 'axios';
3
+ import { APP_ENV } from '../../../../../config/env';
4
+ import { resolveAppDomain } from '@controleonline/ui-common/src/utils/appDomain';
5
+ import { resolveApiEntryPoint } from '@controleonline/ui-common/src/utils/apiEntryPoint';
6
+
7
+ const MIME_TYPE = 'application/ld+json';
8
+
9
+ export const api = {
10
+ device: JSON.parse(localStorage.getItem('device') || '{}'),
11
+ masterDevice: JSON.parse(localStorage.getItem('master-device') || '{}'),
12
+
13
+
14
+ upload: async function (uri, formData) {
15
+ const token = await this.getToken();
16
+ const appDomain = resolveAppDomain(APP_ENV.DOMAIN);
17
+ const apiEntryPoint = resolveApiEntryPoint(APP_ENV.API_ENTRYPOINT);
18
+ const entryPoint = apiEntryPoint + (apiEntryPoint.endsWith("/") ? "" : "/");
19
+ const url = new URL(uri.startsWith('/') ? uri.substring(1) : uri, entryPoint).href;
20
+
21
+ return axios.post(url, formData, {
22
+ headers: {
23
+ 'API-TOKEN': token,
24
+ 'App-Domain': appDomain,
25
+ 'Accept': '*/*',
26
+ // IMPORTANTE: Deixe vazio para o Axios/Browser definir o boundary do multipart
27
+ }
28
+ });
29
+ },
30
+ fetch: async function (uri, options = {}) {
31
+ if (typeof options.headers === 'undefined')
32
+ Object.assign(options, { headers: new Headers() });
33
+
34
+ // Always refresh device from localStorage in case it was set after module load
35
+ try {
36
+ this.device = JSON.parse(localStorage.getItem('device') || '{}');
37
+ } catch (e) {
38
+ this.device = {};
39
+ }
40
+
41
+ try {
42
+ this.masterDevice = JSON.parse(
43
+ localStorage.getItem('master-device') || '{}',
44
+ );
45
+ } catch (e) {
46
+ this.masterDevice = {};
47
+ }
48
+
49
+ let token = await this.getToken();
50
+ if (token) options.headers.set('API-TOKEN', token);
51
+
52
+ let bodyDeviceId = null;
53
+ if (options.body) {
54
+ if (typeof options.body === 'object') {
55
+ bodyDeviceId = options.body.device || null;
56
+ } else if (typeof options.body === 'string') {
57
+ try {
58
+ const parsedBody = JSON.parse(options.body);
59
+ bodyDeviceId = parsedBody?.device || null;
60
+ } catch (e) {
61
+ bodyDeviceId = null;
62
+ }
63
+ }
64
+ }
65
+
66
+ const headerDeviceId =
67
+ this.masterDevice?.id || this.device?.id || bodyDeviceId;
68
+ if (headerDeviceId) options.headers.set('DEVICE', headerDeviceId);
69
+ if (options.responseType != 'text') {
70
+ options.headers.set('Content-Type', MIME_TYPE);
71
+ options.headers.set('Accept', MIME_TYPE);
72
+ }
73
+ options.headers.set('App-Domain', resolveAppDomain(APP_ENV.DOMAIN));
74
+
75
+ if (options.body && typeof options.body != 'string') {
76
+ options.body = JSON.stringify(options.body);
77
+ }
78
+ if (options.params) {
79
+ uri = this.buildQueryString(uri, options);
80
+ }
81
+ return myFetch(uri, options).catch(e => {
82
+ throw e;
83
+ });
84
+ },
85
+ async getToken() {
86
+ const sessionString = localStorage.getItem('session');
87
+ let session = null;
88
+ if (sessionString) {
89
+ try {
90
+ const cleanString =
91
+ typeof sessionString == 'string' &&
92
+ sessionString.startsWith('__q_objt|')
93
+ ? sessionString.substring('__q_objt|'.length)
94
+ : sessionString;
95
+ session = JSON.parse(cleanString); // Transforma a string em objeto
96
+ } catch (e) {
97
+ console.error('Failed to parse session from localStorage', e);
98
+ }
99
+ }
100
+
101
+ return session?.token || session?.api_key;
102
+ },
103
+ serialize(obj, prefix = '') {
104
+ const pairs = [];
105
+
106
+ for (const key in obj) {
107
+ if (obj.hasOwnProperty(key)) {
108
+ const value = obj[key];
109
+ let fullKey = prefix ? `${prefix}.${key}` : key; // Usa ponto para objetos
110
+
111
+ if (value === null || value === undefined) {
112
+ pairs.push(`${fullKey}=`);
113
+ } else if (typeof value === 'object' && !Array.isArray(value)) {
114
+ // Objeto aninhado: chama serialize recursivamente com ponto
115
+ pairs.push(...this.serialize(value, fullKey));
116
+ } else if (Array.isArray(value)) {
117
+ // Array: adiciona [] e itera sobre os valores
118
+ if (value.length === 0) {
119
+ pairs.push(`${fullKey}[]=`);
120
+ } else {
121
+ value.forEach(val => {
122
+ if (typeof val === 'object' && val !== null) {
123
+ pairs.push(...this.serialize(val, `${fullKey}[]`));
124
+ } else {
125
+ pairs.push(`${fullKey}[]=${encodeURIComponent(val)}`);
126
+ }
127
+ });
128
+ }
129
+ } else {
130
+ // Valor simples
131
+ pairs.push(`${fullKey}=${encodeURIComponent(value)}`);
132
+ }
133
+ }
134
+ }
135
+ return pairs;
136
+ },
137
+
138
+ buildQueryString(uri, options) {
139
+ if (options.params) {
140
+ const params = this.serialize(options.params);
141
+ uri = `${uri}?${params.join('&')}`;
142
+ }
143
+ return uri;
144
+ },
145
+ post: async function (uri, body = {}) {
146
+ const options = {
147
+ method: 'POST',
148
+ body: body,
149
+ };
150
+ return await this.fetch(uri, options);
151
+ },
152
+ execute: function (params) {
153
+ return axios(params);
154
+ },
155
+ };
@@ -0,0 +1,131 @@
1
+ import { openDB } from "idb";
2
+
3
+ const DB_NAME = "ControleOnline";
4
+
5
+ export default class localDB {
6
+ constructor(state) {
7
+ this.state = state;
8
+
9
+ this.checkAndGetDB();
10
+ }
11
+
12
+ async initDB() {
13
+ let dbPromise = openDB(DB_NAME, this.currentVersion, {
14
+ upgrade: (db) => {
15
+ if (!db.objectStoreNames.contains(this.state.resourceEndpoint)) {
16
+ const store = db.createObjectStore(this.state.resourceEndpoint, {
17
+ keyPath: "id",
18
+ });
19
+ this.state.columns
20
+ .filter((col) => col.sortable || col.externalFilter === false)
21
+ .forEach((col) => {
22
+ store.createIndex(col.name, col.name, { unique: false });
23
+ });
24
+ }
25
+ },
26
+ });
27
+ return dbPromise;
28
+ }
29
+
30
+ async getCurrentVersion() {
31
+ // Obtém a versão atual do banco de dados
32
+ return new Promise((resolve) => {
33
+ const request = indexedDB.open(DB_NAME);
34
+ request.onsuccess = () => {
35
+ const db = request.result;
36
+ const currentVersion = db.currentVersion;
37
+ db.close();
38
+ resolve(currentVersion);
39
+ this.currentVersion = currentVersion;
40
+ };
41
+ request.onerror = () => resolve(1);
42
+ });
43
+ }
44
+
45
+ async checkAndGetDB() {
46
+ return this.getCurrentVersion().then(() => {
47
+ return this.initDB().then((db) => {
48
+ if (!this.storeExists()) {
49
+ this.currentVersion = db.currentVersion + 1;
50
+ db.close();
51
+ return this.initDB();
52
+ }
53
+ return db;
54
+ });
55
+ });
56
+ }
57
+
58
+ async storeExists() {
59
+ return this.checkAndGetDB().then((db) => {
60
+ return db.objectStoreNames.contains(this.state.resourceEndpoint);
61
+ });
62
+ }
63
+
64
+ async getAll() {
65
+ if (!(await this.storeExists())) {
66
+ return null;
67
+ }
68
+ const db = await this.checkAndGetDB();
69
+ return db.getAll(this.state.resourceEndpoint);
70
+ }
71
+
72
+ async getItemsByColumn(columnName, value) {
73
+ if (!(await this.storeExists())) {
74
+ return null;
75
+ }
76
+ const db = await this.checkAndGetDB();
77
+ const tx = db.transaction(this.state.resourceEndpoint, "readonly");
78
+ const store = tx.objectStore(this.state.resourceEndpoint);
79
+ const index = store.index(columnName);
80
+ const results = await index.getAll(value);
81
+ await tx.done;
82
+ return results;
83
+ }
84
+
85
+ async get(id) {
86
+ if (!(await this.storeExists())) {
87
+ return null;
88
+ }
89
+ const db = await this.checkAndGetDB();
90
+ return db.get(this.state.resourceEndpoint, id);
91
+ }
92
+
93
+ async saveItems(items) {
94
+ const db = await this.checkAndGetDB();
95
+ const tx = db.transaction(this.state.resourceEndpoint, "readwrite");
96
+ const store = tx.objectStore(this.state.resourceEndpoint);
97
+ await Promise.all(items.map((item) => store.put(item)));
98
+ await tx.done;
99
+ }
100
+
101
+ async saveItem(item) {
102
+ const db = await this.checkAndGetDB();
103
+ return db.put(this.state.resourceEndpoint, item);
104
+ }
105
+
106
+ async getItemsByFilters() {
107
+ if (!(await this.storeExists())) {
108
+ return null;
109
+ }
110
+ const db = await this.checkAndGetDB();
111
+ if (Object.keys(this.state.filters).length === 0) {
112
+ return this.getAll();
113
+ }
114
+
115
+ const filterPromises = Object.entries(this.state.filters).map(
116
+ async ([key, value]) => {
117
+ const column = this.state.columns.find((col) => col.name === key);
118
+ if (column && (column.sortable || column.externalFilter === false)) {
119
+ return this.getItemsByColumn(key, value);
120
+ }
121
+ return null;
122
+ }
123
+ );
124
+
125
+ const filterResults = await Promise.all(filterPromises);
126
+ return filterResults.reduce((acc, curr) => {
127
+ if (!acc || acc.length === 0) return curr;
128
+ return acc.filter((item) => curr.some((result) => result.id === item.id));
129
+ }, []);
130
+ }
131
+ }
@@ -0,0 +1,66 @@
1
+ class Queue {
2
+ constructor() {
3
+ this.queue = [];
4
+ this.isProcessing = false;
5
+ this.timeout = [];
6
+ this.onFinish = null;
7
+ }
8
+ addToQueue(func) {
9
+ this.queue.push(func);
10
+ }
11
+ executeQueue(func, callback) {
12
+ this.addToQueue(func);
13
+ this.initQueue(callback);
14
+ }
15
+
16
+ execute(func, id, wait = 10) {
17
+ const debounced = function (...args) {
18
+ clearTimeout(this.timeout[id]);
19
+ this.timeout[id] = setTimeout(() => {
20
+ this.addToQueue(() => func(...args));
21
+ }, wait);
22
+ };
23
+
24
+ debounced.cancel = id => {
25
+ clearTimeout(this.timeout[id]);
26
+ };
27
+ return debounced;
28
+ }
29
+
30
+ finalize = () => {
31
+ if (this.onFinish && typeof this.onFinish == 'function') this.onFinish();
32
+ this.isProcessing = false;
33
+ this.onFinish = null;
34
+ };
35
+
36
+ processQueue() {
37
+ if (this.queue.length === 0) return this.finalize();
38
+ else this.isProcessing = true;
39
+
40
+ if (this.isProcessing === false) return;
41
+
42
+ const func = this.queue[0];
43
+
44
+ return func()
45
+ .then(() => {
46
+ this.queue.shift();
47
+ return this.processQueue();
48
+ })
49
+ .catch(error => {
50
+ console.log(
51
+ 'Erro ao processar a fila. Nova tentativa em 5 segundos',
52
+ error,
53
+ );
54
+
55
+ setTimeout(() => {
56
+ return this.processQueue();
57
+ }, 10);
58
+ });
59
+ }
60
+ initQueue(callback) {
61
+ if (typeof callback == 'function') this.onFinish = callback;
62
+ if (this.isProcessing === true) return;
63
+ this.processQueue();
64
+ }
65
+ }
66
+ export const queue = new Queue();
Binary file