Compare commits
31 Commits
2f4767ce02
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e26b98824 | ||
|
|
1ff582f60a | ||
|
|
7a9a782513 | ||
|
|
2c97b34f0f | ||
|
|
c0dfd700a0 | ||
|
|
aaa5871292 | ||
|
|
8f557b0581 | ||
|
|
4fbebd08de | ||
|
|
09bfc92e1c | ||
|
|
57dff9f819 | ||
|
|
7759186234 | ||
|
|
3578697d60 | ||
|
|
6345aac22e | ||
|
|
3c97bab0df | ||
|
|
274c3ce542 | ||
|
|
ec48078f1a | ||
|
|
554a34f8b1 | ||
|
|
824a64b22a | ||
|
|
9dcb30fd24 | ||
|
|
4595e81798 | ||
|
|
5b04ab0b36 | ||
|
|
7bd134ed8d | ||
|
|
a0a541e387 | ||
|
|
654e1754ab | ||
|
|
7a5784831c | ||
|
|
94c863484c | ||
|
|
2b6ec33837 | ||
|
|
1cb8578e9b | ||
|
|
8f802d551f | ||
|
|
54a1fe669a | ||
|
|
aeee13a0bd |
18
.agents/AGENTS.md
Normal file
18
.agents/AGENTS.md
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
# Diretrizes do Projeto - Gestão de Manutenção
|
||||||
|
|
||||||
|
## Leitura Obrigatória da Documentação
|
||||||
|
- **Consulta Prévia**: Antes de planejar, pesquisar ou implementar qualquer alteração, a IA deve sempre consultar a documentação relevante contida no diretório [`documentacao/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/documentacao) (como [`arquitetura_do_sistema.md`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/documentacao/arquitetura/arquitetura_do_sistema.md), [`fluxo_de_dados_e_sincronizacao.md`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/documentacao/fluxo_de_dados_e_sincronizacao.md), [`recursos_simulados_e_truncados.md`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/documentacao/recursos_simulados_e_truncados.md)) e no [`README.md`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/README.md).
|
||||||
|
- **Alinhamento Arquitetural**: Certifique-se de compreender os padrões arquiteturais offline-first, sincronização, modelos de dados e restrições descritas na documentação antes de propor ou alterar o código.
|
||||||
|
|
||||||
|
## Atualização Pós-Modificação
|
||||||
|
- **Manutenção da Documentação**: Sempre que forem feitas modificações importantes no código (ex.: novas funcionalidades, refatoração de arquitetura, novos fluxos de sincronização, alterações em modelos de dados ou Room DAO/Database, adição de configurações), a IA deve obrigatoriamente atualizar os documentos correspondentes no diretório [`documentacao/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/documentacao) ou no [`README.md`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/README.md).
|
||||||
|
- **Sincronia Código x Docs**: A documentação deve refletir com exatidão as mudanças realizadas para evitar inconsistências e garantir a evolução contínua do projeto.
|
||||||
|
|
||||||
|
## Controle de Versionamento Obrigatório e Atualização do Changelog
|
||||||
|
- **Incremento de Versão e Registros no Changelog**: Sempre que for feita qualquer modificação no código-fonte, correções de bugs, refatoração ou adição de novas funcionalidades no software, a IA deve **obrigatoriamente incrementar a versão do aplicativo** e atualizar o histórico no arquivo [`CHANGELOG.md`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/CHANGELOG.md).
|
||||||
|
- **Lista de Arquivos Obrigatórios a Serem Alterados**:
|
||||||
|
1. [`app/build.gradle.kts`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/build.gradle.kts): Incrementar `versionCode` (ex.: de `2` para `3`) e atualizar `versionName` seguindo o Semantic Versioning (ex.: `1.1.0` -> `1.1.1` para correções/patches ou `1.2.0` para novas funcionalidades).
|
||||||
|
2. [`CHANGELOG.md`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/CHANGELOG.md): Criar o bloco da nova versão com data no formato `## [X.Y.Z] - YYYY-MM-DD` e descrever detalhadamente todas as mudanças nas subseções apropriadas (`### Adicionado`, `### Corrigido`, `### Alterado`, `### Removido`).
|
||||||
|
3. [`app/src/main/java/com/example/util/DeviceUtils.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/util/DeviceUtils.kt): Atualizar as strings padrão de fallback de versão dentro do método `getAppVersion`.
|
||||||
|
4. [`README.md`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/README.md): Atualizar o número da Versão Atual na lista de documentação técnica do projeto.
|
||||||
|
|
||||||
80
CHANGELOG.md
Normal file
80
CHANGELOG.md
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
Todas as alterações notáveis neste projeto serão documentadas neste arquivo.
|
||||||
|
|
||||||
|
O formato é baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.0.0/),
|
||||||
|
e este projeto adere ao [Semantic Versioning](https://semver.org/lang/pt-BR/).
|
||||||
|
## [1.4.0] - 2026-08-07
|
||||||
|
|
||||||
|
### Adicionado
|
||||||
|
- **Exibição da Versão do Aplicativo no Rodapé das Telas**:
|
||||||
|
- Adicionado rodapé visual com a versão dinâmica do software (`DeviceUtils.getAppVersion`) no final da **Tela de Informações Importantes** (`ImportantInfoScreen.kt`).
|
||||||
|
- Adicionado rodapé visual com a versão dinâmica do software no final da **Tela de Configurações** (`SettingsScreen.kt`).
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- **Versão do Aplicativo**: Incrementada a versão para `1.4.0` (com `versionCode = 5`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [1.3.0] - 2026-08-07
|
||||||
|
|
||||||
|
### Adicionado
|
||||||
|
- **Sincronização Automática Periódica em Segundo Plano**:
|
||||||
|
- Implementado loop contínuo no `MaintenanceViewModel` (`viewModelScope`) com intervalo fixo de **5 minutos** (300.000 ms).
|
||||||
|
- Execução global ativa em **qualquer tela do aplicativo** (`Informações`, `Dashboard`, `Ordens` e `Configurações`) através do compartilhamento do ViewModel no escopo da `MainActivity`.
|
||||||
|
- **Card Informativo na Tela de Configurações (`AutoSyncStatusCard`)**:
|
||||||
|
- Adicionado componente visual na Tela de Configurações exibindo o período/frequência de tentativa de sincronização automática (*"A cada 5 minutos"*), a abrangência (*"Ativa em qualquer tela"*), o status da rede/sincronização e o timestamp exato da última sincronização realizada na sessão.
|
||||||
|
- **Registro Detalhado no Histórico de Logs (`AppLogger` / `app_logs`)**:
|
||||||
|
- Gravadas todas as tentativas de sincronização automática e manual no banco de dados local com tags `AutoSync` e `SyncManager` nos níveis de severidade `INFO` (início e sucesso com total de itens e conflitos), `WARN` (cancelado por falta de rede ou app bloqueado) e `ERROR` (falhas e exceções).
|
||||||
|
- Os logs ficam imediatamente disponíveis para auditoria no modal **Histórico de Logs** na tela de Configurações.
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- **Versão do Aplicativo**: Incrementada a versão para `1.3.0` (com `versionCode = 4`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [1.2.0] - 2026-08-07
|
||||||
|
|
||||||
|
### Adicionado
|
||||||
|
- **Trava de Segurança e Bloqueio de Operação (`VersaoMinimaApp` e `PararAcessoApp`)**:
|
||||||
|
- Implementado sistema de verificação de segurança reativo com base nas chaves de configuração `VersaoMinimaApp` e `PararAcessoApp` da aba `config` da planilha online e salvas no banco de dados local Room.
|
||||||
|
- Exibição de **Popup Não Minimizável (Full-Screen Overlay Modal)** em qualquer tela do aplicativo quando a versão do aplicativo for inferior ao valor de `VersaoMinimaApp` ou se `PararAcessoApp` for igual a `1`.
|
||||||
|
- Exibição das mensagens padronizadas de bloqueio e contatos dos responsáveis com botões de ação direta para e-mail (`mailto:`) e cópia para área de transferência:
|
||||||
|
- **Desenvolvedor**: `cesarjhony+dev@gmail.com`
|
||||||
|
- **Responsável**: `gabrielpizzinatto123@gmail.com`
|
||||||
|
- Bloqueio completo de qualquer tentativa de sincronização ou leitura de dados via `MaintenanceRepository` e `MaintenanceViewModel` durante o estado bloqueado.
|
||||||
|
- **Utilitário de Comparação Semântica de Versões (`VersionUtils.kt`)**: Adicionada função de higienização de sufixos de build e comparação numérica de versão semântica (Major, Minor, Patch).
|
||||||
|
- **Testes Automatizados de Segurança**: Adicionados testes unitários e de integração em `VersionUtilsTest.kt`, `AppSecurityTest.kt` e `AppConfigTest.kt`.
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- **Versão do Aplicativo**: Incrementada a versão para `1.2.0` (com `versionCode = 3`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [1.1.0] - 2026-08-07
|
||||||
|
|
||||||
|
### Adicionado
|
||||||
|
- **4º Link Condicional na Tela de Informações**: Suporte dinâmico para leitura e exibição das chaves `Link4` e `DescricaoLink4` da aba `config` da planilha online. O 4º link é exibido **apenas se a chave e seu valor forem encontrados na planilha**, permanecendo oculto caso contrário.
|
||||||
|
- **Seção de Responsáveis pelo Aplicativo**: Adicionada uma nova seção visual na Tela de Informações Importantes exibindo os contatos principais com ação interativa para envio de e-mail:
|
||||||
|
- **Desenvolvedor**: `cesarjhony+dev@gmail.com`
|
||||||
|
- **Responsável**: `gabrielpizzinatto123@gmail.com`
|
||||||
|
- **Testes Unitários**: Adicionada cobertura de testes automatizados para validação da inclusão/ocultação do 4º link (`AppConfigTest.kt`).
|
||||||
|
|
||||||
|
### Corrigido
|
||||||
|
- **Compartilhamento de Fotos**: Correção no visualizador de foto em tela cheia (`FullscreenPhotoViewerDialog`). O aplicativo agora resolve o arquivo físico local `.jpg` armazenado em `filesDir/os_photos/` e gera uma URI segura via `FileProvider` (`type = "image/jpeg"`), corrigindo a falha onde o sistema enviava apenas o texto da rota parcial.
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- **Texto de Status da Tela de Informações**: Atualizada a mensagem de status de conectividade de `"Sincronizado com a planilha online (Aba config)"` para `"Sincronizado com o BD online"`.
|
||||||
|
- **Versão do Aplicativo**: Incrementada a versão do software para `1.1.0` (com `versionCode = 2`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [1.0.0] - 2026-08-01
|
||||||
|
|
||||||
|
### Adicionado
|
||||||
|
- **Versão Inicial Estável**: Lançamento inicial da plataforma de Gestão de Manutenção de Parada (Android).
|
||||||
|
- **Arquitetura Offline-First**: Arquitetura MVVM + Repository Pattern sobre banco de dados local Room SQLite com 7 tabelas principais (`maintenance_activities`, `os_findings`, `os_update_history`, `app_logs`, `sync_conflict_logs`, `user_access`, `app_config`).
|
||||||
|
- **Sincronização Bidirecional com Google Sheets**: Integração com as abas `project`, `history`, `achados`, `config` e `usage_history`.
|
||||||
|
- **Integração com Firebase Storage**: Compactação automática de fotos (<= 500KB) e download de mídias sob demanda (*On-Demand Loading*) para múltiplos dispositivos.
|
||||||
|
- **Painel Analítico e KPIs**: Indicadores globais de progresso industrial, filtros modulares (Setor, Equipe, Status, Data, Recurso) e busca dinâmica.
|
||||||
|
- **Segurança e Auditoria**: Autenticação com Google Sign-In, controle de permissões por e-mail e rastreamento de acessos por dispositivo na aba `usage_history`.
|
||||||
45
README.md
45
README.md
@@ -1,21 +1,38 @@
|
|||||||
<div align="center">
|
# Aplicativo de Gestão de Manutenção de Parada (Android)
|
||||||
<img width="1200" height="475" alt="GHBanner" src="https://ai.google.dev/static/site-assets/images/share-ais-513315318.png" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
# Run and deploy your AI Studio app
|
Aplicativo Android **offline-first** desenvolvido em Kotlin e Jetpack Compose para gerenciamento, acompanhamento e auditoria de Ordens de Serviço (OS) em plantas industriais.
|
||||||
|
|
||||||
This contains everything you need to run your app locally.
|
---
|
||||||
|
|
||||||
View your app in AI Studio: https://ai.studio/apps/d5626d9c-db6d-4067-9ba1-e80d37ea164f
|
## 📚 Documentação Técnica do Projeto
|
||||||
|
|
||||||
## Run Locally
|
- **[Documentação de Fluxo de Dados, Salvamento e Sincronização](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/documentacao/fluxo_de_dados_e_sincronizacao.md)**:
|
||||||
|
- Estrutura completa das 7 tabelas do banco de dados local Room (`maintenance_activities`, `os_findings`, `os_update_history`, `app_logs`, `sync_conflict_logs`, `user_access`, `app_config`).
|
||||||
|
- Fluxo detalhado de salvamento de progresso e achados com tipo exclusivo `FOTO`.
|
||||||
|
- Processo de compactação (<= 500KB) e upload para Firebase Storage.
|
||||||
|
- Sincronização bidirecional com Google Sheets (abas `project`, `history`, `achados`, `config` e `usage_history`).
|
||||||
|
- Sincronização de links úteis da aba `config` para a Tela de Informações Importantes (posicionada à esquerda do Dashboard).
|
||||||
|
- Rastreamento em tempo real do último acesso por dispositivo, e-mail de Google Sign-In e versão do sistema na aba `usage_history`.
|
||||||
|
- Carregamento e download de fotos **sob demanda** (On-Demand Loading) para múltiplos celulares sem erros HTTP 403.
|
||||||
|
|
||||||
**Prerequisites:** [Android Studio](https://developer.android.com/studio)
|
- **[Changelog / Histórico de Versões](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/CHANGELOG.md)**:
|
||||||
|
- Registro de alterações por versão (Versão Atual: **`1.4.0`** - `versionCode 5`).
|
||||||
|
|
||||||
|
- **[Arquitetura do Sistema](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/documentacao/arquitetura/arquitetura_do_sistema.md)**:
|
||||||
|
- Diagramas de arquitetura MVVM + Repository Pattern.
|
||||||
|
- Mapeamento de componentes Compose, ViewModel e Room DAO.
|
||||||
|
- Algoritmo de reconciliação de dados e auditoria transacional.
|
||||||
|
|
||||||
1. Open Android Studio
|
---
|
||||||
2. Select **Open** and choose the directory containing this project
|
|
||||||
3. Allow Android Studio to fix any incompatibilities as it imports the project.
|
## 🚀 Como Executar o Projeto
|
||||||
4. Create a file named `.env` in the project directory and set `GEMINI_API_KEY` in that file to your Gemini API key (see `.env.example` for an example)
|
|
||||||
5. Remove this line from the app's `build.gradle.kts` file: `signingConfig = signingConfigs.getByName("debugConfig")`
|
**Pré-requisitos:** [Android Studio](https://developer.android.com/studio) / JDK 17+
|
||||||
6. Run the app on an emulator or physical device
|
|
||||||
|
1. Abra o Android Studio.
|
||||||
|
2. Selecione **Open** e escolha a pasta deste projeto (`gestao_de_manutencao`).
|
||||||
|
3. Execute os testes unitários via linha de comando ou terminal do estúdio:
|
||||||
|
```bash
|
||||||
|
./gradle_9_3_1/gradle-9.3.1/bin/gradle test
|
||||||
|
```
|
||||||
|
4. Execute o aplicativo em um emulador ou dispositivo físico Android.
|
||||||
|
|||||||
@@ -14,11 +14,11 @@ android {
|
|||||||
compileSdk { version = release(36) { minorApiLevel = 1 } }
|
compileSdk { version = release(36) { minorApiLevel = 1 } }
|
||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
applicationId = "com.aistudio.cargillparadaos.xvyzwt"
|
applicationId = "com.aistudio.gestaoparadaos.xvyzwt"
|
||||||
minSdk = 24
|
minSdk = 24
|
||||||
targetSdk = 36
|
targetSdk = 36
|
||||||
versionCode = 1
|
versionCode = 5
|
||||||
versionName = "1.0"
|
versionName = "1.4.0"
|
||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,43 @@
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"client_info": {
|
||||||
|
"mobilesdk_app_id": "1:461441632355:android:a6f984af1b42521aee5056",
|
||||||
|
"android_client_info": {
|
||||||
|
"package_name": "com.aistudio.gestaoparadaos.xvyzwt"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"oauth_client": [
|
||||||
|
{
|
||||||
|
"client_id": "461441632355-br45iqlv0epgagm3mnrkj8qgak0rgo2o.apps.googleusercontent.com",
|
||||||
|
"client_type": 1,
|
||||||
|
"android_info": {
|
||||||
|
"package_name": "com.aistudio.gestaoparadaos.xvyzwt",
|
||||||
|
"certificate_hash": "6274d8aa0709c0454af47340ae8f223b8a0fbd61"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"client_id": "461441632355-dc85s9u8dctltfbounegv020qn5aj49d.apps.googleusercontent.com",
|
||||||
|
"client_type": 3
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"api_key": [
|
||||||
|
{
|
||||||
|
"current_key": "AIzaSyAB3uaasLqLgB-Ir5NvzUkVo6wSuQPQtTU"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"services": {
|
||||||
|
"appinvite_service": {
|
||||||
|
"other_platform_oauth_client": [
|
||||||
|
{
|
||||||
|
"client_id": "461441632355-dc85s9u8dctltfbounegv020qn5aj49d.apps.googleusercontent.com",
|
||||||
|
"client_type": 3
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"configuration_version": "1"
|
"configuration_version": "1"
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
|
|
||||||
<application
|
<application
|
||||||
|
android:name=".MainApplication"
|
||||||
android:allowBackup="true"
|
android:allowBackup="true"
|
||||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||||
android:fullBackupContent="@xml/backup_rules"
|
android:fullBackupContent="@xml/backup_rules"
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import androidx.compose.foundation.layout.padding
|
|||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Assignment
|
import androidx.compose.material.icons.filled.Assignment
|
||||||
import androidx.compose.material.icons.filled.Dashboard
|
import androidx.compose.material.icons.filled.Dashboard
|
||||||
|
import androidx.compose.material.icons.filled.Info
|
||||||
import androidx.compose.material.icons.filled.Settings
|
import androidx.compose.material.icons.filled.Settings
|
||||||
import androidx.compose.material3.*
|
import androidx.compose.material3.*
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
@@ -25,11 +26,14 @@ import androidx.navigation.compose.rememberNavController
|
|||||||
import com.example.data.local.AppDatabase
|
import com.example.data.local.AppDatabase
|
||||||
import com.example.data.repository.MaintenanceRepository
|
import com.example.data.repository.MaintenanceRepository
|
||||||
import com.example.ui.screens.AnalyticsScreen
|
import com.example.ui.screens.AnalyticsScreen
|
||||||
|
import com.example.ui.screens.ImportantInfoScreen
|
||||||
import com.example.ui.screens.MaintenanceDashboardScreen
|
import com.example.ui.screens.MaintenanceDashboardScreen
|
||||||
import com.example.ui.screens.SettingsScreen
|
import com.example.ui.screens.SettingsScreen
|
||||||
import com.example.ui.theme.BrandGreen
|
import com.example.ui.theme.BrandGreen
|
||||||
import com.example.ui.theme.BrandLightGreen
|
import com.example.ui.theme.BrandLightGreen
|
||||||
import com.example.ui.theme.MyApplicationTheme
|
import com.example.ui.theme.MyApplicationTheme
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import com.example.ui.components.AppSecurityLockDialog
|
||||||
import com.example.ui.viewmodel.MaintenanceViewModel
|
import com.example.ui.viewmodel.MaintenanceViewModel
|
||||||
import com.example.ui.viewmodel.MaintenanceViewModelFactory
|
import com.example.ui.viewmodel.MaintenanceViewModelFactory
|
||||||
|
|
||||||
@@ -51,12 +55,44 @@ class MainActivity : ComponentActivity() {
|
|||||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||||
val currentRoute = navBackStackEntry?.destination?.route
|
val currentRoute = navBackStackEntry?.destination?.route
|
||||||
|
|
||||||
|
val securityState by viewModel.appSecurityState.collectAsStateWithLifecycle()
|
||||||
|
val isRefreshingConfig by viewModel.isRefreshingConfig.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
AppSecurityLockDialog(
|
||||||
|
securityState = securityState,
|
||||||
|
isRefreshing = isRefreshingConfig,
|
||||||
|
onRetryCheck = { viewModel.checkSecurityConfigNow() }
|
||||||
|
)
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
bottomBar = {
|
bottomBar = {
|
||||||
NavigationBar(
|
NavigationBar(
|
||||||
containerColor = Color.White,
|
containerColor = Color.White,
|
||||||
modifier = Modifier.shadow(8.dp)
|
modifier = Modifier.shadow(8.dp)
|
||||||
) {
|
) {
|
||||||
|
// Tab 0: Informações Importantes (Página de Links)
|
||||||
|
NavigationBarItem(
|
||||||
|
selected = currentRoute == "info",
|
||||||
|
onClick = {
|
||||||
|
if (currentRoute != "info") {
|
||||||
|
navController.navigate("info") {
|
||||||
|
popUpTo(navController.graph.startDestinationId) { saveState = true }
|
||||||
|
launchSingleTop = true
|
||||||
|
restoreState = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
icon = { Icon(Icons.Default.Info, contentDescription = "Informações") },
|
||||||
|
label = { Text("Informações", fontSize = 10.sp) },
|
||||||
|
colors = NavigationBarItemDefaults.colors(
|
||||||
|
selectedIconColor = BrandGreen,
|
||||||
|
selectedTextColor = BrandGreen,
|
||||||
|
unselectedIconColor = Color.Gray,
|
||||||
|
unselectedTextColor = Color.Gray,
|
||||||
|
indicatorColor = BrandLightGreen
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
// Tab 1: Dashboard (Stub)
|
// Tab 1: Dashboard (Stub)
|
||||||
NavigationBarItem(
|
NavigationBarItem(
|
||||||
selected = currentRoute == "dashboard",
|
selected = currentRoute == "dashboard",
|
||||||
@@ -70,7 +106,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
icon = { Icon(Icons.Default.Dashboard, contentDescription = "Dashboard") },
|
icon = { Icon(Icons.Default.Dashboard, contentDescription = "Dashboard") },
|
||||||
label = { Text("Dashboard", fontSize = 11.sp) },
|
label = { Text("Dashboard", fontSize = 10.sp) },
|
||||||
colors = NavigationBarItemDefaults.colors(
|
colors = NavigationBarItemDefaults.colors(
|
||||||
selectedIconColor = BrandGreen,
|
selectedIconColor = BrandGreen,
|
||||||
selectedTextColor = BrandGreen,
|
selectedTextColor = BrandGreen,
|
||||||
@@ -93,7 +129,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
icon = { Icon(Icons.Default.Assignment, contentDescription = "Ordens") },
|
icon = { Icon(Icons.Default.Assignment, contentDescription = "Ordens") },
|
||||||
label = { Text("Ordens", fontSize = 11.sp) },
|
label = { Text("Ordens", fontSize = 10.sp) },
|
||||||
colors = NavigationBarItemDefaults.colors(
|
colors = NavigationBarItemDefaults.colors(
|
||||||
selectedIconColor = BrandGreen,
|
selectedIconColor = BrandGreen,
|
||||||
selectedTextColor = BrandGreen,
|
selectedTextColor = BrandGreen,
|
||||||
@@ -116,7 +152,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
icon = { Icon(Icons.Default.Settings, contentDescription = "Configurações") },
|
icon = { Icon(Icons.Default.Settings, contentDescription = "Configurações") },
|
||||||
label = { Text("Configurações", fontSize = 11.sp) },
|
label = { Text("Configurações", fontSize = 10.sp) },
|
||||||
colors = NavigationBarItemDefaults.colors(
|
colors = NavigationBarItemDefaults.colors(
|
||||||
selectedIconColor = BrandGreen,
|
selectedIconColor = BrandGreen,
|
||||||
selectedTextColor = BrandGreen,
|
selectedTextColor = BrandGreen,
|
||||||
@@ -134,6 +170,11 @@ class MainActivity : ComponentActivity() {
|
|||||||
startDestination = "ordens",
|
startDestination = "ordens",
|
||||||
modifier = Modifier.padding(bottom = innerPadding.calculateBottomPadding())
|
modifier = Modifier.padding(bottom = innerPadding.calculateBottomPadding())
|
||||||
) {
|
) {
|
||||||
|
composable("info") {
|
||||||
|
ImportantInfoScreen(
|
||||||
|
viewModel = viewModel
|
||||||
|
)
|
||||||
|
}
|
||||||
composable("dashboard") {
|
composable("dashboard") {
|
||||||
AnalyticsScreen(
|
AnalyticsScreen(
|
||||||
viewModel = viewModel,
|
viewModel = viewModel,
|
||||||
|
|||||||
112
app/src/main/java/com/example/MainApplication.kt
Normal file
112
app/src/main/java/com/example/MainApplication.kt
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
package com.example
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import coil.ImageLoader
|
||||||
|
import coil.ImageLoaderFactory
|
||||||
|
import coil.disk.DiskCache
|
||||||
|
import coil.memory.MemoryCache
|
||||||
|
import coil.request.CachePolicy
|
||||||
|
import com.example.util.AppLogger
|
||||||
|
import okhttp3.Interceptor
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.Response
|
||||||
|
import java.io.IOException
|
||||||
|
import java.util.Random
|
||||||
|
|
||||||
|
class MainApplication : Application(), ImageLoaderFactory {
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun newImageLoader(): ImageLoader {
|
||||||
|
val okHttpClient = OkHttpClient.Builder()
|
||||||
|
.retryOnConnectionFailure(true)
|
||||||
|
.addInterceptor(RetryInterceptor(applicationContext, maxRetries = 3))
|
||||||
|
.build()
|
||||||
|
|
||||||
|
return ImageLoader.Builder(this)
|
||||||
|
.okHttpClient(okHttpClient)
|
||||||
|
.memoryCache {
|
||||||
|
MemoryCache.Builder(this)
|
||||||
|
.maxSizePercent(0.25) // 25% da memória RAM disponível
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
.diskCache {
|
||||||
|
DiskCache.Builder()
|
||||||
|
.directory(cacheDir.resolve("image_cache"))
|
||||||
|
.maxSizeBytes(50 * 1024 * 1024) // 50 MB de cache em disco (~100 fotos de 500KB)
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
.diskCachePolicy(CachePolicy.ENABLED)
|
||||||
|
.memoryCachePolicy(CachePolicy.ENABLED)
|
||||||
|
.networkCachePolicy(CachePolicy.ENABLED)
|
||||||
|
.crossfade(true)
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class RetryInterceptor(
|
||||||
|
private val context: android.content.Context,
|
||||||
|
private val maxRetries: Int = 3
|
||||||
|
) : Interceptor {
|
||||||
|
|
||||||
|
private val random = Random()
|
||||||
|
private val appLogger by lazy { AppLogger.getInstance(context) }
|
||||||
|
|
||||||
|
override fun intercept(chain: Interceptor.Chain): Response {
|
||||||
|
val request = chain.request()
|
||||||
|
val urlStr = request.url.toString()
|
||||||
|
var response: Response? = null
|
||||||
|
var lastException: Exception? = null
|
||||||
|
|
||||||
|
for (attempt in 1..maxRetries) {
|
||||||
|
try {
|
||||||
|
response?.close()
|
||||||
|
response = chain.proceed(request)
|
||||||
|
if (response.isSuccessful) {
|
||||||
|
return response
|
||||||
|
} else if (response.code in 500..599 && attempt < maxRetries) {
|
||||||
|
response.close()
|
||||||
|
val delayMs = 300L + random.nextInt(700) // Intervalo aleatório de 300ms a 1000ms
|
||||||
|
appLogger.logWarning(
|
||||||
|
"ImageDownload",
|
||||||
|
"Tentativa $attempt de $maxRetries falhou para $urlStr (HTTP ${response.code}). Aguardando ${delayMs}ms para tentar novamente..."
|
||||||
|
)
|
||||||
|
Thread.sleep(delayMs)
|
||||||
|
} else {
|
||||||
|
if (!response.isSuccessful) {
|
||||||
|
appLogger.logWarning(
|
||||||
|
"ImageDownload",
|
||||||
|
"Download de imagem retornou HTTP ${response.code} para $urlStr após $attempt tentativa(s)."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
lastException = e
|
||||||
|
if (attempt < maxRetries) {
|
||||||
|
val delayMs = 300L + random.nextInt(700)
|
||||||
|
appLogger.logWarning(
|
||||||
|
"ImageDownload",
|
||||||
|
"Falha de rede na tentativa $attempt de $maxRetries para $urlStr: ${e.message}. Tentando em ${delayMs}ms..."
|
||||||
|
)
|
||||||
|
try {
|
||||||
|
Thread.sleep(delayMs)
|
||||||
|
} catch (ie: InterruptedException) {
|
||||||
|
Thread.currentThread().interrupt()
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response != null) {
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
val errorMsg = "Falha no download da foto após $maxRetries tentativas: ${lastException?.message ?: "Erro de rede"}. URL: $urlStr"
|
||||||
|
appLogger.logError("ImageDownload", errorMsg, lastException)
|
||||||
|
throw lastException ?: IOException(errorMsg)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,15 +4,17 @@ import android.content.Context
|
|||||||
import androidx.room.Database
|
import androidx.room.Database
|
||||||
import androidx.room.Room
|
import androidx.room.Room
|
||||||
import androidx.room.RoomDatabase
|
import androidx.room.RoomDatabase
|
||||||
|
import com.example.data.model.AppConfig
|
||||||
import com.example.data.model.AppLog
|
import com.example.data.model.AppLog
|
||||||
import com.example.data.model.MaintenanceActivity
|
import com.example.data.model.MaintenanceActivity
|
||||||
|
import com.example.data.model.OSFinding
|
||||||
import com.example.data.model.OSUpdateHistory
|
import com.example.data.model.OSUpdateHistory
|
||||||
import com.example.data.model.SyncConflictLog
|
import com.example.data.model.SyncConflictLog
|
||||||
import com.example.data.model.UserAccess
|
import com.example.data.model.UserAccess
|
||||||
|
|
||||||
@Database(
|
@Database(
|
||||||
entities = [MaintenanceActivity::class, OSUpdateHistory::class, SyncConflictLog::class, UserAccess::class, AppLog::class],
|
entities = [MaintenanceActivity::class, OSUpdateHistory::class, SyncConflictLog::class, UserAccess::class, AppLog::class, OSFinding::class, AppConfig::class],
|
||||||
version = 6,
|
version = 10,
|
||||||
exportSchema = false
|
exportSchema = false
|
||||||
)
|
)
|
||||||
abstract class AppDatabase : RoomDatabase() {
|
abstract class AppDatabase : RoomDatabase() {
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ import androidx.room.Insert
|
|||||||
import androidx.room.OnConflictStrategy
|
import androidx.room.OnConflictStrategy
|
||||||
import androidx.room.Query
|
import androidx.room.Query
|
||||||
import androidx.room.Update
|
import androidx.room.Update
|
||||||
|
import com.example.data.model.AppConfig
|
||||||
import com.example.data.model.MaintenanceActivity
|
import com.example.data.model.MaintenanceActivity
|
||||||
|
import com.example.data.model.OSFinding
|
||||||
import com.example.data.model.OSUpdateHistory
|
import com.example.data.model.OSUpdateHistory
|
||||||
import com.example.data.model.SyncConflictLog
|
import com.example.data.model.SyncConflictLog
|
||||||
import com.example.data.model.UserAccess
|
import com.example.data.model.UserAccess
|
||||||
@@ -78,4 +80,74 @@ interface MaintenanceDao {
|
|||||||
|
|
||||||
@Query("DELETE FROM user_access")
|
@Query("DELETE FROM user_access")
|
||||||
suspend fun clearUserAccess()
|
suspend fun clearUserAccess()
|
||||||
|
|
||||||
|
// OSFinding Queries
|
||||||
|
@Query("SELECT * FROM os_findings WHERE numeroOs = :numeroOs ORDER BY timestamp DESC")
|
||||||
|
fun getFindingsForOs(numeroOs: String): Flow<List<OSFinding>>
|
||||||
|
|
||||||
|
@Query("SELECT * FROM os_findings WHERE numeroOs = :numeroOs ORDER BY timestamp DESC")
|
||||||
|
suspend fun getFindingsForOsOneShot(numeroOs: String): List<OSFinding>
|
||||||
|
|
||||||
|
@Query("SELECT * FROM os_findings WHERE numeroOs = :numeroOs AND tipo = 'OBS' ORDER BY timestamp DESC LIMIT 1")
|
||||||
|
fun getLatestObservationForOs(numeroOs: String): Flow<OSFinding?>
|
||||||
|
|
||||||
|
@Query("SELECT * FROM os_findings WHERE numeroOs = :numeroOs AND tipo = 'OBS' ORDER BY timestamp DESC LIMIT 1")
|
||||||
|
suspend fun getLatestObservationForOsOneShot(numeroOs: String): OSFinding?
|
||||||
|
|
||||||
|
@Query("SELECT * FROM os_findings WHERE numeroOs = :numeroOs AND (tipo = 'FOTO' OR (fotoPath IS NOT NULL AND fotoPath != '')) ORDER BY timestamp DESC LIMIT 1")
|
||||||
|
suspend fun getPhotoFindingForOsOneShot(numeroOs: String): OSFinding?
|
||||||
|
|
||||||
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
|
suspend fun insertFinding(finding: OSFinding)
|
||||||
|
|
||||||
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
|
suspend fun insertFindings(findings: List<OSFinding>)
|
||||||
|
|
||||||
|
@Query("DELETE FROM os_findings WHERE id = :id")
|
||||||
|
suspend fun deleteFindingById(id: String)
|
||||||
|
|
||||||
|
@Query("SELECT * FROM os_findings WHERE synced = 0")
|
||||||
|
suspend fun getUnsyncedFindings(): List<OSFinding>
|
||||||
|
|
||||||
|
@Query("SELECT * FROM os_findings")
|
||||||
|
suspend fun getAllFindingsList(): List<OSFinding>
|
||||||
|
|
||||||
|
@Query("DELETE FROM os_findings")
|
||||||
|
suspend fun clearAllFindings()
|
||||||
|
|
||||||
|
// Additional Synced and Epoch Purge Helpers
|
||||||
|
@Query("SELECT * FROM os_update_history WHERE synced = 0")
|
||||||
|
suspend fun getUnsyncedHistory(): List<OSUpdateHistory>
|
||||||
|
|
||||||
|
@Query("UPDATE os_update_history SET synced = 1 WHERE id IN (:ids)")
|
||||||
|
suspend fun markHistorySynced(ids: List<Long>)
|
||||||
|
|
||||||
|
@Query("UPDATE os_update_history SET synced = 1 WHERE numeroOs = :numeroOs AND timestamp = :timestamp")
|
||||||
|
suspend fun markHistorySyncedByOsAndTimestamp(numeroOs: String, timestamp: Long)
|
||||||
|
|
||||||
|
@Query("DELETE FROM os_update_history WHERE synced = 1 AND numeroOs NOT IN (:activeOsNumbers)")
|
||||||
|
suspend fun deleteStaleSyncedHistory(activeOsNumbers: List<String>)
|
||||||
|
|
||||||
|
@Query("DELETE FROM os_update_history WHERE synced = 1")
|
||||||
|
suspend fun deleteAllSyncedHistory()
|
||||||
|
|
||||||
|
@Query("DELETE FROM os_findings WHERE synced = 1 AND numeroOs NOT IN (:activeOsNumbers)")
|
||||||
|
suspend fun deleteStaleSyncedFindings(activeOsNumbers: List<String>)
|
||||||
|
|
||||||
|
@Query("DELETE FROM os_findings WHERE synced = 1")
|
||||||
|
suspend fun deleteAllSyncedFindings()
|
||||||
|
|
||||||
|
// AppConfig queries
|
||||||
|
@Query("SELECT * FROM app_config")
|
||||||
|
fun getAllConfigsFlow(): kotlinx.coroutines.flow.Flow<List<AppConfig>>
|
||||||
|
|
||||||
|
@Query("SELECT * FROM app_config")
|
||||||
|
suspend fun getAllConfigs(): List<AppConfig>
|
||||||
|
|
||||||
|
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||||
|
suspend fun insertConfigs(configs: List<AppConfig>)
|
||||||
|
|
||||||
|
@Query("DELETE FROM app_config")
|
||||||
|
suspend fun clearConfigs()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ data class AnalyticsState(
|
|||||||
val timelineDates: List<Date> = emptyList(),
|
val timelineDates: List<Date> = emptyList(),
|
||||||
val plannedProgressPoints: List<Float> = emptyList(),
|
val plannedProgressPoints: List<Float> = emptyList(),
|
||||||
val realizedProgressPoints: List<Float> = emptyList(),
|
val realizedProgressPoints: List<Float> = emptyList(),
|
||||||
val overdueByTag: List<Pair<String, Int>> = emptyList(),
|
val overdueByTag: List<Pair<String, Double>> = emptyList(),
|
||||||
val overdueBySector: List<Pair<String, Int>> = emptyList()
|
val overdueBySector: List<Pair<String, Double>> = emptyList(),
|
||||||
|
val selectedSetorSCurve: String = "Todos"
|
||||||
)
|
)
|
||||||
|
|||||||
18
app/src/main/java/com/example/data/model/AppConfig.kt
Normal file
18
app/src/main/java/com/example/data/model/AppConfig.kt
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
package com.example.data.model
|
||||||
|
|
||||||
|
import androidx.room.Entity
|
||||||
|
import androidx.room.PrimaryKey
|
||||||
|
|
||||||
|
@Entity(tableName = "app_config")
|
||||||
|
data class AppConfig(
|
||||||
|
@PrimaryKey val key: String,
|
||||||
|
val value: String,
|
||||||
|
val description: String? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ImportantLink(
|
||||||
|
val id: String,
|
||||||
|
val title: String,
|
||||||
|
val url: String,
|
||||||
|
val description: String? = null
|
||||||
|
)
|
||||||
29
app/src/main/java/com/example/data/model/AppSecurityState.kt
Normal file
29
app/src/main/java/com/example/data/model/AppSecurityState.kt
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
package com.example.data.model
|
||||||
|
|
||||||
|
data class SecurityContact(
|
||||||
|
val role: String,
|
||||||
|
val email: String
|
||||||
|
)
|
||||||
|
|
||||||
|
sealed class AppSecurityState {
|
||||||
|
object Allowed : AppSecurityState()
|
||||||
|
|
||||||
|
data class BlockedByMaintenance(
|
||||||
|
val message: String = "App fora de operação, entrar em contato com o responsável e o desenvolvedor",
|
||||||
|
val contacts: List<SecurityContact> = DEFAULT_CONTACTS
|
||||||
|
) : AppSecurityState()
|
||||||
|
|
||||||
|
data class BlockedByVersion(
|
||||||
|
val minVersion: String,
|
||||||
|
val currentVersion: String,
|
||||||
|
val message: String = "Versão do app incompativel, você deve atualizar o app para continuar usando, procure o responsável e o desenvolvedor",
|
||||||
|
val contacts: List<SecurityContact> = DEFAULT_CONTACTS
|
||||||
|
) : AppSecurityState()
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val DEFAULT_CONTACTS = listOf(
|
||||||
|
SecurityContact("Desenvolvedor", "cesarjhony+dev@gmail.com"),
|
||||||
|
SecurityContact("Responsável", "gabrielpizzinatto123@gmail.com")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package com.example.data.model
|
||||||
|
|
||||||
|
enum class DateSimulationMode {
|
||||||
|
DISABLED,
|
||||||
|
VISUALIZATION_ONLY,
|
||||||
|
EDIT_PROGRESS
|
||||||
|
}
|
||||||
|
|
||||||
|
data class DateSimulationConfig(
|
||||||
|
val simulatedDateMillis: Long? = null,
|
||||||
|
val mode: DateSimulationMode = DateSimulationMode.DISABLED,
|
||||||
|
val expirationTimestampMillis: Long? = null
|
||||||
|
) {
|
||||||
|
val isActive: Boolean get() = mode != DateSimulationMode.DISABLED && simulatedDateMillis != null
|
||||||
|
}
|
||||||
15
app/src/main/java/com/example/data/model/DeviceAccessInfo.kt
Normal file
15
app/src/main/java/com/example/data/model/DeviceAccessInfo.kt
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package com.example.data.model
|
||||||
|
|
||||||
|
import com.squareup.moshi.JsonClass
|
||||||
|
|
||||||
|
@JsonClass(generateAdapter = true)
|
||||||
|
data class DeviceAccessInfo(
|
||||||
|
val deviceId: String,
|
||||||
|
val dispositivo: String,
|
||||||
|
val email: String,
|
||||||
|
val nomeUsuario: String,
|
||||||
|
val versaoAndroid: String,
|
||||||
|
val versaoApp: String,
|
||||||
|
val ultimoAcesso: String,
|
||||||
|
val statusSincronizacao: String = "Sucesso"
|
||||||
|
)
|
||||||
@@ -1,13 +1,21 @@
|
|||||||
package com.example.data.model
|
package com.example.data.model
|
||||||
|
|
||||||
import androidx.room.Entity
|
import androidx.room.Entity
|
||||||
|
import androidx.room.Index
|
||||||
import androidx.room.PrimaryKey
|
import androidx.room.PrimaryKey
|
||||||
import java.text.SimpleDateFormat
|
import java.text.SimpleDateFormat
|
||||||
import java.util.Calendar
|
import java.util.Calendar
|
||||||
import java.util.Date
|
import java.util.Date
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
@Entity(tableName = "maintenance_activities")
|
@Entity(
|
||||||
|
tableName = "maintenance_activities",
|
||||||
|
indices = [
|
||||||
|
Index("equipe"),
|
||||||
|
Index("setor"),
|
||||||
|
Index("synced")
|
||||||
|
]
|
||||||
|
)
|
||||||
data class MaintenanceActivity(
|
data class MaintenanceActivity(
|
||||||
@PrimaryKey val numeroOs: String,
|
@PrimaryKey val numeroOs: String,
|
||||||
val descricao: String,
|
val descricao: String,
|
||||||
@@ -21,6 +29,7 @@ data class MaintenanceActivity(
|
|||||||
val fotoPath: String? = null,
|
val fotoPath: String? = null,
|
||||||
val synced: Boolean = false,
|
val synced: Boolean = false,
|
||||||
val tag: String = "",
|
val tag: String = "",
|
||||||
|
val quantidadeHoras: Double = 0.0,
|
||||||
val lastUpdated: Long = System.currentTimeMillis()
|
val lastUpdated: Long = System.currentTimeMillis()
|
||||||
) {
|
) {
|
||||||
val status: ActivityStatus
|
val status: ActivityStatus
|
||||||
@@ -29,6 +38,42 @@ data class MaintenanceActivity(
|
|||||||
percentualExecucao >= 100 -> ActivityStatus.CONCLUIDO
|
percentualExecucao >= 100 -> ActivityStatus.CONCLUIDO
|
||||||
else -> ActivityStatus.EM_ANDAMENTO
|
else -> ActivityStatus.EM_ANDAMENTO
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val formattedHoras: String
|
||||||
|
get() {
|
||||||
|
val hrs = duracaoHorasCalculada
|
||||||
|
return if (hrs <= 0.0) "0h"
|
||||||
|
else if (hrs % 1.0 == 0.0) "${hrs.toInt()}h"
|
||||||
|
else "${hrs}h"
|
||||||
|
}
|
||||||
|
|
||||||
|
val formattedDescricao: String
|
||||||
|
get() {
|
||||||
|
val prefix = "$formattedHoras - "
|
||||||
|
return if (descricao.startsWith(prefix)) descricao else "$prefix$descricao"
|
||||||
|
}
|
||||||
|
|
||||||
|
@delegate:Transient
|
||||||
|
val dataInicioMillis: Long by lazy {
|
||||||
|
(parseFullDateTime(dataInicio) ?: parseDateOnly(dataInicio))?.time ?: 0L
|
||||||
|
}
|
||||||
|
|
||||||
|
@delegate:Transient
|
||||||
|
val dataFimMillis: Long by lazy {
|
||||||
|
(parseFullDateTime(dataFim) ?: parseDateOnly(dataFim))?.time ?: Long.MAX_VALUE
|
||||||
|
}
|
||||||
|
|
||||||
|
val duracaoHorasCalculada: Double
|
||||||
|
get() {
|
||||||
|
if (quantidadeHoras > 0.0) return quantidadeHoras
|
||||||
|
val startMs = dataInicioMillis
|
||||||
|
val endMs = dataFimMillis
|
||||||
|
if (startMs > 0L && endMs < Long.MAX_VALUE && endMs > startMs) {
|
||||||
|
val hours = (endMs - startMs).toDouble() / (1000.0 * 60.0 * 60.0)
|
||||||
|
if (hours > 0.0) return hours
|
||||||
|
}
|
||||||
|
return 1.0
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
enum class ActivityStatus(val displayName: String) {
|
enum class ActivityStatus(val displayName: String) {
|
||||||
@@ -37,7 +82,13 @@ enum class ActivityStatus(val displayName: String) {
|
|||||||
CONCLUIDO("Concluído")
|
CONCLUIDO("Concluído")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Entity(tableName = "os_update_history")
|
@Entity(
|
||||||
|
tableName = "os_update_history",
|
||||||
|
indices = [
|
||||||
|
Index("numeroOs"),
|
||||||
|
Index("synced")
|
||||||
|
]
|
||||||
|
)
|
||||||
data class OSUpdateHistory(
|
data class OSUpdateHistory(
|
||||||
@PrimaryKey(autoGenerate = true) val id: Long = 0,
|
@PrimaryKey(autoGenerate = true) val id: Long = 0,
|
||||||
val numeroOs: String,
|
val numeroOs: String,
|
||||||
@@ -47,7 +98,8 @@ data class OSUpdateHistory(
|
|||||||
val observacao: String? = null,
|
val observacao: String? = null,
|
||||||
val fotoPath: String? = null,
|
val fotoPath: String? = null,
|
||||||
val recurso: String,
|
val recurso: String,
|
||||||
val emailEditor: String? = null
|
val emailEditor: String? = null,
|
||||||
|
val synced: Boolean = false
|
||||||
)
|
)
|
||||||
|
|
||||||
data class GoogleUser(
|
data class GoogleUser(
|
||||||
@@ -56,6 +108,17 @@ data class GoogleUser(
|
|||||||
val photoUrl: String? = null
|
val photoUrl: String? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ThreadLocal map for formatters to prevent continuous instantiation of SimpleDateFormat
|
||||||
|
private val threadLocalFormatters = object : ThreadLocal<MutableMap<String, SimpleDateFormat>>() {
|
||||||
|
override fun initialValue(): MutableMap<String, SimpleDateFormat> = mutableMapOf()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getFormatter(pattern: String): SimpleDateFormat {
|
||||||
|
val map = threadLocalFormatters.get()!!
|
||||||
|
return map.getOrPut(pattern) {
|
||||||
|
SimpleDateFormat(pattern, Locale.US).apply { isLenient = false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun extractDateOnly(dataStr: String): String {
|
fun extractDateOnly(dataStr: String): String {
|
||||||
val clean = dataStr.trim()
|
val clean = dataStr.trim()
|
||||||
@@ -89,22 +152,23 @@ fun adjustTwoDigitYear(date: Date?): Date? {
|
|||||||
return date
|
return date
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val dateOnlyFormats = listOf(
|
||||||
|
"dd/MM/yyyy",
|
||||||
|
"dd/MM/yy",
|
||||||
|
"yyyy-MM-dd",
|
||||||
|
"yy-MM-dd",
|
||||||
|
"dd-MM-yyyy",
|
||||||
|
"dd-MM-yy",
|
||||||
|
"MM/dd/yyyy",
|
||||||
|
"MM/dd/yy"
|
||||||
|
)
|
||||||
|
|
||||||
fun parseDateOnly(dateStr: String): Date? {
|
fun parseDateOnly(dateStr: String): Date? {
|
||||||
val clean = extractDateOnly(dateStr).trim()
|
val clean = extractDateOnly(dateStr).trim()
|
||||||
val formats = listOf(
|
if (clean == "N/A" || clean.isBlank()) return null
|
||||||
"dd/MM/yyyy",
|
for (format in dateOnlyFormats) {
|
||||||
"dd/MM/yy",
|
|
||||||
"yyyy-MM-dd",
|
|
||||||
"yy-MM-dd",
|
|
||||||
"dd-MM-yyyy",
|
|
||||||
"dd-MM-yy",
|
|
||||||
"MM/dd/yyyy",
|
|
||||||
"MM/dd/yy"
|
|
||||||
)
|
|
||||||
for (format in formats) {
|
|
||||||
try {
|
try {
|
||||||
val sdf = SimpleDateFormat(format, Locale.US)
|
val sdf = getFormatter(format)
|
||||||
sdf.isLenient = false
|
|
||||||
val parsed = sdf.parse(clean)
|
val parsed = sdf.parse(clean)
|
||||||
if (parsed != null) {
|
if (parsed != null) {
|
||||||
return adjustTwoDigitYear(parsed)
|
return adjustTwoDigitYear(parsed)
|
||||||
@@ -116,6 +180,29 @@ fun parseDateOnly(dateStr: String): Date? {
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val fullDateTimeFormats = listOf(
|
||||||
|
"dd/MM/yyyy HH:mm:ss",
|
||||||
|
"dd/MM/yyyy HH:mm",
|
||||||
|
"dd/MM/yy HH:mm:ss",
|
||||||
|
"dd/MM/yy HH:mm",
|
||||||
|
"yyyy-MM-dd HH:mm:ss",
|
||||||
|
"yyyy-MM-dd HH:mm",
|
||||||
|
"yy-MM-dd HH:mm:ss",
|
||||||
|
"yy-MM-dd HH:mm",
|
||||||
|
"yyyy-MM-dd'T'HH:mm:ss",
|
||||||
|
"yyyy-MM-dd'T'HH:mm",
|
||||||
|
"yy-MM-dd'T'HH:mm:ss",
|
||||||
|
"yy-MM-dd'T'HH:mm",
|
||||||
|
"dd/MM/yyyy",
|
||||||
|
"dd/MM/yy",
|
||||||
|
"yyyy-MM-dd",
|
||||||
|
"yy-MM-dd",
|
||||||
|
"dd-MM-yyyy",
|
||||||
|
"dd-MM-yy",
|
||||||
|
"MM/dd/yyyy",
|
||||||
|
"MM/dd/yy"
|
||||||
|
)
|
||||||
|
|
||||||
fun parseFullDateTime(dateTimeStr: String): Date? {
|
fun parseFullDateTime(dateTimeStr: String): Date? {
|
||||||
var clean = dateTimeStr.trim()
|
var clean = dateTimeStr.trim()
|
||||||
if (clean == "N/A" || clean.isBlank()) return null
|
if (clean == "N/A" || clean.isBlank()) return null
|
||||||
@@ -123,32 +210,9 @@ fun parseFullDateTime(dateTimeStr: String): Date? {
|
|||||||
// Strip leading weekday prefixes like "sex.", "seg.", "ter.", "qua.", "qui.", "sáb.", "dom.", "Sex", "Seg", etc.
|
// Strip leading weekday prefixes like "sex.", "seg.", "ter.", "qua.", "qui.", "sáb.", "dom.", "Sex", "Seg", etc.
|
||||||
clean = clean.replace(Regex("^[a-zA-zA-ZáàâãéèêíóôõúçÁÀÂÃÉÈÍÓÔÕÚÇ]{2,4}\\.?\\s+"), "").trim()
|
clean = clean.replace(Regex("^[a-zA-zA-ZáàâãéèêíóôõúçÁÀÂÃÉÈÍÓÔÕÚÇ]{2,4}\\.?\\s+"), "").trim()
|
||||||
|
|
||||||
val formats = listOf(
|
for (format in fullDateTimeFormats) {
|
||||||
"dd/MM/yyyy HH:mm:ss",
|
|
||||||
"dd/MM/yyyy HH:mm",
|
|
||||||
"dd/MM/yy HH:mm:ss",
|
|
||||||
"dd/MM/yy HH:mm",
|
|
||||||
"yyyy-MM-dd HH:mm:ss",
|
|
||||||
"yyyy-MM-dd HH:mm",
|
|
||||||
"yy-MM-dd HH:mm:ss",
|
|
||||||
"yy-MM-dd HH:mm",
|
|
||||||
"yyyy-MM-dd'T'HH:mm:ss",
|
|
||||||
"yyyy-MM-dd'T'HH:mm",
|
|
||||||
"yy-MM-dd'T'HH:mm:ss",
|
|
||||||
"yy-MM-dd'T'HH:mm",
|
|
||||||
"dd/MM/yyyy",
|
|
||||||
"dd/MM/yy",
|
|
||||||
"yyyy-MM-dd",
|
|
||||||
"yy-MM-dd",
|
|
||||||
"dd-MM-yyyy",
|
|
||||||
"dd-MM-yy",
|
|
||||||
"MM/dd/yyyy",
|
|
||||||
"MM/dd/yy"
|
|
||||||
)
|
|
||||||
for (format in formats) {
|
|
||||||
try {
|
try {
|
||||||
val sdf = SimpleDateFormat(format, Locale.US)
|
val sdf = getFormatter(format)
|
||||||
sdf.isLenient = false
|
|
||||||
val parsed = sdf.parse(clean)
|
val parsed = sdf.parse(clean)
|
||||||
if (parsed != null) {
|
if (parsed != null) {
|
||||||
return adjustTwoDigitYear(parsed)
|
return adjustTwoDigitYear(parsed)
|
||||||
@@ -166,13 +230,23 @@ fun formatToShortDate(dataStr: String): String {
|
|||||||
val extracted = extractDateOnly(clean)
|
val extracted = extractDateOnly(clean)
|
||||||
val parsed = parseDateOnly(extracted) ?: return extracted
|
val parsed = parseDateOnly(extracted) ?: return extracted
|
||||||
return try {
|
return try {
|
||||||
val sdf = SimpleDateFormat("dd/MM/yy", Locale.US)
|
val sdf = getFormatter("dd/MM/yy")
|
||||||
sdf.format(parsed)
|
sdf.format(parsed)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
extracted
|
extracted
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun truncateToStartOfDay(millis: Long): Long {
|
||||||
|
val cal = Calendar.getInstance()
|
||||||
|
cal.timeInMillis = millis
|
||||||
|
cal.set(Calendar.HOUR_OF_DAY, 0)
|
||||||
|
cal.set(Calendar.MINUTE, 0)
|
||||||
|
cal.set(Calendar.SECOND, 0)
|
||||||
|
cal.set(Calendar.MILLISECOND, 0)
|
||||||
|
return cal.timeInMillis
|
||||||
|
}
|
||||||
|
|
||||||
fun isDateInExecutionPeriod(selectedDateStr: String, dataInicioStr: String, dataFimStr: String): Boolean {
|
fun isDateInExecutionPeriod(selectedDateStr: String, dataInicioStr: String, dataFimStr: String): Boolean {
|
||||||
val cleanSelected = selectedDateStr.trim()
|
val cleanSelected = selectedDateStr.trim()
|
||||||
if (cleanSelected == "Todas" || cleanSelected.isBlank()) return true
|
if (cleanSelected == "Todas" || cleanSelected.isBlank()) return true
|
||||||
@@ -181,28 +255,11 @@ fun isDateInExecutionPeriod(selectedDateStr: String, dataInicioStr: String, data
|
|||||||
val startDate = parseDateOnly(dataInicioStr) ?: parseFullDateTime(dataInicioStr) ?: return false
|
val startDate = parseDateOnly(dataInicioStr) ?: parseFullDateTime(dataInicioStr) ?: return false
|
||||||
val endDate = parseDateOnly(dataFimStr) ?: parseFullDateTime(dataFimStr) ?: startDate
|
val endDate = parseDateOnly(dataFimStr) ?: parseFullDateTime(dataFimStr) ?: startDate
|
||||||
|
|
||||||
val selCal = Calendar.getInstance().apply {
|
val selTime = truncateToStartOfDay(selDate.time)
|
||||||
time = selDate
|
val startTime = truncateToStartOfDay(startDate.time)
|
||||||
set(Calendar.HOUR_OF_DAY, 0)
|
val endTime = truncateToStartOfDay(endDate.time)
|
||||||
set(Calendar.MINUTE, 0)
|
|
||||||
set(Calendar.SECOND, 0)
|
|
||||||
set(Calendar.MILLISECOND, 0)
|
|
||||||
}
|
|
||||||
val startCal = Calendar.getInstance().apply {
|
|
||||||
time = startDate
|
|
||||||
set(Calendar.HOUR_OF_DAY, 0)
|
|
||||||
set(Calendar.MINUTE, 0)
|
|
||||||
set(Calendar.SECOND, 0)
|
|
||||||
set(Calendar.MILLISECOND, 0)
|
|
||||||
}
|
|
||||||
val endCal = Calendar.getInstance().apply {
|
|
||||||
time = endDate
|
|
||||||
set(Calendar.HOUR_OF_DAY, 0)
|
|
||||||
set(Calendar.MINUTE, 0)
|
|
||||||
set(Calendar.SECOND, 0)
|
|
||||||
set(Calendar.MILLISECOND, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
return !selCal.before(startCal) && !selCal.after(endCal)
|
return selTime in startTime..endTime
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
39
app/src/main/java/com/example/data/model/OSFinding.kt
Normal file
39
app/src/main/java/com/example/data/model/OSFinding.kt
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
package com.example.data.model
|
||||||
|
|
||||||
|
import androidx.room.Entity
|
||||||
|
import androidx.room.Index
|
||||||
|
import androidx.room.PrimaryKey
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
@Entity(
|
||||||
|
tableName = "os_findings",
|
||||||
|
indices = [
|
||||||
|
Index("numeroOs"),
|
||||||
|
Index("tipo"),
|
||||||
|
Index("synced")
|
||||||
|
]
|
||||||
|
)
|
||||||
|
data class OSFinding(
|
||||||
|
@PrimaryKey val id: String = UUID.randomUUID().toString(),
|
||||||
|
val numeroOs: String,
|
||||||
|
val tipo: String, // "OBS", "SEGURANCA", "MANUTENCAO"
|
||||||
|
val descricao: String,
|
||||||
|
val timestamp: Long = System.currentTimeMillis(),
|
||||||
|
val responsavel: String,
|
||||||
|
val emailEditor: String? = null,
|
||||||
|
val fotoPath: String? = null,
|
||||||
|
val synced: Boolean = false
|
||||||
|
)
|
||||||
|
|
||||||
|
enum class FindingType(val value: String, val displayName: String) {
|
||||||
|
FOTO("FOTO", "Foto"),
|
||||||
|
OBS("OBS", "Observação"),
|
||||||
|
SEGURANCA("SEGURANCA", "Achado de Segurança"),
|
||||||
|
MANUTENCAO("MANUTENCAO", "Achado de Manutenção");
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun fromValue(value: String): FindingType {
|
||||||
|
return values().firstOrNull { it.value.equals(value, ignoreCase = true) } ?: FOTO
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,24 +24,9 @@ class FirebaseStorageSyncService(
|
|||||||
private val storage: FirebaseStorage by lazy { FirebaseStorage.getInstance() }
|
private val storage: FirebaseStorage by lazy { FirebaseStorage.getInstance() }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Uploads a local photo file to Firebase Storage under `photos/OS_{osNumber}/{fileName}`.
|
* Ensures user is authenticated with Firebase Auth via Google ID Token if currentUser is null.
|
||||||
* Returns FirebaseUploadResult containing the public download URL and storage path.
|
|
||||||
*/
|
*/
|
||||||
suspend fun uploadPhoto(photoFile: File, osNumber: String): FirebaseUploadResult {
|
suspend fun ensureFirebaseAuth() {
|
||||||
if (!photoFile.exists()) {
|
|
||||||
val err = "Arquivo local da foto não existe: ${photoFile.absolutePath}"
|
|
||||||
appLogger.logError(tag, err)
|
|
||||||
throw IOException(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
val timestamp = System.currentTimeMillis()
|
|
||||||
val sanitizedOs = osNumber.replace("/", "_").replace(" ", "")
|
|
||||||
val fileName = "OS_${sanitizedOs}_${timestamp}.jpg"
|
|
||||||
val storagePath = "photos/OS_${sanitizedOs}/$fileName"
|
|
||||||
|
|
||||||
val photoRef: StorageReference = storage.reference.child(storagePath)
|
|
||||||
|
|
||||||
// Ensure user is authenticated with Firebase Auth if possible
|
|
||||||
val auth = com.google.firebase.auth.FirebaseAuth.getInstance()
|
val auth = com.google.firebase.auth.FirebaseAuth.getInstance()
|
||||||
if (auth.currentUser == null) {
|
if (auth.currentUser == null) {
|
||||||
val lastAccount = com.google.android.gms.auth.api.signin.GoogleSignIn.getLastSignedInAccount(context)
|
val lastAccount = com.google.android.gms.auth.api.signin.GoogleSignIn.getLastSignedInAccount(context)
|
||||||
@@ -58,13 +43,39 @@ class FirebaseStorageSyncService(
|
|||||||
Log.w(tag, "Aviso: Nenhum usuário autenticado no FirebaseAuth nem ID Token do Google disponível.")
|
Log.w(tag, "Aviso: Nenhum usuário autenticado no FirebaseAuth nem ID Token do Google disponível.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Uploads a local photo file to Firebase Storage under `photos/OS_{osNumber}/{fileName}`.
|
||||||
|
* Returns FirebaseUploadResult containing the public download URL and storage path.
|
||||||
|
*/
|
||||||
|
suspend fun uploadPhoto(photoFile: File, osNumber: String): FirebaseUploadResult {
|
||||||
|
if (!photoFile.exists()) {
|
||||||
|
val err = "Arquivo local da foto não existe: ${photoFile.absolutePath}"
|
||||||
|
appLogger.logError(tag, err)
|
||||||
|
throw IOException(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
val timestamp = System.currentTimeMillis()
|
||||||
|
val sanitizedOs = osNumber.replace("/", "_").replace(" ", "")
|
||||||
|
val fileName = "OS_${sanitizedOs}_${timestamp}.jpg"
|
||||||
|
val storagePath = "photos/OS_${sanitizedOs}/$fileName"
|
||||||
|
|
||||||
|
val photoRef: StorageReference = storage.reference.child(storagePath)
|
||||||
|
ensureFirebaseAuth()
|
||||||
|
|
||||||
try {
|
try {
|
||||||
val fileUri = Uri.fromFile(photoFile)
|
val fileToUpload = if (photoFile.length() > 500 * 1024L) {
|
||||||
|
com.example.util.ImageCompressor.compressImageFile(photoFile, 500 * 1024L)
|
||||||
|
} else {
|
||||||
|
photoFile
|
||||||
|
}
|
||||||
|
val fileUri = Uri.fromFile(fileToUpload)
|
||||||
photoRef.putFile(fileUri).await()
|
photoRef.putFile(fileUri).await()
|
||||||
val downloadUrl = photoRef.downloadUrl.await().toString()
|
val downloadUrl = photoRef.downloadUrl.await().toString()
|
||||||
|
|
||||||
appLogger.logInfo(tag, "Foto enviada com sucesso para o Firebase Storage. OS: $osNumber, Path: $storagePath")
|
appLogger.logInfo(tag, "Foto enviada com sucesso para o Firebase Storage. OS: $osNumber, Path: $storagePath")
|
||||||
|
downloadUrlCache[storagePath] = downloadUrl
|
||||||
return FirebaseUploadResult(
|
return FirebaseUploadResult(
|
||||||
downloadUrl = downloadUrl,
|
downloadUrl = downloadUrl,
|
||||||
storagePath = storagePath,
|
storagePath = storagePath,
|
||||||
@@ -77,6 +88,75 @@ class FirebaseStorageSyncService(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Downloads a photo file from Firebase Storage ON DEMAND to internal `os_photos` directory.
|
||||||
|
* Returns the downloaded local File or null on error.
|
||||||
|
*/
|
||||||
|
suspend fun downloadPhotoFile(rawPath: String): File? {
|
||||||
|
val trimmed = rawPath.trim()
|
||||||
|
if (trimmed.isBlank() || trimmed.contains("_DELETED")) return null
|
||||||
|
|
||||||
|
val cleanPath = trimmed.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true)
|
||||||
|
val fileName = cleanPath.substringAfterLast("/").substringAfterLast("\\")
|
||||||
|
.removeSuffix("_DELETED").removeSuffix(".jpg_DELETED").replace("_DELETED", "")
|
||||||
|
|
||||||
|
if (fileName.isBlank()) return null
|
||||||
|
|
||||||
|
val photosDir = File(context.filesDir, "os_photos")
|
||||||
|
if (!photosDir.exists()) photosDir.mkdirs()
|
||||||
|
|
||||||
|
val targetLocalFile = File(photosDir, fileName)
|
||||||
|
if (targetLocalFile.exists() && targetLocalFile.length() > 0) {
|
||||||
|
return targetLocalFile
|
||||||
|
}
|
||||||
|
|
||||||
|
var canonicalStoragePath = cleanPath.removePrefix("/")
|
||||||
|
if (!canonicalStoragePath.startsWith("photos/")) {
|
||||||
|
if (canonicalStoragePath.startsWith("o/photos/")) {
|
||||||
|
canonicalStoragePath = canonicalStoragePath.removePrefix("o/")
|
||||||
|
} else if (canonicalStoragePath.contains("photos/")) {
|
||||||
|
canonicalStoragePath = "photos/" + canonicalStoragePath.substringAfter("photos/")
|
||||||
|
} else if (canonicalStoragePath.startsWith("OS_")) {
|
||||||
|
canonicalStoragePath = "photos/$canonicalStoragePath"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ensureFirebaseAuth()
|
||||||
|
|
||||||
|
return try {
|
||||||
|
val photoRef = storage.reference.child(canonicalStoragePath)
|
||||||
|
photoRef.getFile(targetLocalFile).await()
|
||||||
|
|
||||||
|
try {
|
||||||
|
val tokenizedUrl = photoRef.downloadUrl.await().toString()
|
||||||
|
registerDownloadUrl(canonicalStoragePath, tokenizedUrl)
|
||||||
|
} catch (ignored: Exception) {}
|
||||||
|
|
||||||
|
appLogger.logInfo(tag, "Foto baixada com sucesso sob demanda para ${targetLocalFile.name}")
|
||||||
|
targetLocalFile
|
||||||
|
} catch (e: Exception) {
|
||||||
|
appLogger.logError(tag, "Falha ao baixar foto sob demanda de '$canonicalStoragePath': ${e.message}", e)
|
||||||
|
if (targetLocalFile.exists() && targetLocalFile.length() == 0L) {
|
||||||
|
targetLocalFile.delete()
|
||||||
|
}
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val downloadUrlCache = java.util.concurrent.ConcurrentHashMap<String, String>()
|
||||||
|
|
||||||
|
fun registerDownloadUrl(storagePath: String, downloadUrl: String) {
|
||||||
|
if (storagePath.isNotBlank() && downloadUrl.isNotBlank()) {
|
||||||
|
downloadUrlCache[storagePath] = downloadUrl
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getCachedDownloadUrl(storagePath: String): String? {
|
||||||
|
return downloadUrlCache[storagePath]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Performs Soft Delete by copying the file object in Firebase Storage to have "_DELETED"
|
* Performs Soft Delete by copying the file object in Firebase Storage to have "_DELETED"
|
||||||
* suffix in the exact same folder, and deleting the original reference.
|
* suffix in the exact same folder, and deleting the original reference.
|
||||||
@@ -111,6 +191,16 @@ class FirebaseStorageSyncService(
|
|||||||
|
|
||||||
Log.d(tag, "Arquivo $currentPath renomeado no Firebase Storage para $newPath (Soft Delete).")
|
Log.d(tag, "Arquivo $currentPath renomeado no Firebase Storage para $newPath (Soft Delete).")
|
||||||
true
|
true
|
||||||
|
} catch (e: com.google.firebase.storage.StorageException) {
|
||||||
|
if (e.errorCode == com.google.firebase.storage.StorageException.ERROR_OBJECT_NOT_FOUND ||
|
||||||
|
e.message?.contains("Object does not exist", ignoreCase = true) == true
|
||||||
|
) {
|
||||||
|
Log.d(tag, "Arquivo não encontrado no Firebase Storage ao tentar deletar (já inexistente): ${e.message}")
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
Log.e(tag, "Falha ao executar soft delete no Firebase Storage: ${e.message}", e)
|
||||||
|
false
|
||||||
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(tag, "Falha ao executar soft delete no Firebase Storage: ${e.message}", e)
|
Log.e(tag, "Falha ao executar soft delete no Firebase Storage: ${e.message}", e)
|
||||||
false
|
false
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ package com.example.data.remote
|
|||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
|
import com.example.data.model.AppConfig
|
||||||
|
import com.example.data.model.DeviceAccessInfo
|
||||||
import com.example.data.model.MaintenanceActivity
|
import com.example.data.model.MaintenanceActivity
|
||||||
import com.example.data.model.OSUpdateHistory
|
import com.example.data.model.OSUpdateHistory
|
||||||
import com.example.data.model.UserAccess
|
import com.example.data.model.UserAccess
|
||||||
@@ -757,13 +759,67 @@ class GoogleSheetsSyncService(
|
|||||||
observacao = obs,
|
observacao = obs,
|
||||||
fotoPath = foto,
|
fotoPath = foto,
|
||||||
recurso = resp,
|
recurso = resp,
|
||||||
emailEditor = email.takeIf { it.isNotBlank() }
|
emailEditor = email.takeIf { it.isNotBlank() },
|
||||||
|
synced = true
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
return historyList
|
return historyList
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads database_epoch from 'config' tab (cell B2 or key 'database_epoch').
|
||||||
|
* Defaults to 1 if tab or value is missing/invalid.
|
||||||
|
*/
|
||||||
|
fun fetchDatabaseEpoch(): Int {
|
||||||
|
return try {
|
||||||
|
val rows = fetchValues("config!A:B")
|
||||||
|
if (rows.isEmpty()) return 1
|
||||||
|
for (row in rows) {
|
||||||
|
if (row.isNotEmpty() && row[0].trim().lowercase() == "database_epoch") {
|
||||||
|
if (row.size > 1) {
|
||||||
|
val epochVal = row[1].trim().toIntOrNull()
|
||||||
|
if (epochVal != null && epochVal > 0) {
|
||||||
|
return epochVal
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Fallback: check row 2 col 2 (B2)
|
||||||
|
if (rows.size >= 2 && rows[1].size >= 2) {
|
||||||
|
rows[1][1].trim().toIntOrNull() ?: 1
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.d(tag, "Tab 'config' não encontrada ou sem chave 'database_epoch'. Usando epoch padrão = 1.")
|
||||||
|
1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads all key-value-description configuration rows from 'config' tab (config!A:C).
|
||||||
|
*/
|
||||||
|
fun fetchRemoteConfigs(): List<AppConfig> {
|
||||||
|
return try {
|
||||||
|
val rows = fetchValues("config!A:C")
|
||||||
|
if (rows.isEmpty()) return emptyList()
|
||||||
|
val result = mutableListOf<AppConfig>()
|
||||||
|
for (row in rows) {
|
||||||
|
if (row.isEmpty()) continue
|
||||||
|
val key = row[0].trim()
|
||||||
|
if (key.isEmpty() || key.lowercase() == "chave" || key.lowercase() == "key") continue
|
||||||
|
val value = if (row.size > 1) row[1].trim() else ""
|
||||||
|
val desc = if (row.size > 2 && row[2].trim().isNotBlank()) row[2].trim() else null
|
||||||
|
result.add(AppConfig(key = key, value = value, description = desc))
|
||||||
|
}
|
||||||
|
result
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(tag, "Erro ao carregar configurações da aba 'config'", e)
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stubs out direct activities editing since 'project' is now read-only.
|
* Stubs out direct activities editing since 'project' is now read-only.
|
||||||
*/
|
*/
|
||||||
@@ -811,7 +867,7 @@ class GoogleSheetsSyncService(
|
|||||||
row[headerIndices["percentualanterior"] ?: 3] = history.percentualAnterior.toString()
|
row[headerIndices["percentualanterior"] ?: 3] = history.percentualAnterior.toString()
|
||||||
row[headerIndices["percentualnovo"] ?: 4] = history.percentualNovo.toString()
|
row[headerIndices["percentualnovo"] ?: 4] = history.percentualNovo.toString()
|
||||||
row[headerIndices["observacao"] ?: 5] = history.observacao ?: ""
|
row[headerIndices["observacao"] ?: 5] = history.observacao ?: ""
|
||||||
row[headerIndices["fotopath"] ?: 6] = history.fotoPath ?: ""
|
row[headerIndices["fotopath"] ?: 6] = filterRemoteOnlyPhotoPaths(history.fotoPath)
|
||||||
row[headerIndices["responsavel"] ?: 7] = history.recurso
|
row[headerIndices["responsavel"] ?: 7] = history.recurso
|
||||||
row[headerIndices["email_editor"] ?: 8] = history.emailEditor ?: ""
|
row[headerIndices["email_editor"] ?: 8] = history.emailEditor ?: ""
|
||||||
row
|
row
|
||||||
@@ -849,4 +905,231 @@ class GoogleSheetsSyncService(
|
|||||||
}
|
}
|
||||||
return accessList
|
return accessList
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches all remote findings from the 'achados' sheet.
|
||||||
|
*/
|
||||||
|
fun fetchRemoteFindingsList(): List<com.example.data.model.OSFinding> {
|
||||||
|
val defaultHeaders = listOf(
|
||||||
|
"id", "numeroOs", "tipo", "descricao", "timestamp", "responsavel", "email_editor", "fotoPath"
|
||||||
|
)
|
||||||
|
ensureHeaders("achados", defaultHeaders)
|
||||||
|
|
||||||
|
val rows = fetchValues("achados!A:H")
|
||||||
|
val findingsList = mutableListOf<com.example.data.model.OSFinding>()
|
||||||
|
if (rows.size <= 1) return findingsList
|
||||||
|
|
||||||
|
val headers = rows[0].map { it.trim().lowercase() }
|
||||||
|
val idIdx = headers.indexOf("id")
|
||||||
|
val osIdx = headers.indexOf("numeroos")
|
||||||
|
val tipoIdx = headers.indexOf("tipo")
|
||||||
|
val descIdx = headers.indexOf("descricao")
|
||||||
|
val tsIdx = headers.indexOf("timestamp")
|
||||||
|
val respIdx = headers.indexOf("responsavel")
|
||||||
|
val emailIdx = headers.indexOf("email_editor")
|
||||||
|
val fotoIdx = headers.indexOf("fotopath")
|
||||||
|
|
||||||
|
val getCell = { row: List<String>, mapIdx: Int, fallbackIdx: Int ->
|
||||||
|
val idx = if (mapIdx != -1) mapIdx else fallbackIdx
|
||||||
|
if (idx < row.size) row[idx].trim() else ""
|
||||||
|
}
|
||||||
|
|
||||||
|
for (i in 1 until rows.size) {
|
||||||
|
val row = rows[i]
|
||||||
|
val id = getCell(row, idIdx, 0)
|
||||||
|
val os = getCell(row, osIdx, 1)
|
||||||
|
if (id.isBlank() || os.isBlank()) continue
|
||||||
|
|
||||||
|
val tipo = getCell(row, tipoIdx, 2).ifBlank { "OBS" }
|
||||||
|
val desc = getCell(row, descIdx, 3)
|
||||||
|
val tsStr = getCell(row, tsIdx, 4)
|
||||||
|
val ts = tsStr.toLongOrNull() ?: System.currentTimeMillis()
|
||||||
|
val resp = getCell(row, respIdx, 5)
|
||||||
|
val email = getCell(row, emailIdx, 6).takeIf { it.isNotBlank() }
|
||||||
|
val foto = getCell(row, fotoIdx, 7).takeIf { it.isNotBlank() }
|
||||||
|
|
||||||
|
findingsList.add(
|
||||||
|
com.example.data.model.OSFinding(
|
||||||
|
id = id,
|
||||||
|
numeroOs = os,
|
||||||
|
tipo = tipo,
|
||||||
|
descricao = desc,
|
||||||
|
timestamp = ts,
|
||||||
|
responsavel = resp,
|
||||||
|
emailEditor = email,
|
||||||
|
fotoPath = foto,
|
||||||
|
synced = true
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return findingsList
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rewrites/syncs the active findings list to the 'achados' sheet.
|
||||||
|
*/
|
||||||
|
fun syncFindingsWithSheet(allActiveFindings: List<com.example.data.model.OSFinding>) {
|
||||||
|
val defaultHeaders = listOf(
|
||||||
|
"id", "numeroOs", "tipo", "descricao", "timestamp", "responsavel", "email_editor", "fotoPath"
|
||||||
|
)
|
||||||
|
ensureHeaders("achados", defaultHeaders)
|
||||||
|
|
||||||
|
val existingRows = fetchValues("achados!A:H")
|
||||||
|
val currentRemoteRowCount = if (existingRows.size > 1) existingRows.size - 1 else 0
|
||||||
|
|
||||||
|
val newRows = allActiveFindings.map { finding ->
|
||||||
|
listOf(
|
||||||
|
finding.id,
|
||||||
|
finding.numeroOs,
|
||||||
|
finding.tipo,
|
||||||
|
finding.descricao,
|
||||||
|
finding.timestamp.toString(),
|
||||||
|
finding.responsavel,
|
||||||
|
finding.emailEditor ?: "",
|
||||||
|
filterRemoteOnlyPhotoPaths(finding.fotoPath, finding.numeroOs)
|
||||||
|
)
|
||||||
|
}.toMutableList()
|
||||||
|
|
||||||
|
// Pad with empty rows to physically overwrite/clear deleted rows in Google Sheets
|
||||||
|
if (currentRemoteRowCount > newRows.size) {
|
||||||
|
val emptyRow = List(8) { "" }
|
||||||
|
repeat(currentRemoteRowCount - newRows.size) {
|
||||||
|
newRows.add(emptyRow)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newRows.isNotEmpty()) {
|
||||||
|
val endRow = newRows.size + 1
|
||||||
|
updateValues("achados!A2:H$endRow", newRows)
|
||||||
|
Log.d(tag, "Successfully updated 'achados' sheet with ${allActiveFindings.size} active findings.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cleanToStoragePath(pathStr: String?, defaultOsNumber: String = ""): String? {
|
||||||
|
if (pathStr.isNullOrBlank()) return null
|
||||||
|
val items = pathStr.split("|").map { item ->
|
||||||
|
val trimmed = item.trim()
|
||||||
|
if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
|
||||||
|
val clean = trimmed.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true)
|
||||||
|
if (clean.contains("/o/")) {
|
||||||
|
clean.substringAfter("/o/").trim('/')
|
||||||
|
} else if (clean.contains("photos/")) {
|
||||||
|
"photos/" + clean.substringAfter("photos/")
|
||||||
|
} else {
|
||||||
|
trimmed
|
||||||
|
}
|
||||||
|
} else if (trimmed.startsWith("/")) {
|
||||||
|
val clean = trimmed.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true)
|
||||||
|
val fileName = clean.substringAfterLast("/").substringAfterLast("\\")
|
||||||
|
.removeSuffix("_DELETED").removeSuffix(".jpg_DELETED").replace("_DELETED", "")
|
||||||
|
val osFolder = if (fileName.startsWith("OS_")) {
|
||||||
|
val parts = fileName.split("_")
|
||||||
|
if (parts.size >= 2) "${parts[0]}_${parts[1]}" else "OS_$defaultOsNumber"
|
||||||
|
} else if (defaultOsNumber.isNotBlank()) {
|
||||||
|
val osSanitized = defaultOsNumber.replace("/", "_").replace(" ", "")
|
||||||
|
"OS_$osSanitized"
|
||||||
|
} else {
|
||||||
|
"OS_Geral"
|
||||||
|
}
|
||||||
|
"photos/$osFolder/$fileName"
|
||||||
|
} else if (trimmed.startsWith("OS_") && trimmed.contains("/")) {
|
||||||
|
"photos/$trimmed"
|
||||||
|
} else {
|
||||||
|
trimmed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return items.distinct().joinToString("|").ifEmpty { null }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun filterRemoteOnlyPhotoPaths(pathStr: String?, defaultOsNumber: String = ""): String {
|
||||||
|
if (pathStr.isNullOrBlank()) return ""
|
||||||
|
val cleaned = cleanToStoragePath(pathStr, defaultOsNumber) ?: return ""
|
||||||
|
return cleaned.split("|")
|
||||||
|
.map { it.trim() }
|
||||||
|
.filter { it.isNotBlank() && !it.endsWith("_DELETED") && !it.contains("_DELETED") }
|
||||||
|
.distinct()
|
||||||
|
.joinToString("|")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates or appends the device last access record in the 'usage_history' sheet.
|
||||||
|
*/
|
||||||
|
fun updateUsageHistory(info: DeviceAccessInfo) {
|
||||||
|
val sheetName = "usage_history"
|
||||||
|
val defaultHeaders = listOf(
|
||||||
|
"device_id", "dispositivo", "email", "nome_usuario", "versao_android", "versao_app", "ultimo_acesso", "status_sincronizacao"
|
||||||
|
)
|
||||||
|
ensureHeaders(sheetName, defaultHeaders)
|
||||||
|
|
||||||
|
val rows = fetchValues("$sheetName!A:H")
|
||||||
|
if (rows.isEmpty()) {
|
||||||
|
val newRow = listOf(
|
||||||
|
info.deviceId,
|
||||||
|
info.dispositivo,
|
||||||
|
info.email,
|
||||||
|
info.nomeUsuario,
|
||||||
|
info.versaoAndroid,
|
||||||
|
info.versaoApp,
|
||||||
|
info.ultimoAcesso,
|
||||||
|
info.statusSincronizacao
|
||||||
|
)
|
||||||
|
appendValues("$sheetName!A:H", listOf(newRow))
|
||||||
|
Log.d(tag, "Successfully appended initial device access record for device_id: ${info.deviceId}")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
val headers = rows[0].map { it.trim().lowercase() }
|
||||||
|
val deviceIdIdx = headers.indexOfFirst { it == "device_id" || it == "deviceid" || it.contains("device") }
|
||||||
|
.let { if (it != -1) it else 0 }
|
||||||
|
val dispositivoIdx = headers.indexOfFirst { it == "dispositivo" || it.contains("modelo") || it.contains("aparelho") }
|
||||||
|
.let { if (it != -1) it else 1 }
|
||||||
|
val emailIdx = headers.indexOfFirst { it == "email" || it == "e-mail" || it.contains("email") }
|
||||||
|
.let { if (it != -1) it else 2 }
|
||||||
|
val nomeIdx = headers.indexOfFirst { it == "nome_usuario" || it == "nome" || it.contains("usuario") || it.contains("usuário") }
|
||||||
|
.let { if (it != -1) it else 3 }
|
||||||
|
val androidIdx = headers.indexOfFirst { it == "versao_android" || it.contains("android") }
|
||||||
|
.let { if (it != -1) it else 4 }
|
||||||
|
val appIdx = headers.indexOfFirst { it == "versao_app" || it.contains("app") }
|
||||||
|
.let { if (it != -1) it else 5 }
|
||||||
|
val ultimoAcessoIdx = headers.indexOfFirst { it == "ultimo_acesso" || it.contains("acesso") || it.contains("data") || it.contains("timestamp") }
|
||||||
|
.let { if (it != -1) it else 6 }
|
||||||
|
val statusIdx = headers.indexOfFirst { it == "status_sincronizacao" || it.contains("status") }
|
||||||
|
.let { if (it != -1) it else 7 }
|
||||||
|
|
||||||
|
val maxIdx = maxOf(deviceIdIdx, dispositivoIdx, emailIdx, nomeIdx, androidIdx, appIdx, ultimoAcessoIdx, statusIdx)
|
||||||
|
|
||||||
|
var existingRowIndex = -1 // 1-indexed line in sheet
|
||||||
|
for (i in 1 until rows.size) {
|
||||||
|
val row = rows[i]
|
||||||
|
if (deviceIdIdx < row.size && row[deviceIdIdx].trim().equals(info.deviceId.trim(), ignoreCase = true)) {
|
||||||
|
existingRowIndex = i + 1
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun buildRowValues(): List<String> {
|
||||||
|
val list = MutableList(maxIdx + 1) { "" }
|
||||||
|
list[deviceIdIdx] = info.deviceId
|
||||||
|
list[dispositivoIdx] = info.dispositivo
|
||||||
|
list[emailIdx] = info.email
|
||||||
|
list[nomeIdx] = info.nomeUsuario
|
||||||
|
list[androidIdx] = info.versaoAndroid
|
||||||
|
list[appIdx] = info.versaoApp
|
||||||
|
list[ultimoAcessoIdx] = info.ultimoAcesso
|
||||||
|
list[statusIdx] = info.statusSincronizacao
|
||||||
|
return list
|
||||||
|
}
|
||||||
|
|
||||||
|
val rowValues = buildRowValues()
|
||||||
|
|
||||||
|
if (existingRowIndex != -1) {
|
||||||
|
val endCol = getColumnLetter(rowValues.size)
|
||||||
|
updateValues("$sheetName!A$existingRowIndex:$endCol$existingRowIndex", listOf(rowValues))
|
||||||
|
Log.d(tag, "Successfully updated usage_history row $existingRowIndex for device_id: ${info.deviceId}")
|
||||||
|
} else {
|
||||||
|
appendValues("$sheetName!A:H", listOf(rowValues))
|
||||||
|
Log.d(tag, "Successfully appended new device access record to usage_history for device_id: ${info.deviceId}")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,13 +4,19 @@ import android.content.Context
|
|||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import com.example.data.local.MaintenanceDao
|
import com.example.data.local.MaintenanceDao
|
||||||
import com.example.data.model.MaintenanceActivity
|
import com.example.data.model.MaintenanceActivity
|
||||||
|
import com.example.data.model.OSFinding
|
||||||
import com.example.data.model.OSUpdateHistory
|
import com.example.data.model.OSUpdateHistory
|
||||||
import com.example.data.model.GoogleUser
|
import com.example.data.model.GoogleUser
|
||||||
import com.example.data.model.SyncConflictLog
|
import com.example.data.model.SyncConflictLog
|
||||||
|
import com.example.data.model.AppConfig
|
||||||
|
import com.example.data.model.AppSecurityState
|
||||||
import com.example.data.model.UserAccess
|
import com.example.data.model.UserAccess
|
||||||
|
import com.example.util.DeviceUtils
|
||||||
|
import com.example.util.VersionUtils
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import java.io.BufferedReader
|
import java.io.BufferedReader
|
||||||
import java.io.InputStreamReader
|
import java.io.InputStreamReader
|
||||||
@@ -33,17 +39,56 @@ class MaintenanceRepository(
|
|||||||
appLogDao.clearAllLogs()
|
appLogDao.clearAllLogs()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun logAppLog(level: String, tag: String, message: String, throwable: Throwable? = null) {
|
||||||
|
val logger = com.example.util.AppLogger.getInstance(context)
|
||||||
|
when (level.uppercase()) {
|
||||||
|
"ERROR" -> logger.logError(tag, message, throwable)
|
||||||
|
"WARN" -> logger.logWarning(tag, message)
|
||||||
|
else -> logger.logInfo(tag, message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val isNetworkConnected: Flow<Boolean> = networkMonitor.isConnected
|
val isNetworkConnected: Flow<Boolean> = networkMonitor.isConnected
|
||||||
fun isCurrentlyConnected(): Boolean = networkMonitor.isCurrentlyConnected()
|
fun isCurrentlyConnected(): Boolean = networkMonitor.isCurrentlyConnected()
|
||||||
|
|
||||||
val allActivities: Flow<List<MaintenanceActivity>> = dao.getAllActivities()
|
val allActivities: Flow<List<MaintenanceActivity>> = dao.getAllActivities()
|
||||||
|
|
||||||
|
val allConfigs: Flow<List<AppConfig>> = dao.getAllConfigsFlow()
|
||||||
|
|
||||||
|
val appSecurityState: Flow<AppSecurityState> = allConfigs.map { configs ->
|
||||||
|
evaluateSecurityState(configs)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun evaluateSecurityState(configs: List<AppConfig>): AppSecurityState {
|
||||||
|
val pararAcesso = configs.find { it.key.equals("PararAcessoApp", ignoreCase = true) }?.value?.trim() ?: "0"
|
||||||
|
if (pararAcesso == "1") {
|
||||||
|
return AppSecurityState.BlockedByMaintenance()
|
||||||
|
}
|
||||||
|
|
||||||
|
val minVersion = configs.find { it.key.equals("VersaoMinimaApp", ignoreCase = true) }?.value?.trim() ?: ""
|
||||||
|
if (minVersion.isNotBlank()) {
|
||||||
|
val currentVersion = DeviceUtils.getAppVersion(context)
|
||||||
|
if (VersionUtils.isVersionLower(currentVersion, minVersion)) {
|
||||||
|
return AppSecurityState.BlockedByVersion(
|
||||||
|
minVersion = minVersion,
|
||||||
|
currentVersion = VersionUtils.sanitizeVersionString(currentVersion)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return AppSecurityState.Allowed
|
||||||
|
}
|
||||||
|
|
||||||
val allHistory: Flow<List<OSUpdateHistory>> = dao.getAllHistoryFlow()
|
val allHistory: Flow<List<OSUpdateHistory>> = dao.getAllHistoryFlow()
|
||||||
|
|
||||||
fun getActivityByOs(numeroOs: String): Flow<MaintenanceActivity?> = dao.getActivityByOs(numeroOs)
|
fun getActivityByOs(numeroOs: String): Flow<MaintenanceActivity?> = dao.getActivityByOs(numeroOs)
|
||||||
|
|
||||||
fun getHistoryForOs(numeroOs: String): Flow<List<OSUpdateHistory>> = dao.getHistoryForOs(numeroOs)
|
fun getHistoryForOs(numeroOs: String): Flow<List<OSUpdateHistory>> = dao.getHistoryForOs(numeroOs)
|
||||||
|
|
||||||
|
fun getFindingsForOs(numeroOs: String): Flow<List<OSFinding>> = dao.getFindingsForOs(numeroOs)
|
||||||
|
|
||||||
|
fun getLatestObservationForOs(numeroOs: String): Flow<OSFinding?> = dao.getLatestObservationForOs(numeroOs)
|
||||||
|
|
||||||
suspend fun getUserAccess(email: String): UserAccess? = withContext(Dispatchers.IO) {
|
suspend fun getUserAccess(email: String): UserAccess? = withContext(Dispatchers.IO) {
|
||||||
dao.getUserAccess(email)
|
dao.getUserAccess(email)
|
||||||
}
|
}
|
||||||
@@ -53,7 +98,7 @@ class MaintenanceRepository(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Updates progress of an OS, auto-generates a history record, and marks as unsynced (offline-first).
|
* Updates progress of an OS, auto-generates a history record, updates observation finding, and marks as unsynced.
|
||||||
*/
|
*/
|
||||||
suspend fun updateProgress(
|
suspend fun updateProgress(
|
||||||
numeroOs: String,
|
numeroOs: String,
|
||||||
@@ -61,7 +106,8 @@ class MaintenanceRepository(
|
|||||||
observacao: String?,
|
observacao: String?,
|
||||||
fotoPath: String?,
|
fotoPath: String?,
|
||||||
recurso: String,
|
recurso: String,
|
||||||
emailEditor: String?
|
emailEditor: String?,
|
||||||
|
customTimestampMillis: Long? = null
|
||||||
) = withContext(Dispatchers.IO) {
|
) = withContext(Dispatchers.IO) {
|
||||||
// Validate system date only when online
|
// Validate system date only when online
|
||||||
val isOnline = isCurrentlyConnected()
|
val isOnline = isCurrentlyConnected()
|
||||||
@@ -71,13 +117,74 @@ class MaintenanceRepository(
|
|||||||
}
|
}
|
||||||
|
|
||||||
val currentActivity = dao.getActivityByOsOneShot(numeroOs) ?: return@withContext
|
val currentActivity = dao.getActivityByOsOneShot(numeroOs) ?: return@withContext
|
||||||
|
val effectiveTimestamp = customTimestampMillis ?: System.currentTimeMillis()
|
||||||
|
|
||||||
|
// Handle text observation as OSFinding of type OBS
|
||||||
|
val cleanObs = stripAuditTags(observacao)
|
||||||
|
if (cleanObs != null) {
|
||||||
|
val existingObsFinding = dao.getLatestObservationForOsOneShot(numeroOs)
|
||||||
|
val findingObs = if (existingObsFinding != null) {
|
||||||
|
existingObsFinding.copy(
|
||||||
|
descricao = cleanObs,
|
||||||
|
timestamp = effectiveTimestamp,
|
||||||
|
responsavel = recurso,
|
||||||
|
emailEditor = emailEditor,
|
||||||
|
synced = false
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
OSFinding(
|
||||||
|
id = java.util.UUID.randomUUID().toString(),
|
||||||
|
numeroOs = numeroOs,
|
||||||
|
tipo = "OBS",
|
||||||
|
descricao = cleanObs,
|
||||||
|
timestamp = effectiveTimestamp,
|
||||||
|
responsavel = recurso,
|
||||||
|
emailEditor = emailEditor,
|
||||||
|
fotoPath = null,
|
||||||
|
synced = false
|
||||||
|
)
|
||||||
|
}
|
||||||
|
dao.insertFinding(findingObs)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle photos as exclusive OSFinding of type FOTO
|
||||||
|
if (!fotoPath.isNullOrBlank()) {
|
||||||
|
val existingPhotoFinding = dao.getPhotoFindingForOsOneShot(numeroOs)
|
||||||
|
val findingPhoto = if (existingPhotoFinding != null) {
|
||||||
|
val mergedFotoPath = mergePreservingDeletedPhotos(existingPhotoFinding.fotoPath, fotoPath)
|
||||||
|
existingPhotoFinding.copy(
|
||||||
|
tipo = "FOTO",
|
||||||
|
descricao = if (existingPhotoFinding.descricao.isNotBlank() && existingPhotoFinding.descricao != "Foto anexada") existingPhotoFinding.descricao else "Foto anexada",
|
||||||
|
timestamp = effectiveTimestamp,
|
||||||
|
responsavel = recurso,
|
||||||
|
emailEditor = emailEditor,
|
||||||
|
fotoPath = mergedFotoPath,
|
||||||
|
synced = false
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
OSFinding(
|
||||||
|
id = java.util.UUID.randomUUID().toString(),
|
||||||
|
numeroOs = numeroOs,
|
||||||
|
tipo = "FOTO",
|
||||||
|
descricao = "Foto anexada",
|
||||||
|
timestamp = effectiveTimestamp,
|
||||||
|
responsavel = recurso,
|
||||||
|
emailEditor = emailEditor,
|
||||||
|
fotoPath = fotoPath,
|
||||||
|
synced = false
|
||||||
|
)
|
||||||
|
}
|
||||||
|
dao.insertFinding(findingPhoto)
|
||||||
|
}
|
||||||
|
|
||||||
|
val latestObsText = cleanObs ?: stripAuditTags(currentActivity.observacoes)
|
||||||
|
|
||||||
val updatedActivity = currentActivity.copy(
|
val updatedActivity = currentActivity.copy(
|
||||||
percentualExecucao = novoPercentual.coerceIn(0, 100),
|
percentualExecucao = novoPercentual.coerceIn(0, 100),
|
||||||
observacoes = observacao ?: currentActivity.observacoes,
|
observacoes = latestObsText,
|
||||||
fotoPath = fotoPath ?: currentActivity.fotoPath,
|
fotoPath = fotoPath ?: currentActivity.fotoPath,
|
||||||
synced = false, // Must sync later
|
synced = false, // Must sync later
|
||||||
lastUpdated = System.currentTimeMillis()
|
lastUpdated = effectiveTimestamp
|
||||||
)
|
)
|
||||||
|
|
||||||
dao.updateActivity(updatedActivity)
|
dao.updateActivity(updatedActivity)
|
||||||
@@ -85,9 +192,10 @@ class MaintenanceRepository(
|
|||||||
// Log to history
|
// Log to history
|
||||||
val historyEntry = OSUpdateHistory(
|
val historyEntry = OSUpdateHistory(
|
||||||
numeroOs = numeroOs,
|
numeroOs = numeroOs,
|
||||||
|
timestamp = effectiveTimestamp,
|
||||||
percentualAnterior = currentActivity.percentualExecucao,
|
percentualAnterior = currentActivity.percentualExecucao,
|
||||||
percentualNovo = novoPercentual,
|
percentualNovo = novoPercentual,
|
||||||
observacao = observacao,
|
observacao = if (cleanObs != null) "[Observação Atualizada] $cleanObs" else null,
|
||||||
fotoPath = fotoPath,
|
fotoPath = fotoPath,
|
||||||
recurso = recurso,
|
recurso = recurso,
|
||||||
emailEditor = emailEditor
|
emailEditor = emailEditor
|
||||||
@@ -95,6 +203,148 @@ class MaintenanceRepository(
|
|||||||
dao.insertHistory(historyEntry)
|
dao.insertHistory(historyEntry)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds a new Achado (Segurança, Manutenção, ou Observação) and logs audit entry in history.
|
||||||
|
*/
|
||||||
|
suspend fun addFinding(
|
||||||
|
numeroOs: String,
|
||||||
|
tipo: String,
|
||||||
|
descricao: String,
|
||||||
|
recurso: String,
|
||||||
|
emailEditor: String?,
|
||||||
|
fotoPath: String? = null
|
||||||
|
) = withContext(Dispatchers.IO) {
|
||||||
|
val effectiveTimestamp = System.currentTimeMillis()
|
||||||
|
val finding = OSFinding(
|
||||||
|
numeroOs = numeroOs,
|
||||||
|
tipo = tipo,
|
||||||
|
descricao = descricao.trim(),
|
||||||
|
timestamp = effectiveTimestamp,
|
||||||
|
responsavel = recurso,
|
||||||
|
emailEditor = emailEditor,
|
||||||
|
fotoPath = fotoPath,
|
||||||
|
synced = false
|
||||||
|
)
|
||||||
|
dao.insertFinding(finding)
|
||||||
|
|
||||||
|
val currentActivity = dao.getActivityByOsOneShot(numeroOs)
|
||||||
|
if (tipo == "OBS" && currentActivity != null) {
|
||||||
|
dao.updateActivity(
|
||||||
|
currentActivity.copy(
|
||||||
|
observacoes = stripAuditTags(descricao),
|
||||||
|
synced = false,
|
||||||
|
lastUpdated = effectiveTimestamp
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val tagHeader = when (tipo) {
|
||||||
|
"SEGURANCA" -> "[Achado de Segurança Criado]"
|
||||||
|
"MANUTENCAO" -> "[Achado de Manutenção Criado]"
|
||||||
|
else -> "[Observação Criada]"
|
||||||
|
}
|
||||||
|
|
||||||
|
val historyEntry = OSUpdateHistory(
|
||||||
|
numeroOs = numeroOs,
|
||||||
|
timestamp = effectiveTimestamp,
|
||||||
|
percentualAnterior = currentActivity?.percentualExecucao ?: 0,
|
||||||
|
percentualNovo = currentActivity?.percentualExecucao ?: 0,
|
||||||
|
observacao = "$tagHeader ${descricao.trim()}",
|
||||||
|
fotoPath = fotoPath,
|
||||||
|
recurso = recurso,
|
||||||
|
emailEditor = emailEditor
|
||||||
|
)
|
||||||
|
dao.insertHistory(historyEntry)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates an existing Achado and logs audit entry in history.
|
||||||
|
*/
|
||||||
|
suspend fun updateFinding(
|
||||||
|
finding: OSFinding,
|
||||||
|
recurso: String,
|
||||||
|
emailEditor: String?
|
||||||
|
) = withContext(Dispatchers.IO) {
|
||||||
|
val effectiveTimestamp = System.currentTimeMillis()
|
||||||
|
val updatedFinding = finding.copy(
|
||||||
|
timestamp = effectiveTimestamp,
|
||||||
|
synced = false
|
||||||
|
)
|
||||||
|
dao.insertFinding(updatedFinding)
|
||||||
|
|
||||||
|
val currentActivity = dao.getActivityByOsOneShot(finding.numeroOs)
|
||||||
|
if (finding.tipo == "OBS" && currentActivity != null) {
|
||||||
|
dao.updateActivity(
|
||||||
|
currentActivity.copy(
|
||||||
|
observacoes = stripAuditTags(finding.descricao),
|
||||||
|
synced = false,
|
||||||
|
lastUpdated = effectiveTimestamp
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val tagHeader = when (finding.tipo) {
|
||||||
|
"SEGURANCA" -> "[Achado de Segurança Editado]"
|
||||||
|
"MANUTENCAO" -> "[Achado de Manutenção Editado]"
|
||||||
|
else -> "[Observação Editada]"
|
||||||
|
}
|
||||||
|
|
||||||
|
val historyEntry = OSUpdateHistory(
|
||||||
|
numeroOs = finding.numeroOs,
|
||||||
|
timestamp = effectiveTimestamp,
|
||||||
|
percentualAnterior = currentActivity?.percentualExecucao ?: 0,
|
||||||
|
percentualNovo = currentActivity?.percentualExecucao ?: 0,
|
||||||
|
observacao = "$tagHeader ${finding.descricao.trim()}",
|
||||||
|
fotoPath = finding.fotoPath,
|
||||||
|
recurso = recurso,
|
||||||
|
emailEditor = emailEditor
|
||||||
|
)
|
||||||
|
dao.insertHistory(historyEntry)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Physically deletes an Achado and logs audit entry of deletion in history.
|
||||||
|
*/
|
||||||
|
suspend fun deleteFinding(
|
||||||
|
finding: OSFinding,
|
||||||
|
recurso: String,
|
||||||
|
emailEditor: String?
|
||||||
|
) = withContext(Dispatchers.IO) {
|
||||||
|
val effectiveTimestamp = System.currentTimeMillis()
|
||||||
|
dao.deleteFindingById(finding.id)
|
||||||
|
|
||||||
|
val currentActivity = dao.getActivityByOsOneShot(finding.numeroOs)
|
||||||
|
if (finding.tipo == "OBS" && currentActivity != null) {
|
||||||
|
val latestRemainingObs = dao.getLatestObservationForOsOneShot(finding.numeroOs)
|
||||||
|
dao.updateActivity(
|
||||||
|
currentActivity.copy(
|
||||||
|
observacoes = latestRemainingObs?.descricao,
|
||||||
|
synced = false,
|
||||||
|
lastUpdated = effectiveTimestamp
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val tagHeader = when (finding.tipo) {
|
||||||
|
"SEGURANCA" -> "[Achado de Segurança Excluído]"
|
||||||
|
"MANUTENCAO" -> "[Achado de Manutenção Excluído]"
|
||||||
|
else -> "[Observação Excluída]"
|
||||||
|
}
|
||||||
|
|
||||||
|
val historyEntry = OSUpdateHistory(
|
||||||
|
numeroOs = finding.numeroOs,
|
||||||
|
timestamp = effectiveTimestamp,
|
||||||
|
percentualAnterior = currentActivity?.percentualExecucao ?: 0,
|
||||||
|
percentualNovo = currentActivity?.percentualExecucao ?: 0,
|
||||||
|
observacao = "$tagHeader ${finding.descricao.trim()}",
|
||||||
|
fotoPath = null,
|
||||||
|
recurso = recurso,
|
||||||
|
emailEditor = emailEditor
|
||||||
|
)
|
||||||
|
dao.insertHistory(historyEntry)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
// Persist login state
|
// Persist login state
|
||||||
fun getSavedUser(): GoogleUser? {
|
fun getSavedUser(): GoogleUser? {
|
||||||
val prefs = context.getSharedPreferences("google_auth_prefs", Context.MODE_PRIVATE)
|
val prefs = context.getSharedPreferences("google_auth_prefs", Context.MODE_PRIVATE)
|
||||||
@@ -164,6 +414,7 @@ class MaintenanceRepository(
|
|||||||
val fimIdx = headers.indexOfFirst { it.contains("fim") || it.contains("end") || it.contains("termino") || it.contains("término") }
|
val fimIdx = headers.indexOfFirst { it.contains("fim") || it.contains("end") || it.contains("termino") || it.contains("término") }
|
||||||
val pctIdx = headers.indexOfFirst { it.contains("pct") || it.contains("%") || it.contains("percent") || it.contains("exec") }
|
val pctIdx = headers.indexOfFirst { it.contains("pct") || it.contains("%") || it.contains("percent") || it.contains("exec") }
|
||||||
val tagIdx = headers.indexOfFirst { it == "tag" || it.contains("tag") }
|
val tagIdx = headers.indexOfFirst { it == "tag" || it.contains("tag") }
|
||||||
|
val duracaoIdx = headers.indexOfFirst { it.contains("duração") || it.contains("duracao") || it.contains("horas") || (it.contains("dur") && !it.contains("recursos")) }
|
||||||
|
|
||||||
if (osIdx == -1) {
|
if (osIdx == -1) {
|
||||||
return@withContext Result.failure(Exception("Cabeçalho 'Número da OS' não encontrado no CSV."))
|
return@withContext Result.failure(Exception("Cabeçalho 'Número da OS' não encontrado no CSV."))
|
||||||
@@ -183,8 +434,10 @@ class MaintenanceRepository(
|
|||||||
val fim = if (fimIdx != -1 && row.size > fimIdx) row[fimIdx] else "N/A"
|
val fim = if (fimIdx != -1 && row.size > fimIdx) row[fimIdx] else "N/A"
|
||||||
val pctStr = if (pctIdx != -1 && row.size > pctIdx) row[pctIdx] else "0"
|
val pctStr = if (pctIdx != -1 && row.size > pctIdx) row[pctIdx] else "0"
|
||||||
val tag = if (tagIdx != -1 && row.size > tagIdx) row[tagIdx] else ""
|
val tag = if (tagIdx != -1 && row.size > tagIdx) row[tagIdx] else ""
|
||||||
|
val duracaoStr = if (duracaoIdx != -1 && row.size > duracaoIdx) row[duracaoIdx] else ""
|
||||||
|
|
||||||
val pct = pctStr.replace("%", "").trim().toIntOrNull() ?: 0
|
val pct = pctStr.replace("%", "").trim().toIntOrNull() ?: 0
|
||||||
|
val parsedHoras = duracaoStr.replace(Regex("[^0-9.,]"), "").replace(",", ".").toDoubleOrNull() ?: 0.0
|
||||||
val setorClean = sanitizeSetor(rawSetor)
|
val setorClean = sanitizeSetor(rawSetor)
|
||||||
val equipeClean = sanitizeEquipe(rawEquipe)
|
val equipeClean = sanitizeEquipe(rawEquipe)
|
||||||
|
|
||||||
@@ -199,6 +452,7 @@ class MaintenanceRepository(
|
|||||||
dataFim = fim,
|
dataFim = fim,
|
||||||
percentualExecucao = pct.coerceIn(0, 100),
|
percentualExecucao = pct.coerceIn(0, 100),
|
||||||
tag = tag,
|
tag = tag,
|
||||||
|
quantidadeHoras = parsedHoras,
|
||||||
synced = false,
|
synced = false,
|
||||||
lastUpdated = System.currentTimeMillis()
|
lastUpdated = System.currentTimeMillis()
|
||||||
)
|
)
|
||||||
@@ -226,6 +480,19 @@ class MaintenanceRepository(
|
|||||||
suspend fun synchronizeWithBackend(): SyncResult = withContext(Dispatchers.IO) {
|
suspend fun synchronizeWithBackend(): SyncResult = withContext(Dispatchers.IO) {
|
||||||
try {
|
try {
|
||||||
android.util.Log.d("MaintenanceRepository", "Starting Google Sheets synchronization...")
|
android.util.Log.d("MaintenanceRepository", "Starting Google Sheets synchronization...")
|
||||||
|
|
||||||
|
// 0. Initial Security State Check from Local Database
|
||||||
|
val localConfigs = dao.getAllConfigs()
|
||||||
|
val initialSecurity = evaluateSecurityState(localConfigs)
|
||||||
|
if (initialSecurity !is AppSecurityState.Allowed) {
|
||||||
|
val msg = when (initialSecurity) {
|
||||||
|
is AppSecurityState.BlockedByMaintenance -> initialSecurity.message
|
||||||
|
is AppSecurityState.BlockedByVersion -> initialSecurity.message
|
||||||
|
else -> "Sincronização bloqueada por trava de segurança."
|
||||||
|
}
|
||||||
|
android.util.Log.e("MaintenanceRepository", "Synchronization blocked by local security state: $msg")
|
||||||
|
return@withContext SyncResult.Error(msg)
|
||||||
|
}
|
||||||
|
|
||||||
// Validate system date only when online
|
// Validate system date only when online
|
||||||
val isOnline = isCurrentlyConnected()
|
val isOnline = isCurrentlyConnected()
|
||||||
@@ -254,6 +521,40 @@ class MaintenanceRepository(
|
|||||||
android.util.Log.e("MaintenanceRepository", "Falha ao carregar lista de acessos da planilha", e)
|
android.util.Log.e("MaintenanceRepository", "Falha ao carregar lista de acessos da planilha", e)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 0.01 Fetch remote configs and store locally
|
||||||
|
try {
|
||||||
|
val remoteConfigs = sheetsSyncService.fetchRemoteConfigs()
|
||||||
|
if (remoteConfigs.isNotEmpty()) {
|
||||||
|
dao.insertConfigs(remoteConfigs)
|
||||||
|
android.util.Log.d("MaintenanceRepository", "Sincronizadas ${remoteConfigs.size} configurações da planilha.")
|
||||||
|
val remoteSecurity = evaluateSecurityState(remoteConfigs)
|
||||||
|
if (remoteSecurity !is AppSecurityState.Allowed) {
|
||||||
|
val msg = when (remoteSecurity) {
|
||||||
|
is AppSecurityState.BlockedByMaintenance -> remoteSecurity.message
|
||||||
|
is AppSecurityState.BlockedByVersion -> remoteSecurity.message
|
||||||
|
else -> "Sincronização bloqueada por trava de segurança."
|
||||||
|
}
|
||||||
|
android.util.Log.w("MaintenanceRepository", "Sincronização interrompida devido a trava de segurança remota: $msg")
|
||||||
|
return@withContext SyncResult.Error(msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.e("MaintenanceRepository", "Falha ao carregar configurações da planilha", e)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 0.1 Check Remote Database Epoch for reset/cleanup signals
|
||||||
|
val remoteEpoch = try { sheetsSyncService.fetchDatabaseEpoch() } catch (e: Exception) { 1 }
|
||||||
|
val prefs = context.getSharedPreferences("google_auth_prefs", Context.MODE_PRIVATE)
|
||||||
|
val localEpoch = prefs.getInt("database_epoch", 0)
|
||||||
|
|
||||||
|
if (remoteEpoch > localEpoch) {
|
||||||
|
android.util.Log.d("MaintenanceRepository", "Database epoch mudou de $localEpoch para $remoteEpoch. Purgando todo o histórico e achados sincronizados locais para substituir completamente pela nova base remota...")
|
||||||
|
// Completely clear previously synced history and findings so local database is replaced by the new remote database
|
||||||
|
dao.deleteAllSyncedHistory()
|
||||||
|
dao.deleteAllSyncedFindings()
|
||||||
|
prefs.edit().putInt("database_epoch", remoteEpoch).apply()
|
||||||
|
}
|
||||||
|
|
||||||
// 1. Fetch remote OS definitions from the "project" sheet
|
// 1. Fetch remote OS definitions from the "project" sheet
|
||||||
val (remoteActivities, _) = sheetsSyncService.fetchRemoteActivities()
|
val (remoteActivities, _) = sheetsSyncService.fetchRemoteActivities()
|
||||||
|
|
||||||
@@ -264,35 +565,86 @@ class MaintenanceRepository(
|
|||||||
// 3. Fetch local history logs from Room DB
|
// 3. Fetch local history logs from Room DB
|
||||||
val localHistory = dao.getAllHistoryList()
|
val localHistory = dao.getAllHistoryList()
|
||||||
|
|
||||||
// 4. Reconcile and merge all history logs
|
// 4. Reconcile and merge all history logs prioritizing entries with remote URLs (http/https)
|
||||||
val allHistories = (remoteHistory + localHistory)
|
val localHistoryMap = localHistory.associateBy { "${it.numeroOs}_${it.timestamp}" }
|
||||||
.distinctBy { "${it.numeroOs}_${it.timestamp}" }
|
val remoteHistoryMap = remoteHistory.associateBy { "${it.numeroOs}_${it.timestamp}" }
|
||||||
.sortedByDescending { it.timestamp }
|
val allKeys = (localHistoryMap.keys + remoteHistoryMap.keys).toSet()
|
||||||
|
|
||||||
|
val allHistories = allKeys.map { key ->
|
||||||
|
val localItem = localHistoryMap[key]
|
||||||
|
val remoteItem = remoteHistoryMap[key]
|
||||||
|
|
||||||
|
when {
|
||||||
|
localItem != null && remoteItem != null -> {
|
||||||
|
val localHasDeleted = localItem.fotoPath?.contains("_DELETED") == true
|
||||||
|
val localHasUrl = localItem.fotoPath?.let { it.contains("http://") || it.contains("https://") } == true
|
||||||
|
val remoteHasUrl = remoteItem.fotoPath?.let { it.contains("http://") || it.contains("https://") } == true
|
||||||
|
// Always preserve local if it has _DELETED markings (user deleted a photo)
|
||||||
|
if (localHasDeleted) {
|
||||||
|
localItem
|
||||||
|
} else if (localHasUrl && !remoteHasUrl) {
|
||||||
|
localItem
|
||||||
|
} else {
|
||||||
|
remoteItem
|
||||||
|
}
|
||||||
|
}
|
||||||
|
localItem != null -> localItem
|
||||||
|
else -> remoteItem!!
|
||||||
|
}
|
||||||
|
}.sortedByDescending { it.timestamp }
|
||||||
|
|
||||||
// 5. Update local Room DB with any remote history logs we don't have
|
// 5. Update local Room DB with any remote history logs we don't have
|
||||||
val localHistoryKeys = localHistory.map { "${it.numeroOs}_${it.timestamp}" }.toSet()
|
val localHistoryKeys = localHistory.map { "${it.numeroOs}_${it.timestamp}" }.toSet()
|
||||||
val missingLocalHistory = remoteHistory.filter { "${it.numeroOs}_${it.timestamp}" !in localHistoryKeys }
|
val missingLocalHistory = remoteHistory.filter { "${it.numeroOs}_${it.timestamp}" !in localHistoryKeys }
|
||||||
if (missingLocalHistory.isNotEmpty()) {
|
if (missingLocalHistory.isNotEmpty()) {
|
||||||
for (hist in missingLocalHistory) {
|
for (hist in missingLocalHistory) {
|
||||||
dao.insertHistory(hist)
|
dao.insertHistory(hist.copy(synced = true))
|
||||||
}
|
}
|
||||||
android.util.Log.d("MaintenanceRepository", "Inserted ${missingLocalHistory.size} missing history logs locally.")
|
android.util.Log.d("MaintenanceRepository", "Inserted ${missingLocalHistory.size} missing history logs locally as synced.")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6. For each remote activity, determine its current state based on the latest history log
|
// 6. For each remote activity, determine its current state based on findings (achados) and history log
|
||||||
val reconciledActivities = remoteActivities.map { activity ->
|
val reconciledActivities = remoteActivities.map { activity ->
|
||||||
val osHistory = allHistories.filter { it.numeroOs == activity.numeroOs }
|
val osHistory = allHistories.filter { it.numeroOs == activity.numeroOs }
|
||||||
|
val osFindings = dao.getFindingsForOsOneShot(activity.numeroOs)
|
||||||
|
val localAct = dao.getActivityByOsOneShot(activity.numeroOs)
|
||||||
|
val localFotoPath = localAct?.fotoPath
|
||||||
|
val localHasRemoteUrl = localFotoPath?.let { it.contains("http://") || it.contains("https://") } == true
|
||||||
|
|
||||||
|
val findingsFotoPaths = osFindings.mapNotNull { it.fotoPath }
|
||||||
|
.flatMap { it.split("|") }
|
||||||
|
.map { it.trim() }
|
||||||
|
.filter { it.isNotBlank() }
|
||||||
|
|
||||||
if (osHistory.isNotEmpty()) {
|
if (osHistory.isNotEmpty()) {
|
||||||
val latestLog = osHistory.first() // sorted descending, so first is latest
|
val latestLog = osHistory.first() // sorted descending, so first is latest
|
||||||
|
val baseFotoPath = if (findingsFotoPaths.isNotEmpty()) {
|
||||||
|
findingsFotoPaths.distinct().joinToString("|")
|
||||||
|
} else if (localHasRemoteUrl && latestLog.fotoPath?.startsWith("http") != true) {
|
||||||
|
localFotoPath
|
||||||
|
} else {
|
||||||
|
latestLog.fotoPath ?: activity.fotoPath
|
||||||
|
}
|
||||||
|
val finalFotoPath = mergePreservingDeletedPhotos(localFotoPath, baseFotoPath)
|
||||||
|
val cleanLatestObs = stripAuditTags(latestLog.observacao) ?: stripAuditTags(activity.observacoes)
|
||||||
activity.copy(
|
activity.copy(
|
||||||
percentualExecucao = latestLog.percentualNovo,
|
percentualExecucao = latestLog.percentualNovo,
|
||||||
observacoes = latestLog.observacao ?: activity.observacoes,
|
observacoes = cleanLatestObs,
|
||||||
fotoPath = latestLog.fotoPath ?: activity.fotoPath,
|
fotoPath = finalFotoPath,
|
||||||
synced = true,
|
synced = true,
|
||||||
lastUpdated = latestLog.timestamp
|
lastUpdated = latestLog.timestamp
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
activity.copy(synced = true)
|
val baseFotoPath = if (findingsFotoPaths.isNotEmpty()) {
|
||||||
|
findingsFotoPaths.distinct().joinToString("|")
|
||||||
|
} else {
|
||||||
|
activity.fotoPath
|
||||||
|
}
|
||||||
|
val finalFotoPath = mergePreservingDeletedPhotos(localFotoPath, baseFotoPath)
|
||||||
|
activity.copy(
|
||||||
|
fotoPath = finalFotoPath,
|
||||||
|
synced = true
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -309,7 +661,7 @@ class MaintenanceRepository(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 8. Identify and resolve sync conflicts (LWW)
|
// 8. Identify and resolve sync conflicts (LWW)
|
||||||
val unuploadedLocalLogs = localHistory.filter { "${it.numeroOs}_${it.timestamp}" !in remoteHistoryKeys }
|
val unuploadedLocalLogs = localHistory.filter { !it.synced && "${it.numeroOs}_${it.timestamp}" !in remoteHistoryKeys }
|
||||||
val ossWithUnuploadedLogs = unuploadedLocalLogs.map { it.numeroOs }.toSet()
|
val ossWithUnuploadedLogs = unuploadedLocalLogs.map { it.numeroOs }.toSet()
|
||||||
|
|
||||||
val newRemoteLogs = remoteHistory.filter { "${it.numeroOs}_${it.timestamp}" !in localHistoryKeys }
|
val newRemoteLogs = remoteHistory.filter { "${it.numeroOs}_${it.timestamp}" !in localHistoryKeys }
|
||||||
@@ -356,13 +708,99 @@ class MaintenanceRepository(
|
|||||||
android.util.Log.d("MaintenanceRepository", "Inserted ${conflictLogsToInsert.size} resolved conflict logs.")
|
android.util.Log.d("MaintenanceRepository", "Inserted ${conflictLogsToInsert.size} resolved conflict logs.")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 9. Upload any local history logs that are not on Google Sheets yet
|
// 9. Upload any local history logs that are not on Google Sheets yet (only unsynced)
|
||||||
val historyToUpload = localHistory.filter { "${it.numeroOs}_${it.timestamp}" !in remoteHistoryKeys }
|
val historyToUpload = localHistory.filter { !it.synced && "${it.numeroOs}_${it.timestamp}" !in remoteHistoryKeys }
|
||||||
if (historyToUpload.isNotEmpty()) {
|
if (historyToUpload.isNotEmpty()) {
|
||||||
sheetsSyncService.pushHistoryToSheet(historyToUpload)
|
sheetsSyncService.pushHistoryToSheet(historyToUpload)
|
||||||
android.util.Log.d("MaintenanceRepository", "Uploaded ${historyToUpload.size} new local history logs to Google Sheet.")
|
val uploadedIds = historyToUpload.map { it.id }.filter { it != 0L }
|
||||||
|
if (uploadedIds.isNotEmpty()) {
|
||||||
|
dao.markHistorySynced(uploadedIds)
|
||||||
|
}
|
||||||
|
for (h in historyToUpload) {
|
||||||
|
dao.markHistorySyncedByOsAndTimestamp(h.numeroOs, h.timestamp)
|
||||||
|
}
|
||||||
|
android.util.Log.d("MaintenanceRepository", "Uploaded ${historyToUpload.size} new local history logs to Google Sheet and marked as synced.")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 10. Sync 'achados' sheet with local OSFinding database safely preserving local/uploaded photo paths
|
||||||
|
try {
|
||||||
|
val remoteFindings = sheetsSyncService.fetchRemoteFindingsList()
|
||||||
|
val localFindingsMap = dao.getAllFindingsList().associateBy { it.id }
|
||||||
|
|
||||||
|
val reconciledFindings = remoteFindings.map { remote ->
|
||||||
|
val local = localFindingsMap[remote.id]
|
||||||
|
if (local != null) {
|
||||||
|
val finalFotoPath = mergePreservingDeletedPhotos(local.fotoPath, remote.fotoPath)
|
||||||
|
if (!local.synced) {
|
||||||
|
local.copy(fotoPath = finalFotoPath)
|
||||||
|
} else {
|
||||||
|
remote.copy(
|
||||||
|
fotoPath = finalFotoPath,
|
||||||
|
synced = local.synced && (finalFotoPath == remote.fotoPath)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
remote
|
||||||
|
}
|
||||||
|
}.toMutableList()
|
||||||
|
|
||||||
|
// Keep local findings that do not exist on the remote sheet yet
|
||||||
|
val remoteIds = remoteFindings.map { it.id }.toSet()
|
||||||
|
val localOnlyFindings = localFindingsMap.values.filter { it.id !in remoteIds }
|
||||||
|
reconciledFindings.addAll(localOnlyFindings)
|
||||||
|
|
||||||
|
// Consolidate duplicate FOTO and OBS findings for the same OS into single OSFinding rows
|
||||||
|
val consolidatedFindings = mutableListOf<OSFinding>()
|
||||||
|
val groupedByOsAndType = reconciledFindings.groupBy { Pair(it.numeroOs, if (it.tipo == "FOTO" || !it.fotoPath.isNullOrBlank()) "FOTO" else it.tipo) }
|
||||||
|
|
||||||
|
groupedByOsAndType.forEach { (key, findingsList) ->
|
||||||
|
val (osNum, groupType) = key
|
||||||
|
if (findingsList.size > 1) {
|
||||||
|
val latestItem = findingsList.maxByOrNull { it.timestamp } ?: findingsList.first()
|
||||||
|
val mergedPhotoPath = findingsList.mapNotNull { it.fotoPath }
|
||||||
|
.flatMap { it.split("|") }
|
||||||
|
.map { it.trim() }
|
||||||
|
.filter { it.isNotBlank() }
|
||||||
|
.distinct()
|
||||||
|
.joinToString("|")
|
||||||
|
.ifEmpty { null }
|
||||||
|
|
||||||
|
consolidatedFindings.add(
|
||||||
|
latestItem.copy(
|
||||||
|
tipo = groupType,
|
||||||
|
fotoPath = mergedPhotoPath
|
||||||
|
)
|
||||||
|
)
|
||||||
|
// Cleanup duplicate IDs from Room DB
|
||||||
|
val duplicateIds = findingsList.map { it.id }.filter { it != latestItem.id }
|
||||||
|
duplicateIds.forEach { dupId -> dao.deleteFindingById(dupId) }
|
||||||
|
} else {
|
||||||
|
val single = findingsList.first()
|
||||||
|
if (!single.fotoPath.isNullOrBlank() && single.tipo != "FOTO") {
|
||||||
|
consolidatedFindings.add(single.copy(tipo = "FOTO"))
|
||||||
|
} else {
|
||||||
|
consolidatedFindings.add(single)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (consolidatedFindings.isNotEmpty()) {
|
||||||
|
dao.insertFindings(consolidatedFindings)
|
||||||
|
}
|
||||||
|
|
||||||
|
val allLocalActiveFindings = dao.getAllFindingsList()
|
||||||
|
sheetsSyncService.syncFindingsWithSheet(allLocalActiveFindings)
|
||||||
|
android.util.Log.d("MaintenanceRepository", "Synced ${allLocalActiveFindings.size} active findings with Google Sheet.")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.e("MaintenanceRepository", "Falha ao sincronizar aba achados", e)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
recordDeviceAccessLog("Sucesso")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.e("MaintenanceRepository", "Falha ao registrar log de uso do dispositivo", e)
|
||||||
|
}
|
||||||
|
|
||||||
SyncResult.Success(
|
SyncResult.Success(
|
||||||
syncedItems = reconciledActivities.size,
|
syncedItems = reconciledActivities.size,
|
||||||
conflictsResolved = conflictingOSs.size
|
conflictsResolved = conflictingOSs.size
|
||||||
@@ -373,6 +811,42 @@ class MaintenanceRepository(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun recordDeviceAccessLog(status: String = "Sucesso") {
|
||||||
|
try {
|
||||||
|
val savedUser = getSavedUser()
|
||||||
|
val firebaseUser = try {
|
||||||
|
com.google.firebase.auth.FirebaseAuth.getInstance().currentUser
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
val email = savedUser?.email ?: firebaseUser?.email ?: ""
|
||||||
|
val name = savedUser?.displayName ?: firebaseUser?.displayName ?: ""
|
||||||
|
|
||||||
|
val deviceId = com.example.util.DeviceUtils.getDeviceId(context)
|
||||||
|
val model = com.example.util.DeviceUtils.getDeviceModel()
|
||||||
|
val androidVer = com.example.util.DeviceUtils.getAndroidVersion()
|
||||||
|
val appVer = com.example.util.DeviceUtils.getAppVersion(context)
|
||||||
|
|
||||||
|
val sdf = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault())
|
||||||
|
val formattedTime = sdf.format(java.util.Date())
|
||||||
|
|
||||||
|
val accessInfo = com.example.data.model.DeviceAccessInfo(
|
||||||
|
deviceId = deviceId,
|
||||||
|
dispositivo = model,
|
||||||
|
email = email,
|
||||||
|
nomeUsuario = name,
|
||||||
|
versaoAndroid = androidVer,
|
||||||
|
versaoApp = appVer,
|
||||||
|
ultimoAcesso = formattedTime,
|
||||||
|
statusSincronizacao = status
|
||||||
|
)
|
||||||
|
|
||||||
|
sheetsSyncService.updateUsageHistory(accessInfo)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.e("MaintenanceRepository", "Falha ao registrar histórico de uso do dispositivo", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun sanitizeSetor(setor: String): String {
|
private fun sanitizeSetor(setor: String): String {
|
||||||
val s = setor.trim()
|
val s = setor.trim()
|
||||||
if (s.isBlank()) return "Preparação"
|
if (s.isBlank()) return "Preparação"
|
||||||
@@ -452,12 +926,12 @@ class MaintenanceRepository(
|
|||||||
val sanitizedOs = osNumber.replace("/", "_").replace(" ", "")
|
val sanitizedOs = osNumber.replace("/", "_").replace(" ", "")
|
||||||
val targetFile = java.io.File(photosDir, "OS_${sanitizedOs}_${timestamp}.jpg")
|
val targetFile = java.io.File(photosDir, "OS_${sanitizedOs}_${timestamp}.jpg")
|
||||||
|
|
||||||
context.contentResolver.openInputStream(uri)?.use { input ->
|
return com.example.util.ImageCompressor.compressUriToJpegFile(
|
||||||
targetFile.outputStream().use { output ->
|
context = context,
|
||||||
input.copyTo(output)
|
uri = uri,
|
||||||
}
|
targetFile = targetFile,
|
||||||
}
|
maxSizeBytes = 500 * 1024L
|
||||||
return targetFile.absolutePath
|
).absolutePath
|
||||||
}
|
}
|
||||||
|
|
||||||
fun createTempCameraPhotoUri(osNumber: String): Pair<Uri, String> {
|
fun createTempCameraPhotoUri(osNumber: String): Pair<Uri, String> {
|
||||||
@@ -474,6 +948,49 @@ class MaintenanceRepository(
|
|||||||
suspend fun uploadPendingPhotos() = withContext(Dispatchers.IO) {
|
suspend fun uploadPendingPhotos() = withContext(Dispatchers.IO) {
|
||||||
if (!isCurrentlyConnected()) return@withContext
|
if (!isCurrentlyConnected()) return@withContext
|
||||||
|
|
||||||
|
// Collect all local→URL replacements per OS to batch-update activity fotoPath
|
||||||
|
val replacementsByOs = mutableMapOf<String, MutableList<Pair<String, String>>>()
|
||||||
|
|
||||||
|
// 1. Process local photos in OSFinding (achados)
|
||||||
|
val findingsList = dao.getAllFindingsList()
|
||||||
|
for (finding in findingsList) {
|
||||||
|
val rawPath = finding.fotoPath
|
||||||
|
if (!rawPath.isNullOrBlank()) {
|
||||||
|
val subPaths = rawPath.split("|")
|
||||||
|
var changed = false
|
||||||
|
val uploadedSubPaths = subPaths.map { path ->
|
||||||
|
val trimmed = path.trim()
|
||||||
|
if (trimmed.isNotBlank() && !trimmed.startsWith("http://") && !trimmed.startsWith("https://") && !trimmed.endsWith("_DELETED") && !trimmed.contains("_DELETED")) {
|
||||||
|
val file = java.io.File(trimmed)
|
||||||
|
if (file.exists()) {
|
||||||
|
try {
|
||||||
|
val compressedFile = com.example.util.ImageCompressor.compressImageFile(file, 500 * 1024L)
|
||||||
|
val result = firebaseStorageSyncService.uploadPhoto(compressedFile, finding.numeroOs)
|
||||||
|
changed = true
|
||||||
|
replacementsByOs.getOrPut(finding.numeroOs) { mutableListOf() }
|
||||||
|
.add(Pair(trimmed, result.storagePath))
|
||||||
|
result.storagePath
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.e("MaintenanceRepository", "Falha no upload da foto ${file.name} para o Firebase Storage: ${e.message}", e)
|
||||||
|
trimmed
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
trimmed
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
trimmed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (changed) {
|
||||||
|
val updatedJoinedPath = uploadedSubPaths.joinToString("|")
|
||||||
|
val updatedFinding = finding.copy(fotoPath = updatedJoinedPath, synced = false)
|
||||||
|
dao.insertFinding(updatedFinding)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Process local photos in OSUpdateHistory (history)
|
||||||
val historyList = dao.getAllHistoryList()
|
val historyList = dao.getAllHistoryList()
|
||||||
for (history in historyList) {
|
for (history in historyList) {
|
||||||
val rawPath = history.fotoPath
|
val rawPath = history.fotoPath
|
||||||
@@ -482,13 +999,16 @@ class MaintenanceRepository(
|
|||||||
var changed = false
|
var changed = false
|
||||||
val uploadedSubPaths = subPaths.map { path ->
|
val uploadedSubPaths = subPaths.map { path ->
|
||||||
val trimmed = path.trim()
|
val trimmed = path.trim()
|
||||||
if (trimmed.isNotBlank() && !trimmed.startsWith("http://") && !trimmed.startsWith("https://") && !trimmed.endsWith("_DELETED")) {
|
if (trimmed.isNotBlank() && !trimmed.startsWith("http://") && !trimmed.startsWith("https://") && !trimmed.endsWith("_DELETED") && !trimmed.contains("_DELETED")) {
|
||||||
val file = java.io.File(trimmed)
|
val file = java.io.File(trimmed)
|
||||||
if (file.exists()) {
|
if (file.exists()) {
|
||||||
try {
|
try {
|
||||||
val result = firebaseStorageSyncService.uploadPhoto(file, history.numeroOs)
|
val compressedFile = com.example.util.ImageCompressor.compressImageFile(file, 500 * 1024L)
|
||||||
|
val result = firebaseStorageSyncService.uploadPhoto(compressedFile, history.numeroOs)
|
||||||
changed = true
|
changed = true
|
||||||
result.downloadUrl
|
replacementsByOs.getOrPut(history.numeroOs) { mutableListOf() }
|
||||||
|
.add(Pair(trimmed, result.storagePath))
|
||||||
|
result.storagePath
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
android.util.Log.e("MaintenanceRepository", "Falha no upload da foto ${file.name} para o Firebase Storage: ${e.message}", e)
|
android.util.Log.e("MaintenanceRepository", "Falha no upload da foto ${file.name} para o Firebase Storage: ${e.message}", e)
|
||||||
trimmed
|
trimmed
|
||||||
@@ -505,14 +1025,86 @@ class MaintenanceRepository(
|
|||||||
val updatedJoinedPath = uploadedSubPaths.joinToString("|")
|
val updatedJoinedPath = uploadedSubPaths.joinToString("|")
|
||||||
val updatedHistory = history.copy(fotoPath = updatedJoinedPath)
|
val updatedHistory = history.copy(fotoPath = updatedJoinedPath)
|
||||||
dao.insertHistory(updatedHistory)
|
dao.insertHistory(updatedHistory)
|
||||||
|
|
||||||
val activity = dao.getActivityByOsOneShot(history.numeroOs)
|
|
||||||
if (activity != null) {
|
|
||||||
dao.updateActivity(activity.copy(fotoPath = updatedJoinedPath))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Now update each activity's fotoPath by replacing local paths with uploaded URLs
|
||||||
|
// without overwriting the entire fotoPath (preserves photos from other history entries)
|
||||||
|
for ((osNumber, replacements) in replacementsByOs) {
|
||||||
|
val activity = dao.getActivityByOsOneShot(osNumber) ?: continue
|
||||||
|
val currentFotoPath = activity.fotoPath ?: continue
|
||||||
|
var updatedFotoPath = currentFotoPath
|
||||||
|
for ((localPath, uploadedUrl) in replacements) {
|
||||||
|
// Replace the local path with the uploaded URL in the full pipe-separated string
|
||||||
|
updatedFotoPath = updatedFotoPath.split("|").joinToString("|") { p ->
|
||||||
|
if (p.trim() == localPath.trim()) uploadedUrl else p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (updatedFotoPath != currentFotoPath) {
|
||||||
|
dao.updateActivity(activity.copy(fotoPath = updatedFotoPath))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stripAuditTags(text: String?): String? {
|
||||||
|
if (text.isNullOrBlank()) return null
|
||||||
|
var result = text.trim()
|
||||||
|
val regex = Regex("^(\\[[^\\]]+\\]\\s*)+")
|
||||||
|
result = regex.replace(result, "").trim()
|
||||||
|
return result.ifBlank { null }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun extractPhotoFileName(path: String): String {
|
||||||
|
val clean = path.trim().substringBefore("?").substringBefore("#")
|
||||||
|
// Handle both regular slashes and URL-encoded slashes (%2F)
|
||||||
|
val decoded = clean.replace("%2F", "/", ignoreCase = true)
|
||||||
|
val fileName = decoded.substringAfterLast("/").substringAfterLast("\\")
|
||||||
|
return fileName.removeSuffix("_DELETED").removeSuffix(".jpg_DELETED").let {
|
||||||
|
// Also handle _DELETED inserted before extension: photo_DELETED.jpg
|
||||||
|
it.replace("_DELETED", "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isSamePhoto(path1: String?, path2: String?): Boolean {
|
||||||
|
if (path1.isNullOrBlank() || path2.isNullOrBlank()) return false
|
||||||
|
val p1 = path1.trim()
|
||||||
|
val p2 = path2.trim()
|
||||||
|
if (p1 == p2) return true
|
||||||
|
val name1 = extractPhotoFileName(p1)
|
||||||
|
val name2 = extractPhotoFileName(p2)
|
||||||
|
return name1.isNotBlank() && name1 == name2
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun mergePreservingDeletedPhotos(localPath: String?, remotePath: String?): String? {
|
||||||
|
if (localPath.isNullOrBlank()) return remotePath
|
||||||
|
if (remotePath.isNullOrBlank()) return localPath
|
||||||
|
|
||||||
|
val localSubPaths = localPath.split("|").map { it.trim() }.filter { it.isNotBlank() }
|
||||||
|
val remoteSubPaths = remotePath.split("|").map { it.trim() }.filter { it.isNotBlank() }
|
||||||
|
|
||||||
|
val result = mutableListOf<String>()
|
||||||
|
for (remote in remoteSubPaths) {
|
||||||
|
val matchingLocal = localSubPaths.find { isSamePhoto(it, remote) }
|
||||||
|
if (matchingLocal != null && (matchingLocal.endsWith("_DELETED") || matchingLocal.contains("_DELETED"))) {
|
||||||
|
if (!result.contains(matchingLocal)) {
|
||||||
|
result.add(matchingLocal)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val photoToAdd = matchingLocal ?: remote
|
||||||
|
if (!result.contains(photoToAdd)) {
|
||||||
|
result.add(photoToAdd)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (local in localSubPaths) {
|
||||||
|
if (!result.any { isSamePhoto(it, local) }) {
|
||||||
|
result.add(local)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.joinToString("|").ifEmpty { null }
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun softDeletePhoto(targetPhotoPath: String, osNumber: String) = withContext(Dispatchers.IO) {
|
suspend fun softDeletePhoto(targetPhotoPath: String, osNumber: String) = withContext(Dispatchers.IO) {
|
||||||
@@ -524,27 +1116,75 @@ class MaintenanceRepository(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val deletedTarget = if (targetPhotoPath.endsWith("_DELETED")) targetPhotoPath else "${targetPhotoPath}_DELETED"
|
|
||||||
|
|
||||||
// Update history entries by replacing target photo or appending _DELETED
|
// Update history entries by replacing target photo or appending _DELETED
|
||||||
val historyList = dao.getHistoryForOsOneShot(osNumber)
|
val historyList = dao.getHistoryForOsOneShot(osNumber)
|
||||||
for (hist in historyList) {
|
for (hist in historyList) {
|
||||||
val pathStr = hist.fotoPath
|
val pathStr = hist.fotoPath
|
||||||
if (!pathStr.isNullOrBlank() && pathStr.contains(targetPhotoPath)) {
|
if (!pathStr.isNullOrBlank() && pathStr.split("|").any { isSamePhoto(it, targetPhotoPath) }) {
|
||||||
val updatedPaths = pathStr.split("|").map { p ->
|
val updatedPaths = pathStr.split("|").map { p ->
|
||||||
if (p.trim() == targetPhotoPath.trim()) deletedTarget else p
|
if (isSamePhoto(p, targetPhotoPath)) {
|
||||||
|
if (p.contains("_DELETED")) p else "${p}_DELETED"
|
||||||
|
} else p
|
||||||
}
|
}
|
||||||
dao.insertHistory(hist.copy(fotoPath = updatedPaths.joinToString("|")))
|
dao.insertHistory(hist.copy(fotoPath = updatedPaths.joinToString("|")))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Update OS Activity entry
|
||||||
val activity = dao.getActivityByOsOneShot(osNumber)
|
val activity = dao.getActivityByOsOneShot(osNumber)
|
||||||
if (activity != null && !activity.fotoPath.isNullOrBlank() && activity.fotoPath.contains(targetPhotoPath)) {
|
if (activity != null && !activity.fotoPath.isNullOrBlank() && activity.fotoPath.split("|").any { isSamePhoto(it, targetPhotoPath) }) {
|
||||||
val updatedPaths = activity.fotoPath.split("|").map { p ->
|
val updatedPaths = activity.fotoPath.split("|").map { p ->
|
||||||
if (p.trim() == targetPhotoPath.trim()) deletedTarget else p
|
if (isSamePhoto(p, targetPhotoPath)) {
|
||||||
|
if (p.contains("_DELETED")) p else "${p}_DELETED"
|
||||||
|
} else p
|
||||||
}
|
}
|
||||||
dao.updateActivity(activity.copy(fotoPath = updatedPaths.joinToString("|"), synced = false))
|
dao.updateActivity(activity.copy(fotoPath = updatedPaths.joinToString("|"), synced = false))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Update OSFinding entries
|
||||||
|
val findingsList = dao.getFindingsForOsOneShot(osNumber)
|
||||||
|
for (finding in findingsList) {
|
||||||
|
val fPath = finding.fotoPath
|
||||||
|
if (!fPath.isNullOrBlank() && fPath.split("|").any { isSamePhoto(it, targetPhotoPath) }) {
|
||||||
|
val updatedPaths = fPath.split("|").map { p ->
|
||||||
|
if (isSamePhoto(p, targetPhotoPath)) {
|
||||||
|
if (p.contains("_DELETED")) p else "${p}_DELETED"
|
||||||
|
} else p
|
||||||
|
}
|
||||||
|
dao.insertFinding(finding.copy(fotoPath = updatedPaths.joinToString("|"), synced = false))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun seedDefaultConfigsIfEmpty() = withContext(Dispatchers.IO) {
|
||||||
|
val existing = dao.getAllConfigs()
|
||||||
|
if (existing.isEmpty()) {
|
||||||
|
val defaults = listOf(
|
||||||
|
com.example.data.model.AppConfig("database_epoch", "3", "Versão da base de dados. Incremente em +1 ao alterar/limpar a planilha"),
|
||||||
|
com.example.data.model.AppConfig("Link1", "https://forms.office.com/Pages/ResponsePage.aspx?id=IYw2V8-4z0K9C0Ps1LxirnRboL6yMAxJn4T7PLeH0KtURjNLNlNJQTdHU0JMVlVNMlJISlNTSFJFRyQlQCN0PWcu&origin=APPgestaoos", "Link para ser exibido na tela de informações"),
|
||||||
|
com.example.data.model.AppConfig("DescricaoLink1", "Link do RDS (Relato de Segurança)", "Link do RDS (Relato de Segurança)"),
|
||||||
|
com.example.data.model.AppConfig("Link2", "https://exemple.com", "Link de informações de privacidade do app"),
|
||||||
|
com.example.data.model.AppConfig("DescricaoLink2", "Informações de privacidade do APP", "Informações de privacidade"),
|
||||||
|
com.example.data.model.AppConfig("Link3", "https://exemple.com", null),
|
||||||
|
com.example.data.model.AppConfig("DescricaoLink3", "Termos de uso deste APP", "Termos de uso do APP"),
|
||||||
|
com.example.data.model.AppConfig("VersaoMinimaApp", "1.0.0", "Versão mínima para funcionar o aplicativo sem trava-lo e exigir atualização"),
|
||||||
|
com.example.data.model.AppConfig("PararAcessoApp", "0", "0 = Permite acesso ao app; 1 = Trava o acesso ao app")
|
||||||
|
)
|
||||||
|
dao.insertConfigs(defaults)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun refreshConfigs(): List<com.example.data.model.AppConfig> = withContext(Dispatchers.IO) {
|
||||||
|
try {
|
||||||
|
val configs = sheetsSyncService.fetchRemoteConfigs()
|
||||||
|
if (configs.isNotEmpty()) {
|
||||||
|
dao.insertConfigs(configs)
|
||||||
|
}
|
||||||
|
configs
|
||||||
|
} catch (e: Exception) {
|
||||||
|
android.util.Log.e("MaintenanceRepository", "Erro ao atualizar configs", e)
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,302 @@
|
|||||||
|
package com.example.ui.components
|
||||||
|
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.activity.compose.BackHandler
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Block
|
||||||
|
import androidx.compose.material.icons.filled.ContentCopy
|
||||||
|
import androidx.compose.material.icons.filled.Email
|
||||||
|
import androidx.compose.material.icons.filled.Refresh
|
||||||
|
import androidx.compose.material.icons.filled.SystemUpdate
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.compose.ui.window.Dialog
|
||||||
|
import androidx.compose.ui.window.DialogProperties
|
||||||
|
import com.example.data.model.AppSecurityState
|
||||||
|
import com.example.data.model.SecurityContact
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun AppSecurityLockDialog(
|
||||||
|
securityState: AppSecurityState,
|
||||||
|
isRefreshing: Boolean = false,
|
||||||
|
onRetryCheck: () -> Unit
|
||||||
|
) {
|
||||||
|
if (securityState is AppSecurityState.Allowed) return
|
||||||
|
|
||||||
|
// Prevent physical back button navigation
|
||||||
|
BackHandler(enabled = true) { }
|
||||||
|
|
||||||
|
val context = LocalContext.current
|
||||||
|
|
||||||
|
val title: String
|
||||||
|
val mainMessage: String
|
||||||
|
val contacts: List<SecurityContact>
|
||||||
|
val isVersionError: Boolean
|
||||||
|
val minVersion: String
|
||||||
|
val currentVersion: String
|
||||||
|
|
||||||
|
when (securityState) {
|
||||||
|
is AppSecurityState.BlockedByMaintenance -> {
|
||||||
|
title = "App Fora de Operação"
|
||||||
|
mainMessage = securityState.message
|
||||||
|
contacts = securityState.contacts
|
||||||
|
isVersionError = false
|
||||||
|
minVersion = ""
|
||||||
|
currentVersion = ""
|
||||||
|
}
|
||||||
|
is AppSecurityState.BlockedByVersion -> {
|
||||||
|
title = "Versão Incompatível"
|
||||||
|
mainMessage = securityState.message
|
||||||
|
contacts = securityState.contacts
|
||||||
|
isVersionError = true
|
||||||
|
minVersion = securityState.minVersion
|
||||||
|
currentVersion = securityState.currentVersion
|
||||||
|
}
|
||||||
|
AppSecurityState.Allowed -> return
|
||||||
|
}
|
||||||
|
|
||||||
|
Dialog(
|
||||||
|
onDismissRequest = { /* Non-dismissible */ },
|
||||||
|
properties = DialogProperties(
|
||||||
|
usePlatformDefaultWidth = false,
|
||||||
|
dismissOnBackPress = false,
|
||||||
|
dismissOnClickOutside = false
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
Surface(
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
color = Color(0xFF1E1E24).copy(alpha = 0.96f)
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(24.dp),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Card(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.wrapContentHeight(),
|
||||||
|
shape = RoundedCornerShape(20.dp),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||||
|
elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(24.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally
|
||||||
|
) {
|
||||||
|
// Header Icon
|
||||||
|
Surface(
|
||||||
|
shape = RoundedCornerShape(16.dp),
|
||||||
|
color = if (isVersionError) Color(0xFFFFF3E0) else Color(0xFFFFEBEE),
|
||||||
|
modifier = Modifier.size(64.dp)
|
||||||
|
) {
|
||||||
|
Box(contentAlignment = Alignment.Center) {
|
||||||
|
Icon(
|
||||||
|
imageVector = if (isVersionError) Icons.Default.SystemUpdate else Icons.Default.Block,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = if (isVersionError) Color(0xFFE65100) else Color(0xFFC62828),
|
||||||
|
modifier = Modifier.size(36.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = title,
|
||||||
|
fontSize = 22.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = Color(0xFF1F2937),
|
||||||
|
textAlign = TextAlign.Center
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = mainMessage,
|
||||||
|
fontSize = 14.sp,
|
||||||
|
color = Color(0xFF4B5563),
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
lineHeight = 20.sp
|
||||||
|
)
|
||||||
|
|
||||||
|
if (isVersionError && minVersion.isNotBlank()) {
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
Surface(
|
||||||
|
shape = RoundedCornerShape(8.dp),
|
||||||
|
color = Color(0xFFF3F4F6),
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.padding(12.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Versão instalada: $currentVersion",
|
||||||
|
fontSize = 12.sp,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
color = Color(0xFF6B7280)
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "Versão mínima requerida: $minVersion",
|
||||||
|
fontSize = 13.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = Color(0xFFC62828)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(20.dp))
|
||||||
|
|
||||||
|
HorizontalDivider(color = Color(0xFFE5E7EB))
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = "Contatos para Suporte",
|
||||||
|
fontSize = 13.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = Color(0xFF374151),
|
||||||
|
modifier = Modifier.align(Alignment.Start)
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
|
||||||
|
contacts.forEach { contact ->
|
||||||
|
ContactRow(
|
||||||
|
contact = contact,
|
||||||
|
onSendEmail = { email ->
|
||||||
|
try {
|
||||||
|
val intent = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:$email"))
|
||||||
|
context.startActivity(intent)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Toast.makeText(context, "E-mail: $email", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onCopyEmail = { email ->
|
||||||
|
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||||
|
val clip = ClipData.newPlainText("E-mail Contato", email)
|
||||||
|
clipboard.setPrimaryClip(clip)
|
||||||
|
Toast.makeText(context, "E-mail copiado: $email", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = onRetryCheck,
|
||||||
|
enabled = !isRefreshing,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
colors = ButtonDefaults.buttonColors(
|
||||||
|
containerColor = Color(0xFF0284C7)
|
||||||
|
),
|
||||||
|
shape = RoundedCornerShape(10.dp)
|
||||||
|
) {
|
||||||
|
if (isRefreshing) {
|
||||||
|
CircularProgressIndicator(
|
||||||
|
modifier = Modifier.size(18.dp),
|
||||||
|
color = Color.White,
|
||||||
|
strokeWidth = 2.dp
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
|
Text(text = "Consultando Planilha...", fontSize = 14.sp, fontWeight = FontWeight.Medium)
|
||||||
|
} else {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.Refresh,
|
||||||
|
contentDescription = null,
|
||||||
|
modifier = Modifier.size(18.dp)
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
|
Text(text = "Verificar Novamente", fontSize = 14.sp, fontWeight = FontWeight.Medium)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ContactRow(
|
||||||
|
contact: SecurityContact,
|
||||||
|
onSendEmail: (String) -> Unit,
|
||||||
|
onCopyEmail: (String) -> Unit
|
||||||
|
) {
|
||||||
|
Surface(
|
||||||
|
shape = RoundedCornerShape(10.dp),
|
||||||
|
color = Color(0xFFF9FAFB),
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = contact.role,
|
||||||
|
fontSize = 11.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = Color(0xFF6B7280)
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = contact.email,
|
||||||
|
fontSize = 13.sp,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
color = Color(0xFF111827)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Row {
|
||||||
|
IconButton(
|
||||||
|
onClick = { onSendEmail(contact.email) },
|
||||||
|
modifier = Modifier.size(32.dp)
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.Email,
|
||||||
|
contentDescription = "Enviar E-mail",
|
||||||
|
tint = Color(0xFF0284C7),
|
||||||
|
modifier = Modifier.size(18.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
IconButton(
|
||||||
|
onClick = { onCopyEmail(contact.email) },
|
||||||
|
modifier = Modifier.size(32.dp)
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.ContentCopy,
|
||||||
|
contentDescription = "Copiar E-mail",
|
||||||
|
tint = Color(0xFF4B5563),
|
||||||
|
modifier = Modifier.size(18.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ import androidx.compose.foundation.background
|
|||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.layout.*
|
import androidx.compose.foundation.layout.*
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.LazyRow
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.foundation.pager.HorizontalPager
|
import androidx.compose.foundation.pager.HorizontalPager
|
||||||
import androidx.compose.foundation.pager.rememberPagerState
|
import androidx.compose.foundation.pager.rememberPagerState
|
||||||
@@ -22,6 +23,7 @@ import androidx.compose.material.icons.Icons
|
|||||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||||
import androidx.compose.material3.*
|
import androidx.compose.material3.*
|
||||||
import androidx.compose.runtime.*
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.geometry.Offset
|
import androidx.compose.ui.geometry.Offset
|
||||||
@@ -75,9 +77,21 @@ fun AnalyticsScreen(
|
|||||||
val currentUser by viewModel.currentUser.collectAsStateWithLifecycle()
|
val currentUser by viewModel.currentUser.collectAsStateWithLifecycle()
|
||||||
val userAccessLevel by viewModel.userAccessLevel.collectAsStateWithLifecycle()
|
val userAccessLevel by viewModel.userAccessLevel.collectAsStateWithLifecycle()
|
||||||
val allHistory by viewModel.allHistoryState.collectAsStateWithLifecycle()
|
val allHistory by viewModel.allHistoryState.collectAsStateWithLifecycle()
|
||||||
|
val simulationConfig by viewModel.simulationConfig.collectAsStateWithLifecycle()
|
||||||
|
val selectedActivity by viewModel.selectedActivity.collectAsStateWithLifecycle()
|
||||||
|
val selectedActivityHistory by viewModel.selectedActivityHistory.collectAsStateWithLifecycle()
|
||||||
|
val selectedActivityFindings by viewModel.selectedActivityFindings.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
val referenceDate = remember(simulationConfig) {
|
||||||
|
val simMillis = simulationConfig.simulatedDateMillis
|
||||||
|
if (simulationConfig.isActive && simMillis != null) {
|
||||||
|
Date(simMillis)
|
||||||
|
} else {
|
||||||
|
Date()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var selectedOverdueGroup by remember { mutableStateOf<SelectedOverdueGroup?>(null) }
|
var selectedOverdueGroup by remember { mutableStateOf<SelectedOverdueGroup?>(null) }
|
||||||
var selectedActivityToEdit by remember { mutableStateOf<MaintenanceActivity?>(null) }
|
|
||||||
|
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
|
|
||||||
@@ -176,6 +190,12 @@ fun AnalyticsScreen(
|
|||||||
.padding(16.dp),
|
.padding(16.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||||
) {
|
) {
|
||||||
|
// Banner de Alerta de Simulação de Data
|
||||||
|
SimulationAlertBanner(
|
||||||
|
simulationConfig = simulationConfig,
|
||||||
|
onDismiss = { viewModel.clearDateSimulation() }
|
||||||
|
)
|
||||||
|
|
||||||
if (activities.isEmpty()) {
|
if (activities.isEmpty()) {
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -194,8 +214,14 @@ fun AnalyticsScreen(
|
|||||||
// Card 1: Produtividade da Equipe
|
// Card 1: Produtividade da Equipe
|
||||||
TeamProductivityCard(analyticsState.teamMetrics)
|
TeamProductivityCard(analyticsState.teamMetrics)
|
||||||
|
|
||||||
|
val uniqueSectors by viewModel.uniqueSectors.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
// Card 2: Progresso do Projeto: Planejado vs. Realizado
|
// Card 2: Progresso do Projeto: Planejado vs. Realizado
|
||||||
SCurveCard(analyticsState)
|
SCurveCard(
|
||||||
|
analyticsState = analyticsState,
|
||||||
|
uniqueSectors = uniqueSectors,
|
||||||
|
onSetorSelected = { setor -> viewModel.setFilterSetorSCurve(setor) }
|
||||||
|
)
|
||||||
|
|
||||||
// Card 3: OSs Atrasadas (TAG / Setor alternáveis por swipe e clicáveis)
|
// Card 3: OSs Atrasadas (TAG / Setor alternáveis por swipe e clicáveis)
|
||||||
OverdueAnalyticsCard(
|
OverdueAnalyticsCard(
|
||||||
@@ -209,34 +235,35 @@ fun AnalyticsScreen(
|
|||||||
|
|
||||||
// Modal 1: Listagem das OSs Atrasadas por Grupo (TAG ou Setor)
|
// Modal 1: Listagem das OSs Atrasadas por Grupo (TAG ou Setor)
|
||||||
selectedOverdueGroup?.let { group ->
|
selectedOverdueGroup?.let { group ->
|
||||||
val topSectors = analyticsState.overdueBySector.take(3).map { it.first }
|
val topSectors = analyticsState.overdueBySector.map { it.first }
|
||||||
|
val topTags = analyticsState.overdueByTag.take(9).map { it.first }
|
||||||
OverdueActivitiesListModal(
|
OverdueActivitiesListModal(
|
||||||
group = group,
|
group = group,
|
||||||
allActivities = activities,
|
allActivities = activities,
|
||||||
projectEnd = analyticsState.projectEnd,
|
projectEnd = analyticsState.projectEnd,
|
||||||
topSectors = topSectors,
|
topSectors = topSectors,
|
||||||
|
topTags = topTags,
|
||||||
|
referenceDate = referenceDate,
|
||||||
onDismiss = { selectedOverdueGroup = null },
|
onDismiss = { selectedOverdueGroup = null },
|
||||||
onActivityClick = { activity ->
|
onActivityClick = { activity ->
|
||||||
selectedOverdueGroup = null
|
selectedOverdueGroup = null
|
||||||
selectedActivityToEdit = activity
|
viewModel.selectActivity(activity)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Modal 2: Edição da OS Selecionada
|
// Modal 2: Edição da OS Selecionada
|
||||||
selectedActivityToEdit?.let { activity ->
|
if (selectedActivity != null) {
|
||||||
val history = remember(allHistory, activity) {
|
|
||||||
allHistory.filter { it.numeroOs == activity.numeroOs }
|
|
||||||
}
|
|
||||||
EditActivityBottomSheet(
|
EditActivityBottomSheet(
|
||||||
activity = activity,
|
activity = selectedActivity!!,
|
||||||
history = history,
|
history = selectedActivityHistory,
|
||||||
|
findings = selectedActivityFindings,
|
||||||
currentUser = currentUser,
|
currentUser = currentUser,
|
||||||
userAccessLevel = userAccessLevel,
|
userAccessLevel = userAccessLevel,
|
||||||
onDismiss = { selectedActivityToEdit = null },
|
onDismiss = { viewModel.selectActivity(null) },
|
||||||
onUpdateProgress = { newPercentual, observation, photoPath ->
|
onUpdateProgress = { newPercentual, observation, photoPath ->
|
||||||
viewModel.updateProgress(
|
viewModel.updateProgress(
|
||||||
numeroOs = activity.numeroOs,
|
numeroOs = selectedActivity!!.numeroOs,
|
||||||
novoPercentual = newPercentual,
|
novoPercentual = newPercentual,
|
||||||
observacao = observation,
|
observacao = observation,
|
||||||
fotoPath = photoPath,
|
fotoPath = photoPath,
|
||||||
@@ -244,14 +271,23 @@ fun AnalyticsScreen(
|
|||||||
emailEditor = currentUser?.email
|
emailEditor = currentUser?.email
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
onAddFinding = { tipo, desc ->
|
||||||
|
viewModel.addFinding(selectedActivity!!.numeroOs, tipo, desc)
|
||||||
|
},
|
||||||
|
onUpdateFinding = { finding ->
|
||||||
|
viewModel.updateFinding(finding)
|
||||||
|
},
|
||||||
|
onDeleteFinding = { finding ->
|
||||||
|
viewModel.deleteFinding(finding)
|
||||||
|
},
|
||||||
onSavePhotoFromUri = { uri ->
|
onSavePhotoFromUri = { uri ->
|
||||||
viewModel.saveLocalPhotoFromUri(uri, activity.numeroOs)
|
viewModel.saveLocalPhotoFromUri(uri, selectedActivity!!.numeroOs)
|
||||||
},
|
},
|
||||||
onCreateCameraUri = {
|
onCreateCameraUri = {
|
||||||
viewModel.createTempCameraPhotoUri(activity.numeroOs)
|
viewModel.createTempCameraPhotoUri(selectedActivity!!.numeroOs)
|
||||||
},
|
},
|
||||||
onSoftDeletePhoto = { path ->
|
onSoftDeletePhoto = { path ->
|
||||||
viewModel.softDeletePhoto(path, activity.numeroOs)
|
viewModel.softDeletePhoto(path, selectedActivity!!.numeroOs)
|
||||||
},
|
},
|
||||||
onGoogleLoginClick = {
|
onGoogleLoginClick = {
|
||||||
googleSignInLauncher.launch(googleSignInClient.signInIntent)
|
googleSignInLauncher.launch(googleSignInClient.signInIntent)
|
||||||
@@ -341,7 +377,11 @@ fun TeamProductivityCard(teamMetrics: List<Pair<String, Int>>) {
|
|||||||
* Compara o avanço temporal Planejado com o Realizado
|
* Compara o avanço temporal Planejado com o Realizado
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun SCurveCard(analyticsState: AnalyticsState) {
|
fun SCurveCard(
|
||||||
|
analyticsState: AnalyticsState,
|
||||||
|
uniqueSectors: List<String>,
|
||||||
|
onSetorSelected: (String) -> Unit
|
||||||
|
) {
|
||||||
Card(
|
Card(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
colors = CardDefaults.cardColors(containerColor = Color.White),
|
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||||
@@ -361,9 +401,38 @@ fun SCurveCard(analyticsState: AnalyticsState) {
|
|||||||
textAlign = TextAlign.Center,
|
textAlign = TextAlign.Center,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.padding(bottom = 12.dp)
|
.padding(bottom = 8.dp)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Sector filter row (matches Ordens screen filter chip style)
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(bottom = 12.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Setor:",
|
||||||
|
fontSize = 11.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = Color.Gray,
|
||||||
|
modifier = Modifier.padding(end = 8.dp)
|
||||||
|
)
|
||||||
|
LazyRow(
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
items(uniqueSectors) { setor ->
|
||||||
|
val isSelected = setor == analyticsState.selectedSetorSCurve
|
||||||
|
FilterChipWidget(
|
||||||
|
text = setor,
|
||||||
|
isSelected = isSelected,
|
||||||
|
onClick = { onSetorSelected(setor) }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val timelineDates = analyticsState.timelineDates
|
val timelineDates = analyticsState.timelineDates
|
||||||
val plannedProgressPoints = analyticsState.plannedProgressPoints
|
val plannedProgressPoints = analyticsState.plannedProgressPoints
|
||||||
val realizedProgressPoints = analyticsState.realizedProgressPoints
|
val realizedProgressPoints = analyticsState.realizedProgressPoints
|
||||||
@@ -582,7 +651,7 @@ fun OverdueAnalyticsCard(
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun OverdueBarChartContent(
|
private fun OverdueBarChartContent(
|
||||||
displayList: List<Pair<String, Int>>,
|
displayList: List<Pair<String, Double>>,
|
||||||
emptyMessage: String,
|
emptyMessage: String,
|
||||||
onItemClick: (String) -> Unit = {}
|
onItemClick: (String) -> Unit = {}
|
||||||
) {
|
) {
|
||||||
@@ -602,7 +671,7 @@ private fun OverdueBarChartContent(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
val maxCount = displayList.maxOfOrNull { it.second } ?: 1
|
val maxCount = displayList.maxOfOrNull { it.second } ?: 1.0
|
||||||
|
|
||||||
Column(
|
Column(
|
||||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
@@ -617,6 +686,11 @@ private fun OverdueBarChartContent(
|
|||||||
else -> Color(0xFF9C27B0) // Purple
|
else -> Color(0xFF9C27B0) // Purple
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val fillRatio = if (maxCount > 0) (count / maxCount).toFloat().coerceIn(0f, 1f) else 0f
|
||||||
|
val formattedHours = if (count <= 0.0) "0h"
|
||||||
|
else if (count % 1.0 == 0.0) "${count.toInt()}h"
|
||||||
|
else String.format(java.util.Locale.US, "%.1fh", count)
|
||||||
|
|
||||||
Row(
|
Row(
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -643,7 +717,7 @@ private fun OverdueBarChartContent(
|
|||||||
) {
|
) {
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth(count.toFloat() / maxCount.toFloat())
|
.fillMaxWidth(fillRatio)
|
||||||
.fillMaxHeight()
|
.fillMaxHeight()
|
||||||
.background(barColor, shape = RoundedCornerShape(4.dp))
|
.background(barColor, shape = RoundedCornerShape(4.dp))
|
||||||
)
|
)
|
||||||
@@ -651,13 +725,13 @@ private fun OverdueBarChartContent(
|
|||||||
|
|
||||||
Spacer(modifier = Modifier.width(8.dp))
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
|
|
||||||
// Count number
|
// Count number formatted in hours
|
||||||
Text(
|
Text(
|
||||||
text = count.toString(),
|
text = formattedHours,
|
||||||
fontSize = 12.sp,
|
fontSize = 12.sp,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
color = BrandBlack,
|
color = BrandBlack,
|
||||||
modifier = Modifier.width(20.dp),
|
modifier = Modifier.width(42.dp),
|
||||||
textAlign = TextAlign.End
|
textAlign = TextAlign.End
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -675,13 +749,13 @@ fun OverdueActivitiesListModal(
|
|||||||
group: SelectedOverdueGroup,
|
group: SelectedOverdueGroup,
|
||||||
allActivities: List<MaintenanceActivity>,
|
allActivities: List<MaintenanceActivity>,
|
||||||
projectEnd: Date,
|
projectEnd: Date,
|
||||||
topSectors: List<String>,
|
topSectors: List<String> = emptyList(),
|
||||||
|
topTags: List<String> = emptyList(),
|
||||||
|
referenceDate: Date = Date(),
|
||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
onActivityClick: (MaintenanceActivity) -> Unit
|
onActivityClick: (MaintenanceActivity) -> Unit
|
||||||
) {
|
) {
|
||||||
val referenceDate = remember { Date() }
|
val filteredActivities = remember(group, allActivities, referenceDate, topSectors, topTags) {
|
||||||
|
|
||||||
val filteredActivities = remember(group, allActivities, referenceDate, topSectors) {
|
|
||||||
allActivities.filter { act ->
|
allActivities.filter { act ->
|
||||||
val isNotCompleted = act.percentualExecucao < 100
|
val isNotCompleted = act.percentualExecucao < 100
|
||||||
val endDate = parseFullDateTime(act.dataFim) ?: parseDateOnly(act.dataFim)
|
val endDate = parseFullDateTime(act.dataFim) ?: parseDateOnly(act.dataFim)
|
||||||
@@ -691,7 +765,14 @@ fun OverdueActivitiesListModal(
|
|||||||
|
|
||||||
when (group.type) {
|
when (group.type) {
|
||||||
OverdueGroupType.TAG -> {
|
OverdueGroupType.TAG -> {
|
||||||
if (group.label == "Sem TAG") act.tag.isBlank() else act.tag == group.label
|
val actTag = if (act.tag.isBlank()) "Sem TAG" else act.tag
|
||||||
|
if (group.label == "Outros") {
|
||||||
|
!topTags.contains(actTag)
|
||||||
|
} else if (group.label == "Sem TAG") {
|
||||||
|
act.tag.isBlank()
|
||||||
|
} else {
|
||||||
|
act.tag == group.label
|
||||||
|
}
|
||||||
}
|
}
|
||||||
OverdueGroupType.SETOR -> {
|
OverdueGroupType.SETOR -> {
|
||||||
val actSetor = if (act.setor.isBlank()) "Sem Setor" else act.setor
|
val actSetor = if (act.setor.isBlank()) "Sem Setor" else act.setor
|
||||||
@@ -704,7 +785,10 @@ fun OverdueActivitiesListModal(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}.sortedWith(
|
||||||
|
compareByDescending<MaintenanceActivity> { it.duracaoHorasCalculada }
|
||||||
|
.thenBy { it.dataFimMillis }
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
AlertDialog(
|
AlertDialog(
|
||||||
@@ -805,7 +889,7 @@ fun OverdueActivitiesListModal(
|
|||||||
|
|
||||||
Spacer(modifier = Modifier.height(4.dp))
|
Spacer(modifier = Modifier.height(4.dp))
|
||||||
Text(
|
Text(
|
||||||
text = activity.descricao,
|
text = activity.formattedDescricao,
|
||||||
fontSize = 12.sp,
|
fontSize = 12.sp,
|
||||||
fontWeight = FontWeight.Medium,
|
fontWeight = FontWeight.Medium,
|
||||||
color = Color.DarkGray,
|
color = Color.DarkGray,
|
||||||
|
|||||||
431
app/src/main/java/com/example/ui/screens/ImportantInfoScreen.kt
Normal file
431
app/src/main/java/com/example/ui/screens/ImportantInfoScreen.kt
Normal file
@@ -0,0 +1,431 @@
|
|||||||
|
package com.example.ui.screens
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.ArrowForward
|
||||||
|
import androidx.compose.material.icons.filled.Code
|
||||||
|
import androidx.compose.material.icons.filled.Description
|
||||||
|
import androidx.compose.material.icons.filled.Email
|
||||||
|
import androidx.compose.material.icons.filled.Info
|
||||||
|
import androidx.compose.material.icons.filled.Link
|
||||||
|
import androidx.compose.material.icons.filled.Lock
|
||||||
|
import androidx.compose.material.icons.filled.OpenInNew
|
||||||
|
import androidx.compose.material.icons.filled.Person
|
||||||
|
import androidx.compose.material.icons.filled.Refresh
|
||||||
|
import androidx.compose.material.icons.filled.Security
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import com.example.data.model.ImportantLink
|
||||||
|
import com.example.ui.theme.BrandBlack
|
||||||
|
import com.example.ui.theme.BrandGreen
|
||||||
|
import com.example.ui.theme.BrandLightGreen
|
||||||
|
import com.example.ui.theme.LightGrey
|
||||||
|
import com.example.ui.viewmodel.MaintenanceViewModel
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun ImportantInfoScreen(
|
||||||
|
viewModel: MaintenanceViewModel,
|
||||||
|
modifier: Modifier = Modifier
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val links by viewModel.importantLinks.collectAsStateWithLifecycle()
|
||||||
|
val isNetworkConnected by viewModel.isNetworkConnected.collectAsStateWithLifecycle(initialValue = true)
|
||||||
|
val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
val openUrl: (String) -> Unit = { urlString ->
|
||||||
|
try {
|
||||||
|
val formattedUrl = if (!urlString.startsWith("http://") && !urlString.startsWith("https://")) {
|
||||||
|
"https://$urlString"
|
||||||
|
} else urlString
|
||||||
|
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(formattedUrl))
|
||||||
|
context.startActivity(intent)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Toast.makeText(context, "Não foi possível abrir o link: ${e.message}", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Scaffold(
|
||||||
|
topBar = {
|
||||||
|
TopAppBar(
|
||||||
|
title = {
|
||||||
|
Column {
|
||||||
|
Text(
|
||||||
|
text = "Informações Importantes",
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
fontSize = 20.sp,
|
||||||
|
color = BrandBlack
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "Links da aba config da planilha online",
|
||||||
|
fontSize = 12.sp,
|
||||||
|
color = Color.Gray
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
actions = {
|
||||||
|
IconButton(
|
||||||
|
onClick = {
|
||||||
|
if (!isSyncing) {
|
||||||
|
viewModel.syncNow()
|
||||||
|
Toast.makeText(context, "Atualizando informações da planilha...", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
if (isSyncing) {
|
||||||
|
CircularProgressIndicator(
|
||||||
|
modifier = Modifier.size(20.dp),
|
||||||
|
color = BrandGreen,
|
||||||
|
strokeWidth = 2.dp
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.Refresh,
|
||||||
|
contentDescription = "Atualizar Links",
|
||||||
|
tint = BrandGreen
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.White)
|
||||||
|
)
|
||||||
|
},
|
||||||
|
modifier = modifier
|
||||||
|
) { innerPadding ->
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(innerPadding)
|
||||||
|
.background(LightGrey)
|
||||||
|
.padding(horizontal = 16.dp, vertical = 12.dp)
|
||||||
|
) {
|
||||||
|
// Status Card
|
||||||
|
Card(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(bottom = 16.dp),
|
||||||
|
shape = RoundedCornerShape(12.dp),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||||
|
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(16.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(40.dp)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(BrandLightGreen),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.Info,
|
||||||
|
contentDescription = "Informações",
|
||||||
|
tint = BrandGreen
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.width(12.dp))
|
||||||
|
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = "Central de Links do Sistema",
|
||||||
|
fontSize = 15.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = BrandBlack
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.height(2.dp))
|
||||||
|
Text(
|
||||||
|
text = if (isNetworkConnected) "Sincronizado com o BD online" else "Modo Offline (Links armazenados localmente)",
|
||||||
|
fontSize = 12.sp,
|
||||||
|
color = if (isNetworkConnected) BrandGreen else Color(0xFFD97706)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Links List Title
|
||||||
|
Text(
|
||||||
|
text = "LINKS ÚTEIS E DOCUMENTOS",
|
||||||
|
fontSize = 12.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = Color.Gray,
|
||||||
|
modifier = Modifier.padding(start = 4.dp, bottom = 8.dp)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Links List + Responsáveis
|
||||||
|
LazyColumn(
|
||||||
|
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
items(links, key = { it.id }) { linkItem ->
|
||||||
|
ImportantLinkCard(
|
||||||
|
link = linkItem,
|
||||||
|
onOpenUrl = { openUrl(linkItem.url) }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
item {
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
Text(
|
||||||
|
text = "RESPONSÁVEIS PELO APLICATIVO",
|
||||||
|
fontSize = 12.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = Color.Gray,
|
||||||
|
modifier = Modifier.padding(start = 4.dp, bottom = 8.dp)
|
||||||
|
)
|
||||||
|
|
||||||
|
AppMaintainersCard(
|
||||||
|
onSendEmail = { email ->
|
||||||
|
try {
|
||||||
|
val intent = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:$email"))
|
||||||
|
context.startActivity(intent)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Toast.makeText(context, "E-mail: $email", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
item {
|
||||||
|
Spacer(modifier = Modifier.height(12.dp))
|
||||||
|
Box(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Versão do aplicativo: ${com.example.util.DeviceUtils.getAppVersion(context)}",
|
||||||
|
fontSize = 12.sp,
|
||||||
|
color = Color.Gray,
|
||||||
|
fontWeight = FontWeight.Medium
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun ImportantLinkCard(
|
||||||
|
link: ImportantLink,
|
||||||
|
onOpenUrl: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier
|
||||||
|
) {
|
||||||
|
val (icon, badgeColor) = when (link.id) {
|
||||||
|
"1" -> Icons.Default.Security to Color(0xFF0284C7)
|
||||||
|
"2" -> Icons.Default.Lock to Color(0xFF7C3AED)
|
||||||
|
"3" -> Icons.Default.Description to Color(0xFF059669)
|
||||||
|
"4" -> Icons.Default.Link to Color(0xFFEA580C)
|
||||||
|
else -> Icons.Default.OpenInNew to BrandGreen
|
||||||
|
}
|
||||||
|
|
||||||
|
Card(
|
||||||
|
modifier = modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable { onOpenUrl() },
|
||||||
|
shape = RoundedCornerShape(14.dp),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||||
|
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(16.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(48.dp)
|
||||||
|
.clip(RoundedCornerShape(12.dp))
|
||||||
|
.background(badgeColor.copy(alpha = 0.1f)),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = icon,
|
||||||
|
contentDescription = link.title,
|
||||||
|
tint = badgeColor,
|
||||||
|
modifier = Modifier.size(24.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.width(14.dp))
|
||||||
|
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = link.title,
|
||||||
|
fontSize = 15.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = BrandBlack,
|
||||||
|
maxLines = 2,
|
||||||
|
overflow = TextOverflow.Ellipsis
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!link.description.isNullOrBlank()) {
|
||||||
|
Spacer(modifier = Modifier.height(4.dp))
|
||||||
|
Text(
|
||||||
|
text = link.description,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
color = Color.Gray,
|
||||||
|
maxLines = 2,
|
||||||
|
overflow = TextOverflow.Ellipsis
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(6.dp))
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = link.url,
|
||||||
|
fontSize = 11.sp,
|
||||||
|
color = badgeColor,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
|
|
||||||
|
IconButton(
|
||||||
|
onClick = onOpenUrl,
|
||||||
|
modifier = Modifier
|
||||||
|
.size(36.dp)
|
||||||
|
.clip(CircleShape)
|
||||||
|
.background(LightGrey)
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.OpenInNew,
|
||||||
|
contentDescription = "Abrir Link",
|
||||||
|
tint = BrandBlack,
|
||||||
|
modifier = Modifier.size(18.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun AppMaintainersCard(
|
||||||
|
onSendEmail: (String) -> Unit,
|
||||||
|
modifier: Modifier = Modifier
|
||||||
|
) {
|
||||||
|
Card(
|
||||||
|
modifier = modifier.fillMaxWidth(),
|
||||||
|
shape = RoundedCornerShape(14.dp),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||||
|
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(16.dp)
|
||||||
|
) {
|
||||||
|
MaintainerRow(
|
||||||
|
role = "Desenvolvedor",
|
||||||
|
email = "cesarjhony+dev@gmail.com",
|
||||||
|
icon = Icons.Default.Code,
|
||||||
|
badgeColor = Color(0xFF0284C7),
|
||||||
|
onSendEmail = onSendEmail
|
||||||
|
)
|
||||||
|
|
||||||
|
HorizontalDivider(
|
||||||
|
modifier = Modifier.padding(vertical = 12.dp),
|
||||||
|
color = LightGrey
|
||||||
|
)
|
||||||
|
|
||||||
|
MaintainerRow(
|
||||||
|
role = "Responsável",
|
||||||
|
email = "gabrielpizzinatto123@gmail.com",
|
||||||
|
icon = Icons.Default.Person,
|
||||||
|
badgeColor = BrandGreen,
|
||||||
|
onSendEmail = onSendEmail
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun MaintainerRow(
|
||||||
|
role: String,
|
||||||
|
email: String,
|
||||||
|
icon: ImageVector,
|
||||||
|
badgeColor: Color,
|
||||||
|
onSendEmail: (String) -> Unit
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable { onSendEmail(email) },
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(40.dp)
|
||||||
|
.clip(RoundedCornerShape(10.dp))
|
||||||
|
.background(badgeColor.copy(alpha = 0.1f)),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = icon,
|
||||||
|
contentDescription = role,
|
||||||
|
tint = badgeColor,
|
||||||
|
modifier = Modifier.size(20.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.width(12.dp))
|
||||||
|
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = role,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
color = Color.Gray
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.height(2.dp))
|
||||||
|
Text(
|
||||||
|
text = email,
|
||||||
|
fontSize = 14.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = BrandBlack,
|
||||||
|
maxLines = 1,
|
||||||
|
overflow = TextOverflow.Ellipsis
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.Email,
|
||||||
|
contentDescription = "Enviar E-mail",
|
||||||
|
tint = badgeColor,
|
||||||
|
modifier = Modifier.size(20.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -65,6 +65,15 @@ fun SettingsScreen(
|
|||||||
val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle()
|
val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle()
|
||||||
val conflictLogs by viewModel.conflictLogs.collectAsStateWithLifecycle()
|
val conflictLogs by viewModel.conflictLogs.collectAsStateWithLifecycle()
|
||||||
val appLogs by viewModel.appLogsState.collectAsStateWithLifecycle()
|
val appLogs by viewModel.appLogsState.collectAsStateWithLifecycle()
|
||||||
|
val userAccessLevel by viewModel.userAccessLevel.collectAsStateWithLifecycle()
|
||||||
|
val simulationConfig by viewModel.simulationConfig.collectAsStateWithLifecycle()
|
||||||
|
val isNetworkConnected by viewModel.isNetworkConnected.collectAsStateWithLifecycle(initialValue = true)
|
||||||
|
val autoSyncIntervalMinutes by viewModel.autoSyncIntervalMinutes.collectAsStateWithLifecycle()
|
||||||
|
val lastSyncTimestamp by viewModel.lastSyncTimestamp.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
val hasTotalAccess = remember(userAccessLevel) {
|
||||||
|
userAccessLevel?.trim()?.equals("total", ignoreCase = true) == true
|
||||||
|
}
|
||||||
|
|
||||||
var showClearCacheDialog by remember { mutableStateOf(false) }
|
var showClearCacheDialog by remember { mutableStateOf(false) }
|
||||||
var showConflictsDialog by remember { mutableStateOf(false) }
|
var showConflictsDialog by remember { mutableStateOf(false) }
|
||||||
@@ -146,178 +155,15 @@ fun SettingsScreen(
|
|||||||
verticalArrangement = Arrangement.spacedBy(20.dp)
|
verticalArrangement = Arrangement.spacedBy(20.dp)
|
||||||
) {
|
) {
|
||||||
|
|
||||||
// Seção 2: Status da API Google Cloud
|
// Seção: Status da Sincronização Automática
|
||||||
Column {
|
AutoSyncStatusCard(
|
||||||
Text(
|
autoSyncIntervalMinutes = autoSyncIntervalMinutes,
|
||||||
text = "Status da API Google Cloud",
|
isNetworkConnected = isNetworkConnected,
|
||||||
fontSize = 20.sp,
|
isSyncing = isSyncing,
|
||||||
fontWeight = FontWeight.Black,
|
lastSyncTimestamp = lastSyncTimestamp
|
||||||
color = Color(0xFF0F2644),
|
)
|
||||||
modifier = Modifier.padding(bottom = 8.dp)
|
|
||||||
)
|
|
||||||
|
|
||||||
Card(
|
// Seção: Painel do Administrador
|
||||||
colors = CardDefaults.cardColors(containerColor = Color.White),
|
|
||||||
shape = RoundedCornerShape(12.dp),
|
|
||||||
elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
|
|
||||||
) {
|
|
||||||
Column(
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(16.dp)
|
|
||||||
) {
|
|
||||||
if (!connectionTested) {
|
|
||||||
// Erro ou Awaiting Connection State
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
|
||||||
) {
|
|
||||||
Icon(
|
|
||||||
imageVector = Icons.Default.Warning,
|
|
||||||
contentDescription = "Alerta",
|
|
||||||
tint = Color(0xFFD32F2F),
|
|
||||||
modifier = Modifier.size(24.dp)
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
text = "Configure e teste a conexão para carregar as métricas da API Google Cloud em tempo real.",
|
|
||||||
color = Color(0xFFD32F2F),
|
|
||||||
fontSize = 14.sp,
|
|
||||||
fontWeight = FontWeight.Medium
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Row(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
horizontalArrangement = Arrangement.SpaceBetween
|
|
||||||
) {
|
|
||||||
// Coluna Latência
|
|
||||||
Column(modifier = Modifier.weight(1f)) {
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(6.dp)
|
|
||||||
) {
|
|
||||||
Text(
|
|
||||||
text = "Latência",
|
|
||||||
fontSize = 13.sp,
|
|
||||||
color = Color.Gray,
|
|
||||||
fontWeight = FontWeight.Medium
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
text = apiLatency ?: "0ms",
|
|
||||||
fontSize = 12.sp,
|
|
||||||
color = Color.Gray,
|
|
||||||
fontWeight = FontWeight.Bold
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(6.dp))
|
|
||||||
|
|
||||||
LinearProgressIndicator(
|
|
||||||
progress = { 0.8f },
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.height(8.dp),
|
|
||||||
color = BrandGreen,
|
|
||||||
trackColor = Color(0xFFE0E0E0),
|
|
||||||
strokeCap = androidx.compose.ui.graphics.StrokeCap.Round
|
|
||||||
)
|
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(6.dp))
|
|
||||||
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(4.dp)
|
|
||||||
) {
|
|
||||||
Text(
|
|
||||||
text = apiLatency ?: "0ms",
|
|
||||||
fontSize = 16.sp,
|
|
||||||
fontWeight = FontWeight.Black,
|
|
||||||
color = BrandBlack
|
|
||||||
)
|
|
||||||
Icon(
|
|
||||||
imageVector = Icons.Default.DateRange,
|
|
||||||
contentDescription = "Online",
|
|
||||||
tint = BrandGreen,
|
|
||||||
modifier = Modifier.size(14.dp)
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
text = "Online",
|
|
||||||
fontSize = 14.sp,
|
|
||||||
fontWeight = FontWeight.Bold,
|
|
||||||
color = BrandGreen
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Spacer(modifier = Modifier.width(24.dp))
|
|
||||||
|
|
||||||
// Coluna Cota
|
|
||||||
Column(modifier = Modifier.weight(1f)) {
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(6.dp)
|
|
||||||
) {
|
|
||||||
Text(
|
|
||||||
text = "Cota de Uso",
|
|
||||||
fontSize = 13.sp,
|
|
||||||
color = Color.Gray,
|
|
||||||
fontWeight = FontWeight.Medium
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
text = apiQuota ?: "0%",
|
|
||||||
fontSize = 12.sp,
|
|
||||||
color = Color.Gray,
|
|
||||||
fontWeight = FontWeight.Bold
|
|
||||||
)
|
|
||||||
Icon(
|
|
||||||
imageVector = Icons.Default.Info,
|
|
||||||
contentDescription = "Cota",
|
|
||||||
tint = BrandGreen,
|
|
||||||
modifier = Modifier.size(14.dp)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(6.dp))
|
|
||||||
|
|
||||||
val quotaFloat = (apiQuota?.replace("%", "")?.toFloatOrNull() ?: 0f) / 100f
|
|
||||||
LinearProgressIndicator(
|
|
||||||
progress = { quotaFloat.coerceIn(0f, 1f) },
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.height(8.dp),
|
|
||||||
color = BrandGreen,
|
|
||||||
trackColor = Color(0xFFE0E0E0),
|
|
||||||
strokeCap = androidx.compose.ui.graphics.StrokeCap.Round
|
|
||||||
)
|
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(6.dp))
|
|
||||||
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(4.dp)
|
|
||||||
) {
|
|
||||||
Text(
|
|
||||||
text = apiQuota ?: "0%",
|
|
||||||
fontSize = 16.sp,
|
|
||||||
fontWeight = FontWeight.Black,
|
|
||||||
color = BrandBlack
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
text = "Bom",
|
|
||||||
fontSize = 14.sp,
|
|
||||||
fontWeight = FontWeight.Bold,
|
|
||||||
color = BrandGreen
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Seção 3: Painel do Administrador
|
|
||||||
Column {
|
Column {
|
||||||
Text(
|
Text(
|
||||||
text = "Painel do Administrador",
|
text = "Painel do Administrador",
|
||||||
@@ -378,6 +224,33 @@ fun SettingsScreen(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Seção: Simulação de Data (Posicionada no final da tela)
|
||||||
|
DateSimulationSection(
|
||||||
|
hasTotalAccess = hasTotalAccess,
|
||||||
|
simulationConfig = simulationConfig,
|
||||||
|
onActivateSimulation = { dateMillis, mode ->
|
||||||
|
viewModel.setDateSimulation(dateMillis, mode)
|
||||||
|
},
|
||||||
|
onClearSimulation = {
|
||||||
|
viewModel.clearDateSimulation()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Rodapé com exibição da versão do aplicativo
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(vertical = 12.dp),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Versão do aplicativo: ${com.example.util.DeviceUtils.getAppVersion(context)}",
|
||||||
|
fontSize = 12.sp,
|
||||||
|
color = Color.Gray,
|
||||||
|
fontWeight = FontWeight.Medium
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -438,6 +311,242 @@ fun SettingsScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun DateSimulationSection(
|
||||||
|
hasTotalAccess: Boolean,
|
||||||
|
simulationConfig: com.example.data.model.DateSimulationConfig,
|
||||||
|
onActivateSimulation: (dateMillis: Long, mode: com.example.data.model.DateSimulationMode) -> Unit,
|
||||||
|
onClearSimulation: () -> Unit
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
var showDatePicker by remember { mutableStateOf(false) }
|
||||||
|
var selectedDateMillis by remember(simulationConfig.simulatedDateMillis) {
|
||||||
|
mutableLongStateOf(simulationConfig.simulatedDateMillis ?: System.currentTimeMillis())
|
||||||
|
}
|
||||||
|
var selectedMode by remember(simulationConfig.mode) {
|
||||||
|
mutableStateOf(
|
||||||
|
if (simulationConfig.mode == com.example.data.model.DateSimulationMode.DISABLED)
|
||||||
|
com.example.data.model.DateSimulationMode.VISUALIZATION_ONLY
|
||||||
|
else simulationConfig.mode
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val dateFormatter = remember { SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()) }
|
||||||
|
val formattedDate = remember(selectedDateMillis) { dateFormatter.format(Date(selectedDateMillis)) }
|
||||||
|
|
||||||
|
Column {
|
||||||
|
Text(
|
||||||
|
text = "Simulação de Data do Sistema",
|
||||||
|
fontSize = 20.sp,
|
||||||
|
fontWeight = FontWeight.Black,
|
||||||
|
color = Color(0xFF0F2644),
|
||||||
|
modifier = Modifier.padding(bottom = 8.dp)
|
||||||
|
)
|
||||||
|
|
||||||
|
Card(
|
||||||
|
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||||
|
shape = RoundedCornerShape(12.dp),
|
||||||
|
elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||||
|
) {
|
||||||
|
if (!hasTotalAccess) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
|
modifier = Modifier.padding(vertical = 8.dp)
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.Lock,
|
||||||
|
contentDescription = "Acesso Bloqueado",
|
||||||
|
tint = Color.Gray,
|
||||||
|
modifier = Modifier.size(28.dp)
|
||||||
|
)
|
||||||
|
Column {
|
||||||
|
Text(
|
||||||
|
text = "Simulação de Data Restrita",
|
||||||
|
fontSize = 16.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = Color.Gray
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "Este recurso requer permissão de Nível Total no aplicativo.",
|
||||||
|
fontSize = 13.sp,
|
||||||
|
color = Color.Gray
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.DateRange,
|
||||||
|
contentDescription = "Simulação de Data",
|
||||||
|
tint = BrandGreen,
|
||||||
|
modifier = Modifier.size(24.dp)
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = if (simulationConfig.isActive) "Simulação Ativa" else "Configurar Simulação",
|
||||||
|
fontSize = 16.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = BrandBlack
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
HorizontalDivider(color = Color(0xFFE5E5E5))
|
||||||
|
|
||||||
|
// Seleção de Data
|
||||||
|
Text(
|
||||||
|
text = "Data para Simulação:",
|
||||||
|
fontSize = 14.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = BrandBlack
|
||||||
|
)
|
||||||
|
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = { showDatePicker = true },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
shape = RoundedCornerShape(8.dp),
|
||||||
|
border = BorderStroke(1.dp, BrandGreen)
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.CalendarToday,
|
||||||
|
contentDescription = "Calendário",
|
||||||
|
tint = BrandGreen,
|
||||||
|
modifier = Modifier.size(18.dp)
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
|
Text(
|
||||||
|
text = "Data Selecionada: $formattedDate",
|
||||||
|
color = BrandBlack,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Seleção de Modo
|
||||||
|
Text(
|
||||||
|
text = "Modo de Simulação:",
|
||||||
|
fontSize = 14.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = BrandBlack
|
||||||
|
)
|
||||||
|
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable { selectedMode = com.example.data.model.DateSimulationMode.VISUALIZATION_ONLY }
|
||||||
|
) {
|
||||||
|
RadioButton(
|
||||||
|
selected = selectedMode == com.example.data.model.DateSimulationMode.VISUALIZATION_ONLY,
|
||||||
|
onClick = { selectedMode = com.example.data.model.DateSimulationMode.VISUALIZATION_ONLY },
|
||||||
|
colors = RadioButtonDefaults.colors(selectedColor = BrandGreen)
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "Somente Simulação para Visualização",
|
||||||
|
fontSize = 14.sp,
|
||||||
|
color = BrandBlack
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable { selectedMode = com.example.data.model.DateSimulationMode.EDIT_PROGRESS }
|
||||||
|
) {
|
||||||
|
RadioButton(
|
||||||
|
selected = selectedMode == com.example.data.model.DateSimulationMode.EDIT_PROGRESS,
|
||||||
|
onClick = { selectedMode = com.example.data.model.DateSimulationMode.EDIT_PROGRESS },
|
||||||
|
colors = RadioButtonDefaults.colors(selectedColor = BrandGreen)
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "Simulação para Edição do Progresso das Ordens",
|
||||||
|
fontSize = 14.sp,
|
||||||
|
color = BrandBlack
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = "Nota: A simulação se encerra automaticamente após 15 minutos de uso contínuo.",
|
||||||
|
fontSize = 11.sp,
|
||||||
|
color = Color.Gray
|
||||||
|
)
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||||
|
) {
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
onActivateSimulation(selectedDateMillis, selectedMode)
|
||||||
|
Toast.makeText(context, "Simulação de data ativada!", Toast.LENGTH_SHORT).show()
|
||||||
|
},
|
||||||
|
colors = ButtonDefaults.buttonColors(containerColor = BrandGreen),
|
||||||
|
shape = RoundedCornerShape(8.dp),
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Text("Ativar Simulação", fontWeight = FontWeight.Bold, color = Color.White)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (simulationConfig.isActive) {
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = {
|
||||||
|
onClearSimulation()
|
||||||
|
Toast.makeText(context, "Simulação encerrada.", Toast.LENGTH_SHORT).show()
|
||||||
|
},
|
||||||
|
shape = RoundedCornerShape(8.dp),
|
||||||
|
border = BorderStroke(1.dp, Color.Red),
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Text("Restaurar Data Real", fontWeight = FontWeight.Bold, color = Color.Red)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (showDatePicker) {
|
||||||
|
val datePickerState = rememberDatePickerState(
|
||||||
|
initialSelectedDateMillis = selectedDateMillis
|
||||||
|
)
|
||||||
|
DatePickerDialog(
|
||||||
|
onDismissRequest = { showDatePicker = false },
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(
|
||||||
|
onClick = {
|
||||||
|
datePickerState.selectedDateMillis?.let {
|
||||||
|
selectedDateMillis = it
|
||||||
|
}
|
||||||
|
showDatePicker = false
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
Text("OK", fontWeight = FontWeight.Bold, color = BrandGreen)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = { showDatePicker = false }) {
|
||||||
|
Text("Cancelar")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
DatePicker(state = datePickerState)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun ConflictsDialog(
|
fun ConflictsDialog(
|
||||||
@@ -945,4 +1054,142 @@ fun AppLogsHistoryDialog(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun AutoSyncStatusCard(
|
||||||
|
autoSyncIntervalMinutes: Int,
|
||||||
|
isNetworkConnected: Boolean,
|
||||||
|
isSyncing: Boolean,
|
||||||
|
lastSyncTimestamp: Long?
|
||||||
|
) {
|
||||||
|
val dateFormatter = remember { SimpleDateFormat("HH:mm:ss - dd/MM/yyyy", Locale.getDefault()) }
|
||||||
|
val lastSyncFormatted = remember(lastSyncTimestamp) {
|
||||||
|
if (lastSyncTimestamp != null && lastSyncTimestamp > 0) {
|
||||||
|
dateFormatter.format(Date(lastSyncTimestamp))
|
||||||
|
} else {
|
||||||
|
"Nenhuma sincronização nesta sessão"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Card(
|
||||||
|
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||||
|
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
|
||||||
|
shape = RoundedCornerShape(12.dp),
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.padding(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(10.dp)
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(10.dp)
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.Sync,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = BrandGreen,
|
||||||
|
modifier = Modifier.size(24.dp)
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "Sincronização Automática em Background",
|
||||||
|
fontSize = 16.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = BrandBlack
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
HorizontalDivider(color = LightGrey)
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Frequência / Período:",
|
||||||
|
fontSize = 13.sp,
|
||||||
|
color = Color.Gray
|
||||||
|
)
|
||||||
|
Surface(
|
||||||
|
color = BrandLightGreen,
|
||||||
|
shape = RoundedCornerShape(16.dp)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "A cada $autoSyncIntervalMinutes minutos",
|
||||||
|
fontSize = 12.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = BrandGreen,
|
||||||
|
modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Abrangência:",
|
||||||
|
fontSize = 13.sp,
|
||||||
|
color = Color.Gray
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = "Ativa em qualquer tela",
|
||||||
|
fontSize = 13.sp,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
color = BrandBlack
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Status da Conexão:",
|
||||||
|
fontSize = 13.sp,
|
||||||
|
color = Color.Gray
|
||||||
|
)
|
||||||
|
Row(
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(6.dp)
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(8.dp)
|
||||||
|
.clip(androidx.compose.foundation.shape.CircleShape)
|
||||||
|
.background(if (isNetworkConnected) BrandGreen else Color.Red)
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = if (isSyncing) "Sincronizando..." else if (isNetworkConnected) "Conectado ao BD Online" else "Modo Offline",
|
||||||
|
fontSize = 13.sp,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
color = if (isSyncing) Color(0xFFFF9100) else if (isNetworkConnected) BrandGreen else Color.Red
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Última Sincronização:",
|
||||||
|
fontSize = 13.sp,
|
||||||
|
color = Color.Gray
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = lastSyncFormatted,
|
||||||
|
fontSize = 12.sp,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
color = BrandBlack
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -12,14 +12,18 @@ import com.example.data.model.SyncConflictLog
|
|||||||
import com.example.data.model.extractDateOnly
|
import com.example.data.model.extractDateOnly
|
||||||
import com.example.data.model.formatToShortDate
|
import com.example.data.model.formatToShortDate
|
||||||
import com.example.data.model.parseFullDateTime
|
import com.example.data.model.parseFullDateTime
|
||||||
import com.example.data.model.AnalyticsState
|
|
||||||
import com.example.data.model.parseDateOnly
|
|
||||||
import com.example.data.repository.MaintenanceRepository
|
import com.example.data.repository.MaintenanceRepository
|
||||||
import com.example.data.repository.SyncResult
|
import com.example.data.repository.SyncResult
|
||||||
|
import com.example.data.model.AnalyticsState
|
||||||
|
import com.example.data.model.parseDateOnly
|
||||||
|
import com.example.data.model.AppSecurityState
|
||||||
|
import com.example.data.model.DateSimulationConfig
|
||||||
|
import com.example.data.model.DateSimulationMode
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.flow.flowOn
|
import kotlinx.coroutines.flow.flowOn
|
||||||
import java.util.Calendar
|
import java.util.Calendar
|
||||||
import java.util.Date
|
import java.util.Date
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.SharingStarted
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
@@ -33,6 +37,102 @@ import kotlinx.coroutines.launch
|
|||||||
|
|
||||||
class MaintenanceViewModel(private val repository: MaintenanceRepository) : ViewModel() {
|
class MaintenanceViewModel(private val repository: MaintenanceRepository) : ViewModel() {
|
||||||
|
|
||||||
|
init {
|
||||||
|
viewModelScope.launch {
|
||||||
|
repository.seedDefaultConfigsIfEmpty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val importantLinks: StateFlow<List<com.example.data.model.ImportantLink>> = repository.allConfigs
|
||||||
|
.map { configs -> parseImportantLinks(configs) }
|
||||||
|
.stateIn(
|
||||||
|
scope = viewModelScope,
|
||||||
|
started = SharingStarted.WhileSubscribed(5000),
|
||||||
|
initialValue = getDefaultImportantLinks()
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun parseImportantLinks(configs: List<com.example.data.model.AppConfig>): List<com.example.data.model.ImportantLink> {
|
||||||
|
if (configs.isEmpty()) return getDefaultImportantLinks()
|
||||||
|
val configMap = configs.associateBy { it.key }
|
||||||
|
val defaultLinks = getDefaultImportantLinks()
|
||||||
|
val result = mutableListOf<com.example.data.model.ImportantLink>()
|
||||||
|
|
||||||
|
for (i in 1..3) {
|
||||||
|
val linkKey = "Link$i"
|
||||||
|
val descKey = "DescricaoLink$i"
|
||||||
|
val defaultItem = defaultLinks.getOrNull(i - 1)
|
||||||
|
|
||||||
|
val url = configMap[linkKey]?.value?.trim()?.takeIf { it.isNotBlank() }
|
||||||
|
?: defaultItem?.url
|
||||||
|
?: "https://exemple.com"
|
||||||
|
|
||||||
|
val title = configMap[descKey]?.value?.trim()?.takeIf { it.isNotBlank() }
|
||||||
|
?: configMap[descKey]?.description?.trim()?.takeIf { it.isNotBlank() }
|
||||||
|
?: defaultItem?.title
|
||||||
|
?: "Link $i"
|
||||||
|
|
||||||
|
val description = configMap[linkKey]?.description?.trim()?.takeIf { it.isNotBlank() }
|
||||||
|
?: configMap[descKey]?.description?.trim()?.takeIf { it.isNotBlank() }
|
||||||
|
?: defaultItem?.description
|
||||||
|
|
||||||
|
result.add(
|
||||||
|
com.example.data.model.ImportantLink(
|
||||||
|
id = i.toString(),
|
||||||
|
title = title,
|
||||||
|
url = url,
|
||||||
|
description = description
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val link4Obj = configMap["Link4"]
|
||||||
|
val link4Url = link4Obj?.value?.trim()?.takeIf { it.isNotBlank() }
|
||||||
|
if (link4Obj != null && link4Url != null) {
|
||||||
|
val descObj = configMap["DescricaoLink4"]
|
||||||
|
val title = descObj?.value?.trim()?.takeIf { it.isNotBlank() }
|
||||||
|
?: descObj?.description?.trim()?.takeIf { it.isNotBlank() }
|
||||||
|
?: link4Obj.description?.trim()?.takeIf { it.isNotBlank() }
|
||||||
|
?: "Link 4"
|
||||||
|
|
||||||
|
val description = link4Obj.description?.trim()?.takeIf { it.isNotBlank() }
|
||||||
|
?: descObj?.description?.trim()?.takeIf { it.isNotBlank() }
|
||||||
|
|
||||||
|
result.add(
|
||||||
|
com.example.data.model.ImportantLink(
|
||||||
|
id = "4",
|
||||||
|
title = title,
|
||||||
|
url = link4Url,
|
||||||
|
description = description
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getDefaultImportantLinks(): List<com.example.data.model.ImportantLink> {
|
||||||
|
return listOf(
|
||||||
|
com.example.data.model.ImportantLink(
|
||||||
|
id = "1",
|
||||||
|
title = "Link do RDS (Relato de Segurança)",
|
||||||
|
url = "https://forms.office.com/Pages/ResponsePage.aspx?id=IYw2V8-4z0K9C0Ps1LxirnRboL6yMAxJn4T7PLeH0KtURjNLNlNJQTdHU0JMVlVNMlJISlNTSFJFRyQlQCN0PWcu&origin=APPgestaoos",
|
||||||
|
description = "Link para ser exibido na tela de informações"
|
||||||
|
),
|
||||||
|
com.example.data.model.ImportantLink(
|
||||||
|
id = "2",
|
||||||
|
title = "Informações de privacidade do APP",
|
||||||
|
url = "https://exemple.com",
|
||||||
|
description = "Informações de privacidade"
|
||||||
|
),
|
||||||
|
com.example.data.model.ImportantLink(
|
||||||
|
id = "3",
|
||||||
|
title = "Termos de uso deste APP",
|
||||||
|
url = "https://exemple.com",
|
||||||
|
description = "Termos de uso do APP"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// Filtering inputs
|
// Filtering inputs
|
||||||
private val _selectedSetor = MutableStateFlow("Todos")
|
private val _selectedSetor = MutableStateFlow("Todos")
|
||||||
val selectedSetor = _selectedSetor.asStateFlow()
|
val selectedSetor = _selectedSetor.asStateFlow()
|
||||||
@@ -65,10 +165,29 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
// UI Operation States
|
// UI Operation States
|
||||||
private val _isSyncing = MutableStateFlow(false)
|
private val _isSyncing = MutableStateFlow(false)
|
||||||
val isSyncing = _isSyncing.asStateFlow()
|
val isSyncing = _isSyncing.asStateFlow()
|
||||||
|
val isNetworkConnected = repository.isNetworkConnected
|
||||||
|
|
||||||
private val _syncStatusMessage = MutableStateFlow<String?>(null)
|
private val _syncStatusMessage = MutableStateFlow<String?>(null)
|
||||||
val syncStatusMessage = _syncStatusMessage.asStateFlow()
|
val syncStatusMessage = _syncStatusMessage.asStateFlow()
|
||||||
|
|
||||||
|
// Auto-Sync Background Loop & Last Sync State
|
||||||
|
private val _autoSyncIntervalMinutes = MutableStateFlow(AUTO_SYNC_INTERVAL_MINUTES)
|
||||||
|
val autoSyncIntervalMinutes = _autoSyncIntervalMinutes.asStateFlow()
|
||||||
|
|
||||||
|
private val _lastSyncTimestamp = MutableStateFlow<Long?>(null)
|
||||||
|
val lastSyncTimestamp = _lastSyncTimestamp.asStateFlow()
|
||||||
|
|
||||||
|
private var autoSyncJob: kotlinx.coroutines.Job? = null
|
||||||
|
|
||||||
|
val appSecurityState: StateFlow<AppSecurityState> = repository.appSecurityState.stateIn(
|
||||||
|
scope = viewModelScope,
|
||||||
|
started = SharingStarted.WhileSubscribed(5000),
|
||||||
|
initialValue = AppSecurityState.Allowed
|
||||||
|
)
|
||||||
|
|
||||||
|
private val _isRefreshingConfig = MutableStateFlow(false)
|
||||||
|
val isRefreshingConfig = _isRefreshingConfig.asStateFlow()
|
||||||
|
|
||||||
private val _importStatusMessage = MutableStateFlow<String?>(null)
|
private val _importStatusMessage = MutableStateFlow<String?>(null)
|
||||||
val importStatusMessage = _importStatusMessage.asStateFlow()
|
val importStatusMessage = _importStatusMessage.asStateFlow()
|
||||||
|
|
||||||
@@ -80,6 +199,36 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
private val _selectedActivity = MutableStateFlow<MaintenanceActivity?>(null)
|
private val _selectedActivity = MutableStateFlow<MaintenanceActivity?>(null)
|
||||||
val selectedActivity = _selectedActivity.asStateFlow()
|
val selectedActivity = _selectedActivity.asStateFlow()
|
||||||
|
|
||||||
|
// Simulation state
|
||||||
|
private val _simulationConfig = MutableStateFlow(DateSimulationConfig())
|
||||||
|
val simulationConfig: StateFlow<DateSimulationConfig> = _simulationConfig.asStateFlow()
|
||||||
|
|
||||||
|
private var simulationTimerJob: kotlinx.coroutines.Job? = null
|
||||||
|
|
||||||
|
fun setDateSimulation(simulatedDateMillis: Long, mode: DateSimulationMode) {
|
||||||
|
simulationTimerJob?.cancel()
|
||||||
|
val expirationMs = System.currentTimeMillis() + 15 * 60 * 1000L // 15 min
|
||||||
|
_simulationConfig.value = DateSimulationConfig(
|
||||||
|
simulatedDateMillis = simulatedDateMillis,
|
||||||
|
mode = mode,
|
||||||
|
expirationTimestampMillis = expirationMs
|
||||||
|
)
|
||||||
|
|
||||||
|
simulationTimerJob = viewModelScope.launch {
|
||||||
|
kotlinx.coroutines.delay(15 * 60 * 1000L)
|
||||||
|
clearDateSimulation(byTimeout = true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearDateSimulation(byTimeout: Boolean = false) {
|
||||||
|
simulationTimerJob?.cancel()
|
||||||
|
simulationTimerJob = null
|
||||||
|
_simulationConfig.value = DateSimulationConfig()
|
||||||
|
if (byTimeout) {
|
||||||
|
_syncStatusMessage.value = "Tempo máximo de 15 minutos no modo simulação atingido. A simulação foi encerrada."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// All activities from repository
|
// All activities from repository
|
||||||
val allActivitiesState: StateFlow<List<MaintenanceActivity>> = repository.allActivities
|
val allActivitiesState: StateFlow<List<MaintenanceActivity>> = repository.allActivities
|
||||||
.stateIn(
|
.stateIn(
|
||||||
@@ -109,11 +258,74 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val uniqueSectors: StateFlow<List<String>> = repository.allActivities
|
||||||
|
.map { activities ->
|
||||||
|
val sectors = activities.map { it.setor }.filter { it.isNotBlank() }.distinct().sorted()
|
||||||
|
listOf("Todos") + sectors
|
||||||
|
}
|
||||||
|
.flowOn(Dispatchers.Default)
|
||||||
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), listOf("Todos"))
|
||||||
|
|
||||||
|
val uniqueEquipes: StateFlow<List<String>> = repository.allActivities
|
||||||
|
.map { activities ->
|
||||||
|
val eqList = activities.map { it.equipe.trim() }.filter { it.isNotBlank() }.distinct().sorted()
|
||||||
|
listOf("Todas") + eqList
|
||||||
|
}
|
||||||
|
.flowOn(Dispatchers.Default)
|
||||||
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), listOf("Todas"))
|
||||||
|
|
||||||
|
val uniqueRecursos: StateFlow<List<String>> = repository.allActivities
|
||||||
|
.map { activities ->
|
||||||
|
val recs = activities.flatMap { activity ->
|
||||||
|
activity.recurso.split(";").map { it.trim() }
|
||||||
|
}.filter {
|
||||||
|
it.isNotBlank() &&
|
||||||
|
it != "Sem Responsável" && it != "Sem responsável" &&
|
||||||
|
it != "Sem Recurso" && it != "Sem recurso"
|
||||||
|
}.distinct().sorted()
|
||||||
|
listOf("Todos") + recs
|
||||||
|
}
|
||||||
|
.flowOn(Dispatchers.Default)
|
||||||
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), listOf("Todos"))
|
||||||
|
|
||||||
|
val uniqueDates: StateFlow<List<String>> = repository.allActivities
|
||||||
|
.map { activities ->
|
||||||
|
val datesOnly = activities
|
||||||
|
.map { extractDateOnly(it.dataInicio) }
|
||||||
|
.filter { it.isNotBlank() && it != "N/A" }
|
||||||
|
.distinct()
|
||||||
|
|
||||||
|
val sortedDates = datesOnly.sortedWith { d1, d2 ->
|
||||||
|
val parsed1 = parseDateOnly(d1)
|
||||||
|
val parsed2 = parseDateOnly(d2)
|
||||||
|
when {
|
||||||
|
parsed1 == null && parsed2 == null -> d1.compareTo(d2)
|
||||||
|
parsed1 == null -> 1
|
||||||
|
parsed2 == null -> -1
|
||||||
|
else -> parsed1.compareTo(parsed2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val formattedDates = sortedDates.map { formatToShortDate(it) }.distinct()
|
||||||
|
listOf("Todas") + formattedDates
|
||||||
|
}
|
||||||
|
.flowOn(Dispatchers.Default)
|
||||||
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), listOf("Todas"))
|
||||||
|
|
||||||
|
private val _selectedSetorSCurve = MutableStateFlow("Todos")
|
||||||
|
val selectedSetorSCurve = _selectedSetorSCurve.asStateFlow()
|
||||||
|
|
||||||
|
fun setFilterSetorSCurve(setor: String) {
|
||||||
|
_selectedSetorSCurve.value = setor
|
||||||
|
}
|
||||||
|
|
||||||
val analyticsState: StateFlow<AnalyticsState> = combine(
|
val analyticsState: StateFlow<AnalyticsState> = combine(
|
||||||
repository.allActivities,
|
repository.allActivities,
|
||||||
repository.allHistory
|
repository.allHistory,
|
||||||
) { activities, history ->
|
_selectedSetorSCurve,
|
||||||
calculateAnalyticsState(activities, history)
|
_simulationConfig
|
||||||
|
) { activities, history, setorSCurve, simConfig ->
|
||||||
|
val refDate = if (simConfig.isActive && simConfig.simulatedDateMillis != null) Date(simConfig.simulatedDateMillis) else null
|
||||||
|
calculateAnalyticsState(activities, history, referenceDateOverride = refDate, selectedSetorSCurve = setorSCurve)
|
||||||
}
|
}
|
||||||
.flowOn(Dispatchers.Default)
|
.flowOn(Dispatchers.Default)
|
||||||
.stateIn(
|
.stateIn(
|
||||||
@@ -157,7 +369,8 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
val matchQuery = query.isBlank() ||
|
val matchQuery = query.isBlank() ||
|
||||||
activity.numeroOs.contains(query, ignoreCase = true) ||
|
activity.numeroOs.contains(query, ignoreCase = true) ||
|
||||||
activity.descricao.contains(query, ignoreCase = true) ||
|
activity.descricao.contains(query, ignoreCase = true) ||
|
||||||
activity.recurso.contains(query, ignoreCase = true)
|
activity.recurso.contains(query, ignoreCase = true) ||
|
||||||
|
activity.tag.contains(query, ignoreCase = true)
|
||||||
|
|
||||||
val matchQuickFilter = when (quickFilter) {
|
val matchQuickFilter = when (quickFilter) {
|
||||||
"Todos" -> true
|
"Todos" -> true
|
||||||
@@ -187,33 +400,34 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
// Always sort by dataFim (predicted completion date) ascending, oldest first
|
// Always sort by dataInicio (start date) ascending, oldest first. OSs without start date appear at the very end.
|
||||||
filtered.sortedWith { a1, a2 ->
|
filtered.sortedWith { a1, a2 ->
|
||||||
val p1 = parseFullDateTime(a1.dataFim)
|
val p1 = if (a1.dataInicio.isNullOrBlank() || a1.dataInicioMillis == 0L) Long.MAX_VALUE else a1.dataInicioMillis
|
||||||
val p2 = parseFullDateTime(a2.dataFim)
|
val p2 = if (a2.dataInicio.isNullOrBlank() || a2.dataInicioMillis == 0L) Long.MAX_VALUE else a2.dataInicioMillis
|
||||||
when {
|
when {
|
||||||
p1 == null && p2 == null -> a1.numeroOs.compareTo(a2.numeroOs)
|
p1 == Long.MAX_VALUE && p2 == Long.MAX_VALUE -> {
|
||||||
p1 == null -> 1 // Keep null/invalid date at the end
|
val f1 = a1.dataFimMillis
|
||||||
p2 == null -> -1
|
val f2 = a2.dataFimMillis
|
||||||
|
val endComp = f1.compareTo(f2)
|
||||||
|
if (endComp != 0) endComp else a1.numeroOs.compareTo(a2.numeroOs)
|
||||||
|
}
|
||||||
|
p1 == Long.MAX_VALUE -> 1
|
||||||
|
p2 == Long.MAX_VALUE -> -1
|
||||||
else -> {
|
else -> {
|
||||||
val comp = p1.compareTo(p2)
|
val comp = p1.compareTo(p2)
|
||||||
if (comp != 0) {
|
if (comp != 0) {
|
||||||
comp
|
comp
|
||||||
} else {
|
} else {
|
||||||
val s1 = parseFullDateTime(a1.dataInicio)
|
val f1 = a1.dataFimMillis
|
||||||
val s2 = parseFullDateTime(a2.dataInicio)
|
val f2 = a2.dataFimMillis
|
||||||
val startComp = when {
|
val endComp = f1.compareTo(f2)
|
||||||
s1 == null && s2 == null -> 0
|
if (endComp != 0) endComp else a1.numeroOs.compareTo(a2.numeroOs)
|
||||||
s1 == null -> 1
|
|
||||||
s2 == null -> -1
|
|
||||||
else -> s1.compareTo(s2)
|
|
||||||
}
|
|
||||||
if (startComp != 0) startComp else a1.numeroOs.compareTo(a2.numeroOs)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}.stateIn(
|
}.flowOn(Dispatchers.Default)
|
||||||
|
.stateIn(
|
||||||
scope = viewModelScope,
|
scope = viewModelScope,
|
||||||
started = SharingStarted.WhileSubscribed(5000),
|
started = SharingStarted.WhileSubscribed(5000),
|
||||||
initialValue = emptyList()
|
initialValue = emptyList()
|
||||||
@@ -235,6 +449,23 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
initialValue = emptyList()
|
initialValue = emptyList()
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Reactive Flow for the current activity's findings (Achados & Observações)
|
||||||
|
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||||
|
val selectedActivityFindings: StateFlow<List<com.example.data.model.OSFinding>> = _selectedActivity
|
||||||
|
.flatMapLatest { activity ->
|
||||||
|
if (activity != null) {
|
||||||
|
repository.getFindingsForOs(activity.numeroOs)
|
||||||
|
} else {
|
||||||
|
flowOf(emptyList())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.stateIn(
|
||||||
|
scope = viewModelScope,
|
||||||
|
started = SharingStarted.WhileSubscribed(5000),
|
||||||
|
initialValue = emptyList()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
init {
|
init {
|
||||||
val savedUser = repository.getSavedUser()
|
val savedUser = repository.getSavedUser()
|
||||||
_currentUser.value = savedUser
|
_currentUser.value = savedUser
|
||||||
@@ -257,6 +488,9 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
isFirstEmission = false
|
isFirstEmission = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Start periodic auto-sync background loop (every 5 minutes)
|
||||||
|
startAutoSyncLoop()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun selectActivity(activity: MaintenanceActivity?) {
|
fun selectActivity(activity: MaintenanceActivity?) {
|
||||||
@@ -318,26 +552,123 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun checkSecurityConfigNow() {
|
||||||
|
if (_isRefreshingConfig.value) return
|
||||||
|
viewModelScope.launch {
|
||||||
|
_isRefreshingConfig.value = true
|
||||||
|
_syncStatusMessage.value = "Consultando aba 'config' da planilha online..."
|
||||||
|
try {
|
||||||
|
val remoteConfigs = repository.refreshConfigs()
|
||||||
|
if (remoteConfigs.isEmpty()) {
|
||||||
|
_syncStatusMessage.value = "Não foi possível conectar à planilha online para atualizar as configurações."
|
||||||
|
} else {
|
||||||
|
val security = repository.evaluateSecurityState(remoteConfigs)
|
||||||
|
if (security is AppSecurityState.Allowed) {
|
||||||
|
_syncStatusMessage.value = "Configurações atualizadas: Acesso liberado com sucesso!"
|
||||||
|
} else {
|
||||||
|
_syncStatusMessage.value = "Configurações atualizadas: Aplicativo permanece restrito."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
_syncStatusMessage.value = "Erro ao buscar configurações remotas: ${e.localizedMessage}"
|
||||||
|
} finally {
|
||||||
|
_isRefreshingConfig.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Performs synchronized check.
|
* Performs synchronized check.
|
||||||
*/
|
*/
|
||||||
fun syncNow() {
|
fun syncNow() {
|
||||||
|
val currentSecurity = appSecurityState.value
|
||||||
|
if (currentSecurity !is AppSecurityState.Allowed) {
|
||||||
|
checkSecurityConfigNow()
|
||||||
|
repository.logAppLog("WARN", "SyncManager", "Sincronização manual impedida: aplicativo bloqueado por regras de segurança.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if (!_internetAvailable.value) {
|
if (!_internetAvailable.value) {
|
||||||
_syncStatusMessage.value = "Sincronização impossível: Sem conectividade de rede na área atual."
|
_syncStatusMessage.value = "Sincronização impossível: Sem conectividade de rede na área atual."
|
||||||
|
repository.logAppLog("WARN", "SyncManager", "Sincronização manual impedida: sem conexão com a internet.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (_isSyncing.value) {
|
if (_isSyncing.value) {
|
||||||
|
repository.logAppLog("WARN", "SyncManager", "Tentativa de sincronização ignorada: já existe uma sincronização em andamento.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
_isSyncing.value = true
|
_isSyncing.value = true
|
||||||
_syncStatusMessage.value = "Conectando ao servidor central..."
|
_syncStatusMessage.value = "Conectando ao servidor central..."
|
||||||
|
repository.logAppLog("INFO", "SyncManager", "Iniciando sincronização manual de dados...")
|
||||||
|
|
||||||
|
try {
|
||||||
|
when (val result = repository.synchronizeWithBackend()) {
|
||||||
|
is SyncResult.Success -> {
|
||||||
|
_lastSyncTimestamp.value = System.currentTimeMillis()
|
||||||
|
_syncStatusMessage.value = "Sincronização concluída! ${result.syncedItems} OSs sincronizadas com sucesso. Conflitos resolvidos: ${result.conflictsResolved}."
|
||||||
|
repository.logAppLog("INFO", "SyncManager", "Sincronização concluída com sucesso! ${result.syncedItems} itens sincronizados. Conflitos resolvidos: ${result.conflictsResolved}.")
|
||||||
|
// Refresh selected activity if active to show sync badge
|
||||||
|
_selectedActivity.value?.let { active ->
|
||||||
|
_selectedActivity.value = allActivitiesState.value.find { it.numeroOs == active.numeroOs }
|
||||||
|
}
|
||||||
|
_currentUser.value?.let { user ->
|
||||||
|
checkUserAccessLevel(user.email)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
is SyncResult.Error -> {
|
||||||
|
_syncStatusMessage.value = "Falha na sincronização: ${result.message}"
|
||||||
|
repository.logAppLog("ERROR", "SyncManager", "Falha na sincronização: ${result.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
_syncStatusMessage.value = "Erro na sincronização: ${e.message}"
|
||||||
|
repository.logAppLog("ERROR", "SyncManager", "Exceção na sincronização: ${e.message}", e)
|
||||||
|
} finally {
|
||||||
|
_isSyncing.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startAutoSyncLoop() {
|
||||||
|
autoSyncJob?.cancel()
|
||||||
|
autoSyncJob = viewModelScope.launch {
|
||||||
|
while (true) {
|
||||||
|
kotlinx.coroutines.delay(AUTO_SYNC_INTERVAL_MS)
|
||||||
|
performAutoSyncAttempt()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun performAutoSyncAttempt() {
|
||||||
|
val currentSecurity = appSecurityState.value
|
||||||
|
if (currentSecurity !is AppSecurityState.Allowed) {
|
||||||
|
repository.logAppLog("WARN", "AutoSync", "Tentativa de sincronização automática ignorada: aplicativo bloqueado por segurança.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!_internetAvailable.value) {
|
||||||
|
repository.logAppLog("WARN", "AutoSync", "Tentativa de sincronização automática ignorada: sem conectividade de rede no momento.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_isSyncing.value) {
|
||||||
|
repository.logAppLog("WARN", "AutoSync", "Tentativa de sincronização automática ignorada: outra sincronização já está em andamento.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
repository.logAppLog("INFO", "AutoSync", "Iniciando tentativa de sincronização automática em segundo plano (intervalo: $AUTO_SYNC_INTERVAL_MINUTES min)...")
|
||||||
|
|
||||||
|
_isSyncing.value = true
|
||||||
|
_syncStatusMessage.value = "Sincronizando em segundo plano (automático)..."
|
||||||
|
|
||||||
|
try {
|
||||||
when (val result = repository.synchronizeWithBackend()) {
|
when (val result = repository.synchronizeWithBackend()) {
|
||||||
is SyncResult.Success -> {
|
is SyncResult.Success -> {
|
||||||
_syncStatusMessage.value = "Sincronização concluída! ${result.syncedItems} OSs sincronizadas com sucesso. Conflitos resolvidos: ${result.conflictsResolved}."
|
_lastSyncTimestamp.value = System.currentTimeMillis()
|
||||||
// Refresh selected activity if active to show sync badge
|
_syncStatusMessage.value = "Sincronização automática concluída com sucesso! (${result.syncedItems} itens)"
|
||||||
|
repository.logAppLog("INFO", "AutoSync", "Sincronização automática concluída com sucesso! ${result.syncedItems} OSs sincronizadas. Conflitos resolvidos: ${result.conflictsResolved}.")
|
||||||
_selectedActivity.value?.let { active ->
|
_selectedActivity.value?.let { active ->
|
||||||
_selectedActivity.value = allActivitiesState.value.find { it.numeroOs == active.numeroOs }
|
_selectedActivity.value = allActivitiesState.value.find { it.numeroOs == active.numeroOs }
|
||||||
}
|
}
|
||||||
@@ -346,9 +677,13 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
is SyncResult.Error -> {
|
is SyncResult.Error -> {
|
||||||
_syncStatusMessage.value = "Falha na sincronização: ${result.message}"
|
_syncStatusMessage.value = "Falha na sincronização automática: ${result.message}"
|
||||||
|
repository.logAppLog("ERROR", "AutoSync", "Falha na sincronização automática: ${result.message}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
repository.logAppLog("ERROR", "AutoSync", "Exceção na sincronização automática: ${e.message}", e)
|
||||||
|
} finally {
|
||||||
_isSyncing.value = false
|
_isSyncing.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -393,7 +728,13 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
repository.updateProgress(numeroOs, novoPercentual, observacao, fotoPath, recurso, emailEditor)
|
val currentSim = _simulationConfig.value
|
||||||
|
val customTimestamp = if (currentSim.mode == DateSimulationMode.EDIT_PROGRESS) {
|
||||||
|
currentSim.simulatedDateMillis
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
repository.updateProgress(numeroOs, novoPercentual, observacao, fotoPath, recurso, emailEditor, customTimestamp)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_syncStatusMessage.value = e.message ?: "Erro ao atualizar a OS."
|
_syncStatusMessage.value = e.message ?: "Erro ao atualizar a OS."
|
||||||
return@launch
|
return@launch
|
||||||
@@ -412,6 +753,92 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private suspend fun checkUserCanEdit(): Boolean {
|
||||||
|
val user = _currentUser.value
|
||||||
|
if (user == null) {
|
||||||
|
_syncStatusMessage.value = "Erro: É necessário fazer login com o Google para realizar alterações."
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
val access = repository.getUserAccess(user.email)
|
||||||
|
val level = access?.nivelAcesso?.trim()?.lowercase()
|
||||||
|
if (level != "total" && level != "editor") {
|
||||||
|
_syncStatusMessage.value = "Erro: Nível de acesso '$level' não possui permissão para editar."
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addFinding(
|
||||||
|
numeroOs: String,
|
||||||
|
tipo: String,
|
||||||
|
descricao: String,
|
||||||
|
fotoPath: String? = null
|
||||||
|
) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
if (!checkUserCanEdit()) return@launch
|
||||||
|
val user = _currentUser.value!!
|
||||||
|
val recurso = user.displayName
|
||||||
|
val emailEditor = user.email
|
||||||
|
try {
|
||||||
|
repository.addFinding(numeroOs, tipo, descricao, recurso, emailEditor, fotoPath)
|
||||||
|
_selectedActivity.value?.let { active ->
|
||||||
|
if (active.numeroOs == numeroOs) {
|
||||||
|
_selectedActivity.value = allActivitiesState.value.find { it.numeroOs == numeroOs }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (_internetAvailable.value) {
|
||||||
|
syncNow()
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
_syncStatusMessage.value = e.message ?: "Erro ao salvar achado."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun updateFinding(finding: com.example.data.model.OSFinding) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
if (!checkUserCanEdit()) return@launch
|
||||||
|
val user = _currentUser.value!!
|
||||||
|
val recurso = user.displayName
|
||||||
|
val emailEditor = user.email
|
||||||
|
try {
|
||||||
|
repository.updateFinding(finding, recurso, emailEditor)
|
||||||
|
_selectedActivity.value?.let { active ->
|
||||||
|
if (active.numeroOs == finding.numeroOs) {
|
||||||
|
_selectedActivity.value = allActivitiesState.value.find { it.numeroOs == finding.numeroOs }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (_internetAvailable.value) {
|
||||||
|
syncNow()
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
_syncStatusMessage.value = e.message ?: "Erro ao atualizar achado."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deleteFinding(finding: com.example.data.model.OSFinding) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
if (!checkUserCanEdit()) return@launch
|
||||||
|
val user = _currentUser.value!!
|
||||||
|
val recurso = user.displayName
|
||||||
|
val emailEditor = user.email
|
||||||
|
try {
|
||||||
|
repository.deleteFinding(finding, recurso, emailEditor)
|
||||||
|
_selectedActivity.value?.let { active ->
|
||||||
|
if (active.numeroOs == finding.numeroOs) {
|
||||||
|
_selectedActivity.value = allActivitiesState.value.find { it.numeroOs == finding.numeroOs }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (_internetAvailable.value) {
|
||||||
|
syncNow()
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
_syncStatusMessage.value = e.message ?: "Erro ao excluir achado."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun saveLocalPhotoFromUri(uri: Uri, osNumber: String): String {
|
fun saveLocalPhotoFromUri(uri: Uri, osNumber: String): String {
|
||||||
return repository.saveLocalPhotoFromUri(uri, osNumber)
|
return repository.saveLocalPhotoFromUri(uri, osNumber)
|
||||||
}
|
}
|
||||||
@@ -422,12 +849,19 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
|
|
||||||
fun softDeletePhoto(fotoPath: String, osNumber: String) {
|
fun softDeletePhoto(fotoPath: String, osNumber: String) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
|
if (!checkUserCanEdit()) return@launch
|
||||||
try {
|
try {
|
||||||
repository.softDeletePhoto(fotoPath, osNumber)
|
repository.softDeletePhoto(fotoPath, osNumber)
|
||||||
_syncStatusMessage.value = "Foto excluída com sucesso."
|
_syncStatusMessage.value = "Foto excluída com sucesso."
|
||||||
if (_internetAvailable.value) {
|
// Refresh selected activity from local DB to reflect the deletion immediately
|
||||||
syncNow()
|
_selectedActivity.value?.let { active ->
|
||||||
|
if (active.numeroOs == osNumber) {
|
||||||
|
_selectedActivity.value = allActivitiesState.value.find { it.numeroOs == osNumber }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
// Do NOT auto-sync here — the sync would reconcile with remote data
|
||||||
|
// and potentially overwrite the local _DELETED marking while the dialog is open.
|
||||||
|
// The deletion will be synced on the next manual or periodic sync.
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
_syncStatusMessage.value = "Erro ao excluir foto: ${e.message}"
|
_syncStatusMessage.value = "Erro ao excluir foto: ${e.message}"
|
||||||
}
|
}
|
||||||
@@ -528,139 +962,153 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
fun calculateAnalyticsState(
|
fun calculateAnalyticsState(
|
||||||
activities: List<MaintenanceActivity>,
|
activities: List<MaintenanceActivity>,
|
||||||
history: List<OSUpdateHistory>,
|
history: List<OSUpdateHistory>,
|
||||||
referenceDateOverride: Date? = null
|
referenceDateOverride: Date? = null,
|
||||||
): AnalyticsState {
|
selectedSetorSCurve: String = "Todos"
|
||||||
if (activities.isEmpty()) {
|
): AnalyticsState = Companion.calculateAnalyticsState(activities, history, referenceDateOverride, selectedSetorSCurve)
|
||||||
return AnalyticsState()
|
|
||||||
}
|
|
||||||
|
|
||||||
// 1. Team metrics
|
companion object {
|
||||||
val teams = activities.map { it.equipe.trim() }.filter { it.isNotBlank() }.distinct().sorted()
|
private const val AUTO_SYNC_INTERVAL_MINUTES = 5
|
||||||
val teamMetrics = teams.map { team ->
|
private const val AUTO_SYNC_INTERVAL_MS = AUTO_SYNC_INTERVAL_MINUTES * 60 * 1000L
|
||||||
val teamActivities = activities.filter { it.equipe.equals(team, ignoreCase = true) }
|
|
||||||
val total = teamActivities.size
|
|
||||||
val completed = teamActivities.count { it.percentualExecucao >= 100 }
|
|
||||||
val ratio = if (total > 0) (completed.toFloat() / total.toFloat() * 100f).toInt() else 0
|
|
||||||
team to ratio
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. S-Curve bounds and steps
|
fun calculateAnalyticsState(
|
||||||
val parsedDates = activities.flatMap {
|
activities: List<MaintenanceActivity>,
|
||||||
listOfNotNull(
|
history: List<OSUpdateHistory>,
|
||||||
parseFullDateTime(it.dataInicio) ?: parseDateOnly(it.dataInicio),
|
referenceDateOverride: Date? = null,
|
||||||
parseFullDateTime(it.dataFim) ?: parseDateOnly(it.dataFim)
|
selectedSetorSCurve: String = "Todos"
|
||||||
)
|
): AnalyticsState {
|
||||||
}
|
if (activities.isEmpty()) {
|
||||||
|
return AnalyticsState()
|
||||||
val projectStart = parsedDates.minOrNull() ?: Calendar.getInstance().apply { set(2026, Calendar.AUGUST, 1) }.time
|
}
|
||||||
val projectEnd = parsedDates.maxOrNull() ?: Calendar.getInstance().apply { set(2026, Calendar.AUGUST, 29) }.time
|
|
||||||
|
|
||||||
val durationMs = projectEnd.time - projectStart.time
|
// 1. Team metrics
|
||||||
val timelineSteps = 5
|
val teams = activities.map { it.equipe.trim() }.filter { it.isNotBlank() }.distinct().sorted()
|
||||||
val timelineDates = (0 until timelineSteps).map { i ->
|
val teamMetrics = teams.map { team ->
|
||||||
Date(projectStart.time + (durationMs * i / (timelineSteps - 1)))
|
val teamActivities = activities.filter { it.equipe.equals(team, ignoreCase = true) }
|
||||||
}
|
val total = teamActivities.size
|
||||||
|
val completed = teamActivities.count { it.percentualExecucao >= 100 }
|
||||||
|
val ratio = if (total > 0) (completed.toFloat() / total.toFloat() * 100f).toInt() else 0
|
||||||
|
team to ratio
|
||||||
|
}
|
||||||
|
|
||||||
// Calculate Planned progress points
|
// 2. S-Curve bounds and steps using dataInicioMillis & dataFimMillis (Always global bounds across all activities)
|
||||||
val plannedProgressPoints = timelineDates.map { date ->
|
val startTimes = activities.map { it.dataInicioMillis }.filter { it > 0 }
|
||||||
val dayTime = date.time
|
val endTimes = activities.map { it.dataFimMillis }.filter { it < Long.MAX_VALUE }
|
||||||
val totalActivities = activities.size
|
|
||||||
if (totalActivities == 0) 0f
|
val minStartMs = startTimes.minOrNull() ?: Calendar.getInstance().apply { set(2026, Calendar.AUGUST, 1) }.timeInMillis
|
||||||
else {
|
val maxEndMs = endTimes.maxOrNull() ?: Calendar.getInstance().apply { set(2026, Calendar.AUGUST, 29) }.timeInMillis
|
||||||
val sum = activities.sumOf { act ->
|
|
||||||
val start = (parseFullDateTime(act.dataInicio) ?: parseDateOnly(act.dataInicio))?.time ?: dayTime
|
val projectStart = Date(minStartMs)
|
||||||
val end = (parseFullDateTime(act.dataFim) ?: parseDateOnly(act.dataFim))?.time ?: dayTime
|
val projectEnd = Date(maxEndMs)
|
||||||
when {
|
|
||||||
dayTime <= start -> 0
|
val durationMs = maxEndMs - minStartMs
|
||||||
dayTime >= end -> 100
|
val timelineSteps = 5
|
||||||
end <= start -> 100
|
val timelineDates = (0 until timelineSteps).map { i ->
|
||||||
else -> {
|
Date(minStartMs + if (timelineSteps > 1) (durationMs * i / (timelineSteps - 1)) else 0)
|
||||||
val progress = ((dayTime - start).toDouble() / (end - start).toDouble() * 100.0).toInt()
|
}
|
||||||
progress.coerceIn(0, 100)
|
|
||||||
|
// Filter activities for S-Curve calculation by selectedSetorSCurve
|
||||||
|
val sCurveActivities = if (selectedSetorSCurve == "Todos") {
|
||||||
|
activities
|
||||||
|
} else {
|
||||||
|
activities.filter { act ->
|
||||||
|
val actSetor = if (act.setor.isBlank()) "Sem Setor" else act.setor
|
||||||
|
actSetor == selectedSetorSCurve
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Weight total in hours for filtered activities
|
||||||
|
val totalHours = sCurveActivities.sumOf { it.duracaoHorasCalculada }
|
||||||
|
|
||||||
|
// Calculate Planned progress points (Weighted by duracaoHorasCalculada)
|
||||||
|
val plannedProgressPoints = timelineDates.map { date ->
|
||||||
|
val dayTime = date.time
|
||||||
|
if (totalHours <= 0.0) 0f
|
||||||
|
else {
|
||||||
|
val weightedSum = sCurveActivities.sumOf { act ->
|
||||||
|
val hours = act.duracaoHorasCalculada
|
||||||
|
val start = if (act.dataInicioMillis > 0) act.dataInicioMillis else dayTime
|
||||||
|
val end = if (act.dataFimMillis < Long.MAX_VALUE) act.dataFimMillis else dayTime
|
||||||
|
val pct = when {
|
||||||
|
dayTime <= start -> 0.0
|
||||||
|
dayTime >= end -> 100.0
|
||||||
|
end <= start -> 100.0
|
||||||
|
else -> {
|
||||||
|
((dayTime - start).toDouble() / (end - start).toDouble() * 100.0).coerceIn(0.0, 100.0)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
pct * hours
|
||||||
}
|
}
|
||||||
|
(weightedSum / totalHours).toFloat().coerceIn(0f, 100f)
|
||||||
}
|
}
|
||||||
sum.toFloat() / totalActivities.toFloat()
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Calculate Realized progress points
|
// Calculate Realized progress points (Weighted by duracaoHorasCalculada, O(1) history index)
|
||||||
val realizedProgressPoints = timelineDates.map { date ->
|
val historyByOs = history.groupBy { it.numeroOs }
|
||||||
val dayTime = date.time
|
val realizedProgressPoints = timelineDates.map { date ->
|
||||||
val totalActivities = activities.size
|
val dayTime = date.time
|
||||||
if (totalActivities == 0) 0f
|
if (totalHours <= 0.0) 0f
|
||||||
else {
|
else {
|
||||||
val sum = activities.sumOf { act ->
|
val weightedSum = sCurveActivities.sumOf { act ->
|
||||||
val osLogs = history.filter { it.numeroOs == act.numeroOs && it.timestamp <= dayTime }
|
val hours = act.duracaoHorasCalculada
|
||||||
if (osLogs.isNotEmpty()) {
|
val osLogs = historyByOs[act.numeroOs]?.filter { it.timestamp <= dayTime } ?: emptyList()
|
||||||
osLogs.last().percentualNovo
|
val pct = if (osLogs.isNotEmpty()) {
|
||||||
} else {
|
osLogs.last().percentualNovo.toDouble()
|
||||||
if (act.lastUpdated <= dayTime) act.percentualExecucao else 0
|
} else {
|
||||||
|
if (act.lastUpdated <= dayTime) act.percentualExecucao.toDouble() else 0.0
|
||||||
|
}
|
||||||
|
pct * hours
|
||||||
}
|
}
|
||||||
|
(weightedSum / totalHours).toFloat().coerceIn(0f, 100f)
|
||||||
}
|
}
|
||||||
sum.toFloat() / totalActivities.toFloat()
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Overdue tags and sectors (OSs em atraso consideram a data/hora atual real ou override de testes)
|
// 3. Overdue tags and sectors (OSs em atraso consideram a data/hora atual real ou override de testes)
|
||||||
val referenceDate = referenceDateOverride ?: Date()
|
val referenceDateMs = (referenceDateOverride ?: Date()).time
|
||||||
|
|
||||||
val overdueActivities = activities.filter { act ->
|
val overdueActivities = activities.filter { act ->
|
||||||
val isNotCompleted = act.percentualExecucao < 100
|
val isNotCompleted = act.percentualExecucao < 100
|
||||||
val endDate = parseFullDateTime(act.dataFim) ?: parseDateOnly(act.dataFim)
|
val endMs = act.dataFimMillis
|
||||||
isNotCompleted && endDate != null && endDate.before(referenceDate)
|
isNotCompleted && endMs < Long.MAX_VALUE && endMs < referenceDateMs
|
||||||
}
|
}
|
||||||
|
|
||||||
val overdueByTag = overdueActivities
|
val overdueByTagList = overdueActivities
|
||||||
.groupBy { if (it.tag.isBlank()) "Sem TAG" else it.tag }
|
.groupBy { if (it.tag.isBlank()) "Sem TAG" else it.tag }
|
||||||
.mapValues { it.value.size }
|
.mapValues { entry -> entry.value.sumOf { it.duracaoHorasCalculada } }
|
||||||
.toList()
|
.toList()
|
||||||
.sortedByDescending { it.second }
|
.sortedWith(compareByDescending<Pair<String, Double>> { it.second }.thenBy { it.first })
|
||||||
|
|
||||||
val displayLimit = 4
|
val finalOverdueByTag = if (overdueByTagList.size <= 9) {
|
||||||
val finalOverdueByTag = if (overdueByTag.size <= displayLimit) {
|
overdueByTagList
|
||||||
overdueByTag
|
} else {
|
||||||
} else {
|
val top = overdueByTagList.take(9)
|
||||||
val top = overdueByTag.take(displayLimit - 1)
|
val othersHours = overdueByTagList.drop(9).sumOf { it.second }
|
||||||
val othersCount = overdueByTag.drop(displayLimit - 1).sumOf { it.second }
|
top + listOf("Outros" to othersHours)
|
||||||
top + listOf("Outros" to othersCount)
|
}
|
||||||
}
|
|
||||||
|
|
||||||
val overdueBySectorMap = overdueActivities
|
val overdueBySectorMap = overdueActivities
|
||||||
.groupBy { if (it.setor.isBlank()) "Sem Setor" else it.setor }
|
.groupBy { if (it.setor.isBlank()) "Sem Setor" else it.setor }
|
||||||
.mapValues { it.value.size }
|
.mapValues { entry -> entry.value.sumOf { it.duracaoHorasCalculada } }
|
||||||
|
|
||||||
val finalOverdueBySector = if (overdueActivities.isEmpty()) {
|
|
||||||
emptyList()
|
|
||||||
} else {
|
|
||||||
val plantSectors = activities
|
val plantSectors = activities
|
||||||
.map { if (it.setor.isBlank()) "Sem Setor" else it.setor }
|
.map { if (it.setor.isBlank()) "Sem Setor" else it.setor }
|
||||||
.distinct()
|
.distinct()
|
||||||
|
|
||||||
val fullOverdueBySector = plantSectors
|
val finalOverdueBySector = plantSectors
|
||||||
.map { sector -> sector to (overdueBySectorMap[sector] ?: 0) }
|
.map { sector -> sector to (overdueBySectorMap[sector] ?: 0.0) }
|
||||||
.sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first })
|
.sortedWith(compareByDescending<Pair<String, Double>> { it.second }.thenBy { it.first })
|
||||||
|
|
||||||
val displayLimit = 4
|
return AnalyticsState(
|
||||||
if (fullOverdueBySector.size <= displayLimit) {
|
teamMetrics = teamMetrics,
|
||||||
fullOverdueBySector
|
projectStart = projectStart,
|
||||||
} else {
|
projectEnd = projectEnd,
|
||||||
val top = fullOverdueBySector.take(displayLimit - 1)
|
timelineDates = timelineDates,
|
||||||
val othersCount = fullOverdueBySector.drop(displayLimit - 1).sumOf { it.second }
|
plannedProgressPoints = plannedProgressPoints,
|
||||||
top + listOf("Outros" to othersCount)
|
realizedProgressPoints = realizedProgressPoints,
|
||||||
}
|
overdueByTag = finalOverdueByTag,
|
||||||
|
overdueBySector = finalOverdueBySector,
|
||||||
|
selectedSetorSCurve = selectedSetorSCurve
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return AnalyticsState(
|
|
||||||
teamMetrics = teamMetrics,
|
|
||||||
projectStart = projectStart,
|
|
||||||
projectEnd = projectEnd,
|
|
||||||
timelineDates = timelineDates,
|
|
||||||
plannedProgressPoints = plannedProgressPoints,
|
|
||||||
realizedProgressPoints = realizedProgressPoints,
|
|
||||||
overdueByTag = finalOverdueByTag,
|
|
||||||
overdueBySector = finalOverdueBySector
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
61
app/src/main/java/com/example/util/DeviceUtils.kt
Normal file
61
app/src/main/java/com/example/util/DeviceUtils.kt
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package com.example.util
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.Build
|
||||||
|
import android.provider.Settings
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
object DeviceUtils {
|
||||||
|
|
||||||
|
fun getDeviceId(context: Context): String {
|
||||||
|
val androidId = try {
|
||||||
|
Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!androidId.isNullOrBlank() && androidId != "9774d56d682e549c") {
|
||||||
|
return androidId
|
||||||
|
}
|
||||||
|
|
||||||
|
val prefs = context.getSharedPreferences("device_prefs", Context.MODE_PRIVATE)
|
||||||
|
var uuid = prefs.getString("device_uuid", null)
|
||||||
|
if (uuid.isNullOrBlank()) {
|
||||||
|
uuid = UUID.randomUUID().toString()
|
||||||
|
prefs.edit().putString("device_uuid", uuid).apply()
|
||||||
|
}
|
||||||
|
return uuid
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getDeviceModel(): String {
|
||||||
|
val manufacturer = Build.MANUFACTURER ?: ""
|
||||||
|
val model = Build.MODEL ?: ""
|
||||||
|
return if (model.startsWith(manufacturer, ignoreCase = true)) {
|
||||||
|
model.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }
|
||||||
|
} else {
|
||||||
|
"${manufacturer.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }} $model"
|
||||||
|
}.trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getAndroidVersion(): String {
|
||||||
|
val release = Build.VERSION.RELEASE ?: "Unknown"
|
||||||
|
val sdk = Build.VERSION.SDK_INT
|
||||||
|
return "Android $release (API $sdk)"
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getAppVersion(context: Context): String {
|
||||||
|
return try {
|
||||||
|
val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
|
||||||
|
val versionName = packageInfo.versionName ?: "1.4.0"
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
val versionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||||
|
packageInfo.longVersionCode
|
||||||
|
} else {
|
||||||
|
packageInfo.versionCode.toLong()
|
||||||
|
}
|
||||||
|
"$versionName (v$versionCode)"
|
||||||
|
} catch (e: Exception) {
|
||||||
|
"1.4.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
241
app/src/main/java/com/example/util/ImageCompressor.kt
Normal file
241
app/src/main/java/com/example/util/ImageCompressor.kt
Normal file
@@ -0,0 +1,241 @@
|
|||||||
|
package com.example.util
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import android.graphics.Matrix
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Build
|
||||||
|
import android.util.Log
|
||||||
|
import android.media.ExifInterface
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.File
|
||||||
|
import java.io.FileOutputStream
|
||||||
|
import java.io.InputStream
|
||||||
|
|
||||||
|
object ImageCompressor {
|
||||||
|
|
||||||
|
private const val TAG = "ImageCompressor"
|
||||||
|
private const val MAX_DIMENSION = 1920
|
||||||
|
private const val DEFAULT_MAX_SIZE_BYTES = 500 * 1024L // 500 KB
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compresses an image from a [Uri] (supporting JPEG, PNG, HEIC/HEIF, WEBP)
|
||||||
|
* and saves it to [targetFile] as JPEG guaranteed to be <= [maxSizeBytes].
|
||||||
|
*/
|
||||||
|
fun compressUriToJpegFile(
|
||||||
|
context: Context,
|
||||||
|
uri: Uri,
|
||||||
|
targetFile: File,
|
||||||
|
maxSizeBytes: Long = DEFAULT_MAX_SIZE_BYTES
|
||||||
|
): File {
|
||||||
|
return try {
|
||||||
|
val inputStream = context.contentResolver.openInputStream(uri)
|
||||||
|
?: throw IllegalArgumentException("Não foi possível abrir o Uri: $uri")
|
||||||
|
|
||||||
|
// Read orientation if available
|
||||||
|
val orientation = getOrientationFromUri(context, uri)
|
||||||
|
|
||||||
|
val bitmap = decodeBitmapFromStream(context, uri, inputStream, MAX_DIMENSION, MAX_DIMENSION)
|
||||||
|
?: throw IllegalStateException("Falha ao decodificar imagem a partir de Uri: $uri")
|
||||||
|
|
||||||
|
val rotatedBitmap = rotateBitmap(bitmap, orientation)
|
||||||
|
compressBitmapToFile(rotatedBitmap, targetFile, maxSizeBytes)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "Erro ao comprimir imagem a partir de Uri $uri: ${e.message}", e)
|
||||||
|
// Fallback: try direct stream copy if decode fails
|
||||||
|
try {
|
||||||
|
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||||
|
targetFile.outputStream().use { output ->
|
||||||
|
input.copyTo(output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (fallbackEx: Exception) {
|
||||||
|
Log.e(TAG, "Erro no fallback de cópia de imagem: ${fallbackEx.message}", fallbackEx)
|
||||||
|
}
|
||||||
|
targetFile
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compresses an existing local [inputFile] (supporting JPEG, PNG, HEIC/HEIF)
|
||||||
|
* so that it is guaranteed to be <= [maxSizeBytes]. Returns the compressed file (or original if already <= maxSizeBytes).
|
||||||
|
*/
|
||||||
|
fun compressImageFile(
|
||||||
|
inputFile: File,
|
||||||
|
maxSizeBytes: Long = DEFAULT_MAX_SIZE_BYTES
|
||||||
|
): File {
|
||||||
|
if (!inputFile.exists()) return inputFile
|
||||||
|
|
||||||
|
// If file is already smaller than maxSizeBytes and is a standard JPG, return as is
|
||||||
|
if (inputFile.length() <= maxSizeBytes && inputFile.extension.lowercase() in listOf("jpg", "jpeg")) {
|
||||||
|
return inputFile
|
||||||
|
}
|
||||||
|
|
||||||
|
return try {
|
||||||
|
val orientation = getOrientationFromFile(inputFile)
|
||||||
|
val options = BitmapFactory.Options().apply {
|
||||||
|
inJustDecodeBounds = true
|
||||||
|
}
|
||||||
|
BitmapFactory.decodeFile(inputFile.absolutePath, options)
|
||||||
|
|
||||||
|
val sampleSize = calculateInSampleSize(options, MAX_DIMENSION, MAX_DIMENSION)
|
||||||
|
val decodeOptions = BitmapFactory.Options().apply {
|
||||||
|
inSampleSize = sampleSize
|
||||||
|
}
|
||||||
|
|
||||||
|
val decodedBitmap = BitmapFactory.decodeFile(inputFile.absolutePath, decodeOptions)
|
||||||
|
?: return inputFile
|
||||||
|
|
||||||
|
val rotatedBitmap = rotateBitmap(decodedBitmap, orientation)
|
||||||
|
val compressedFile = compressBitmapToFile(rotatedBitmap, inputFile, maxSizeBytes)
|
||||||
|
compressedFile
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "Erro ao comprimir arquivo de imagem ${inputFile.name}: ${e.message}", e)
|
||||||
|
inputFile
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun decodeBitmapFromStream(
|
||||||
|
context: Context,
|
||||||
|
uri: Uri,
|
||||||
|
inputStream: InputStream,
|
||||||
|
reqWidth: Int,
|
||||||
|
reqHeight: Int
|
||||||
|
): Bitmap? {
|
||||||
|
return try {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||||
|
val source = android.graphics.ImageDecoder.createSource(context.contentResolver, uri)
|
||||||
|
android.graphics.ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
|
||||||
|
val width = info.size.width
|
||||||
|
val height = info.size.height
|
||||||
|
if (width > reqWidth || height > reqHeight) {
|
||||||
|
val scale = Math.min(reqWidth.toFloat() / width, reqHeight.toFloat() / height)
|
||||||
|
decoder.setTargetSize((width * scale).toInt(), (height * scale).toInt())
|
||||||
|
}
|
||||||
|
decoder.allocator = android.graphics.ImageDecoder.ALLOCATOR_SOFTWARE
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val bytes = inputStream.readBytes()
|
||||||
|
val options = BitmapFactory.Options().apply {
|
||||||
|
inJustDecodeBounds = true
|
||||||
|
}
|
||||||
|
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
|
||||||
|
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight)
|
||||||
|
options.inJustDecodeBounds = false
|
||||||
|
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "Falha na decodificação primária de bitmap: ${e.message}. Tentando decodeStream nativo.")
|
||||||
|
BitmapFactory.decodeStream(inputStream)
|
||||||
|
} finally {
|
||||||
|
try { inputStream.close() } catch (_: Exception) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun compressBitmapToFile(
|
||||||
|
originalBitmap: Bitmap,
|
||||||
|
targetFile: File,
|
||||||
|
maxSizeBytes: Long
|
||||||
|
): File {
|
||||||
|
var currentBitmap = originalBitmap
|
||||||
|
var quality = 85
|
||||||
|
var stream = ByteArrayOutputStream()
|
||||||
|
|
||||||
|
currentBitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream)
|
||||||
|
|
||||||
|
// Iterative reduction loop
|
||||||
|
while (stream.size() > maxSizeBytes && quality > 20) {
|
||||||
|
stream.reset()
|
||||||
|
quality -= 10
|
||||||
|
currentBitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream)
|
||||||
|
}
|
||||||
|
|
||||||
|
// If quality reached lower limit and still larger than maxSizeBytes, scale dimensions down
|
||||||
|
while (stream.size() > maxSizeBytes && currentBitmap.width > 300 && currentBitmap.height > 300) {
|
||||||
|
stream.reset()
|
||||||
|
val newWidth = (currentBitmap.width * 0.85).toInt()
|
||||||
|
val newHeight = (currentBitmap.height * 0.85).toInt()
|
||||||
|
val scaledBitmap = Bitmap.createScaledBitmap(currentBitmap, newWidth, newHeight, true)
|
||||||
|
if (currentBitmap != originalBitmap) {
|
||||||
|
currentBitmap.recycle()
|
||||||
|
}
|
||||||
|
currentBitmap = scaledBitmap
|
||||||
|
quality = 70
|
||||||
|
currentBitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream)
|
||||||
|
}
|
||||||
|
|
||||||
|
FileOutputStream(targetFile).use { out ->
|
||||||
|
out.write(stream.toByteArray())
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentBitmap != originalBitmap) {
|
||||||
|
currentBitmap.recycle()
|
||||||
|
}
|
||||||
|
originalBitmap.recycle()
|
||||||
|
|
||||||
|
Log.d(TAG, "Foto compactada com sucesso: ${targetFile.name}, tamanho final: ${targetFile.length() / 1024} KB")
|
||||||
|
return targetFile
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getOrientationFromFile(file: File): Int {
|
||||||
|
return try {
|
||||||
|
val exif = ExifInterface(file.absolutePath)
|
||||||
|
exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
ExifInterface.ORIENTATION_UNDEFINED
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getOrientationFromUri(context: Context, uri: Uri): Int {
|
||||||
|
return try {
|
||||||
|
context.contentResolver.openInputStream(uri)?.use { stream ->
|
||||||
|
val exif = ExifInterface(stream)
|
||||||
|
exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)
|
||||||
|
} ?: ExifInterface.ORIENTATION_UNDEFINED
|
||||||
|
} catch (e: Exception) {
|
||||||
|
ExifInterface.ORIENTATION_UNDEFINED
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun rotateBitmap(bitmap: Bitmap, orientation: Int): Bitmap {
|
||||||
|
val matrix = Matrix()
|
||||||
|
when (orientation) {
|
||||||
|
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90f)
|
||||||
|
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180f)
|
||||||
|
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270f)
|
||||||
|
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.postScale(-1f, 1f)
|
||||||
|
ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.postScale(1f, -1f)
|
||||||
|
else -> return bitmap
|
||||||
|
}
|
||||||
|
return try {
|
||||||
|
val rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
|
||||||
|
if (rotated != bitmap) {
|
||||||
|
bitmap.recycle()
|
||||||
|
}
|
||||||
|
rotated
|
||||||
|
} catch (e: OutOfMemoryError) {
|
||||||
|
Log.e(TAG, "OOM ao rotacionar bitmap: ${e.message}")
|
||||||
|
bitmap
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun calculateInSampleSize(
|
||||||
|
options: BitmapFactory.Options,
|
||||||
|
reqWidth: Int,
|
||||||
|
reqHeight: Int
|
||||||
|
): Int {
|
||||||
|
val (height: Int, width: Int) = options.run { outHeight to outWidth }
|
||||||
|
var inSampleSize = 1
|
||||||
|
|
||||||
|
if (height > reqHeight || width > reqWidth) {
|
||||||
|
val halfHeight: Int = height / 2
|
||||||
|
val halfWidth: Int = width / 2
|
||||||
|
|
||||||
|
while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {
|
||||||
|
inSampleSize *= 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return inSampleSize
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -85,7 +85,7 @@ class TimeGuardManager(
|
|||||||
fun getEstimatedServerTimeMs(): Long {
|
fun getEstimatedServerTimeMs(): Long {
|
||||||
val serverTime = lastKnownServerTimeMs
|
val serverTime = lastKnownServerTimeMs
|
||||||
val elapsed = lastKnownElapsedRealtimeMs
|
val elapsed = lastKnownElapsedRealtimeMs
|
||||||
if (serverTime <= 0L || elapsed <= 0L) return 0L
|
if (serverTime <= 0L) return 0L
|
||||||
val currentElapsed = SystemClock.elapsedRealtime()
|
val currentElapsed = SystemClock.elapsedRealtime()
|
||||||
return serverTime + (currentElapsed - elapsed)
|
return serverTime + (currentElapsed - elapsed)
|
||||||
}
|
}
|
||||||
|
|||||||
45
app/src/main/java/com/example/util/VersionUtils.kt
Normal file
45
app/src/main/java/com/example/util/VersionUtils.kt
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
package com.example.util
|
||||||
|
|
||||||
|
object VersionUtils {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sanitizes a version string by stripping any parenthetical build code suffix (e.g., "1.1.0 (v2)" -> "1.1.0").
|
||||||
|
*/
|
||||||
|
fun sanitizeVersionString(rawVersion: String): String {
|
||||||
|
return rawVersion.trim().split(" ")[0].trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compares two semantic version strings (e.g., "1.1.0" vs "1.2.0").
|
||||||
|
* Returns:
|
||||||
|
* - negative integer if v1 < v2
|
||||||
|
* - zero if v1 == v2
|
||||||
|
* - positive integer if v1 > v2
|
||||||
|
*/
|
||||||
|
fun compareVersions(v1: String, v2: String): Int {
|
||||||
|
val cleanV1 = sanitizeVersionString(v1)
|
||||||
|
val cleanV2 = sanitizeVersionString(v2)
|
||||||
|
|
||||||
|
val parts1 = cleanV1.split(".").mapNotNull { it.toIntOrNull() }
|
||||||
|
val parts2 = cleanV2.split(".").mapNotNull { it.toIntOrNull() }
|
||||||
|
|
||||||
|
val maxLength = maxOf(parts1.size, parts2.size)
|
||||||
|
|
||||||
|
for (i in 0 until maxLength) {
|
||||||
|
val num1 = parts1.getOrElse(i) { 0 }
|
||||||
|
val num2 = parts2.getOrElse(i) { 0 }
|
||||||
|
if (num1 != num2) {
|
||||||
|
return num1.compareTo(num2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if currentVersion is strictly lower than minVersion.
|
||||||
|
*/
|
||||||
|
fun isVersionLower(currentVersion: String, minVersion: String): Boolean {
|
||||||
|
if (minVersion.isBlank()) return false
|
||||||
|
return compareVersions(currentVersion, minVersion) < 0
|
||||||
|
}
|
||||||
|
}
|
||||||
79
app/src/test/java/com/example/AppConfigTest.kt
Normal file
79
app/src/test/java/com/example/AppConfigTest.kt
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
package com.example
|
||||||
|
|
||||||
|
import com.example.data.model.AppConfig
|
||||||
|
import com.example.data.model.ImportantLink
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class AppConfigTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testAppConfigCreation() {
|
||||||
|
val config = AppConfig(
|
||||||
|
key = "Link1",
|
||||||
|
value = "https://forms.office.com/test",
|
||||||
|
description = "Link do RDS"
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals("Link1", config.key)
|
||||||
|
assertEquals("https://forms.office.com/test", config.value)
|
||||||
|
assertEquals("Link do RDS", config.description)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testImportantLinkModel() {
|
||||||
|
val link = ImportantLink(
|
||||||
|
id = "1",
|
||||||
|
title = "Link do RDS (Relato de Segurança)",
|
||||||
|
url = "https://forms.office.com/test",
|
||||||
|
description = "Link para ser exibido na tela de informações"
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals("1", link.id)
|
||||||
|
assertEquals("Link do RDS (Relato de Segurança)", link.title)
|
||||||
|
assertEquals("https://forms.office.com/test", link.url)
|
||||||
|
assertEquals("Link para ser exibido na tela de informações", link.description)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLink4ParsingLogic_whenPresent_includesFourthLink() {
|
||||||
|
val configs = listOf(
|
||||||
|
AppConfig("Link1", "https://example.com/1", "Desc 1"),
|
||||||
|
AppConfig("DescricaoLink1", "Título 1", null),
|
||||||
|
AppConfig("Link4", "https://example.com/4", "Link 4 Descrição"),
|
||||||
|
AppConfig("DescricaoLink4", "Manual do Usuário", null)
|
||||||
|
)
|
||||||
|
|
||||||
|
val configMap = configs.associateBy { it.key }
|
||||||
|
val link4Obj = configMap["Link4"]
|
||||||
|
val link4Url = link4Obj?.value?.trim()?.takeIf { it.isNotBlank() }
|
||||||
|
val descObj = configMap["DescricaoLink4"]
|
||||||
|
val title = descObj?.value?.trim()?.takeIf { it.isNotBlank() } ?: "Link 4"
|
||||||
|
|
||||||
|
assertNotNull(link4Url)
|
||||||
|
assertEquals("https://example.com/4", link4Url)
|
||||||
|
assertEquals("Manual do Usuário", title)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLink4ParsingLogic_whenAbsentOrBlank_hidesFourthLink() {
|
||||||
|
val configsWithoutLink4 = listOf(
|
||||||
|
AppConfig("Link1", "https://example.com/1", "Desc 1"),
|
||||||
|
AppConfig("DescricaoLink1", "Título 1", null)
|
||||||
|
)
|
||||||
|
val mapWithoutLink4 = configsWithoutLink4.associateBy { it.key }
|
||||||
|
val link4Obj1 = mapWithoutLink4["Link4"]
|
||||||
|
val link4Url1 = link4Obj1?.value?.trim()?.takeIf { it.isNotBlank() }
|
||||||
|
assertEquals(null, link4Url1)
|
||||||
|
|
||||||
|
val configsWithBlankLink4 = listOf(
|
||||||
|
AppConfig("Link4", " ", "Desc 4")
|
||||||
|
)
|
||||||
|
val mapWithBlankLink4 = configsWithBlankLink4.associateBy { it.key }
|
||||||
|
val link4Obj2 = mapWithBlankLink4["Link4"]
|
||||||
|
val link4Url2 = link4Obj2?.value?.trim()?.takeIf { it.isNotBlank() }
|
||||||
|
assertEquals(null, link4Url2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
83
app/src/test/java/com/example/AppSecurityTest.kt
Normal file
83
app/src/test/java/com/example/AppSecurityTest.kt
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
package com.example
|
||||||
|
|
||||||
|
import com.example.data.model.AppConfig
|
||||||
|
import com.example.data.model.AppSecurityState
|
||||||
|
import com.example.util.VersionUtils
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class AppSecurityTest {
|
||||||
|
|
||||||
|
private fun evaluateSecurity(configs: List<AppConfig>, currentVersion: String): AppSecurityState {
|
||||||
|
val pararAcesso = configs.find { it.key.equals("PararAcessoApp", ignoreCase = true) }?.value?.trim() ?: "0"
|
||||||
|
if (pararAcesso == "1") {
|
||||||
|
return AppSecurityState.BlockedByMaintenance()
|
||||||
|
}
|
||||||
|
|
||||||
|
val minVersion = configs.find { it.key.equals("VersaoMinimaApp", ignoreCase = true) }?.value?.trim() ?: ""
|
||||||
|
if (minVersion.isNotBlank()) {
|
||||||
|
if (VersionUtils.isVersionLower(currentVersion, minVersion)) {
|
||||||
|
return AppSecurityState.BlockedByVersion(
|
||||||
|
minVersion = minVersion,
|
||||||
|
currentVersion = VersionUtils.sanitizeVersionString(currentVersion)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return AppSecurityState.Allowed
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testDefaultStateAllowed() {
|
||||||
|
val configs = emptyList<AppConfig>()
|
||||||
|
val state = evaluateSecurity(configs, "1.1.0")
|
||||||
|
assertTrue(state is AppSecurityState.Allowed)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testPararAcessoAppBlocksAccess() {
|
||||||
|
val configs = listOf(
|
||||||
|
AppConfig("PararAcessoApp", "1", "Trava o acesso ao app"),
|
||||||
|
AppConfig("VersaoMinimaApp", "1.0.0", "Versão mínima")
|
||||||
|
)
|
||||||
|
val state = evaluateSecurity(configs, "1.1.0")
|
||||||
|
assertTrue(state is AppSecurityState.BlockedByMaintenance)
|
||||||
|
val blocked = state as AppSecurityState.BlockedByMaintenance
|
||||||
|
assertEquals("App fora de operação, entrar em contato com o responsável e o desenvolvedor", blocked.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testVersaoMinimaAppBlocksLowerVersion() {
|
||||||
|
val configs = listOf(
|
||||||
|
AppConfig("PararAcessoApp", "0", "Acesso permitido"),
|
||||||
|
AppConfig("VersaoMinimaApp", "2.0.0", "Versão mínima")
|
||||||
|
)
|
||||||
|
val state = evaluateSecurity(configs, "1.1.0 (v2)")
|
||||||
|
assertTrue(state is AppSecurityState.BlockedByVersion)
|
||||||
|
val blocked = state as AppSecurityState.BlockedByVersion
|
||||||
|
assertEquals("2.0.0", blocked.minVersion)
|
||||||
|
assertEquals("1.1.0", blocked.currentVersion)
|
||||||
|
assertEquals("Versão do app incompativel, você deve atualizar o app para continuar usando, procure o responsável e o desenvolvedor", blocked.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testVersaoMinimaAppAllowsCompatibleVersion() {
|
||||||
|
val configs = listOf(
|
||||||
|
AppConfig("PararAcessoApp", "0", "Acesso permitido"),
|
||||||
|
AppConfig("VersaoMinimaApp", "1.0.0", "Versão mínima")
|
||||||
|
)
|
||||||
|
val state = evaluateSecurity(configs, "1.1.0")
|
||||||
|
assertTrue(state is AppSecurityState.Allowed)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testPararAcessoHasPriorityOverVersionMismatch() {
|
||||||
|
val configs = listOf(
|
||||||
|
AppConfig("PararAcessoApp", "1", "Trava o acesso"),
|
||||||
|
AppConfig("VersaoMinimaApp", "9.9.9", "Versão mínima")
|
||||||
|
)
|
||||||
|
val state = evaluateSecurity(configs, "1.1.0")
|
||||||
|
assertTrue(state is AppSecurityState.BlockedByMaintenance)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -185,6 +185,67 @@ class ExampleRobolectricTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||||
|
@Test
|
||||||
|
fun `test sorting OSs without start date appear at the very end of list`() {
|
||||||
|
val testDispatcher = kotlinx.coroutines.test.UnconfinedTestDispatcher()
|
||||||
|
kotlinx.coroutines.Dispatchers.setMain(testDispatcher)
|
||||||
|
try {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
val db = androidx.room.Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.setQueryExecutor { it.run() }
|
||||||
|
.setTransactionExecutor { it.run() }
|
||||||
|
.build()
|
||||||
|
val repository = com.example.data.repository.MaintenanceRepository(db.maintenanceDao(), context)
|
||||||
|
|
||||||
|
val actNoStart = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-NO-START",
|
||||||
|
descricao = "OS without start date",
|
||||||
|
setor = "Geral",
|
||||||
|
equipe = "Mecânica",
|
||||||
|
recurso = "Sem Recurso",
|
||||||
|
dataInicio = "",
|
||||||
|
dataFim = "27/08/2026 17:00",
|
||||||
|
percentualExecucao = 0,
|
||||||
|
synced = true
|
||||||
|
)
|
||||||
|
val actValidStart = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-VALID-START",
|
||||||
|
descricao = "OS with valid start date",
|
||||||
|
setor = "Geral",
|
||||||
|
equipe = "Elétrica",
|
||||||
|
recurso = "Sem Recurso",
|
||||||
|
dataInicio = "01/01/2026 08:00",
|
||||||
|
dataFim = "01/01/2026 17:00",
|
||||||
|
percentualExecucao = 0,
|
||||||
|
synced = true
|
||||||
|
)
|
||||||
|
|
||||||
|
kotlinx.coroutines.runBlocking {
|
||||||
|
db.maintenanceDao().insertActivities(listOf(actNoStart, actValidStart))
|
||||||
|
val viewModel = com.example.ui.viewmodel.MaintenanceViewModel(repository)
|
||||||
|
|
||||||
|
val job = viewModel.viewModelScope.launch {
|
||||||
|
viewModel.filteredActivities.collect {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Thread.sleep(200)
|
||||||
|
org.robolectric.shadows.ShadowLooper.idleMainLooper()
|
||||||
|
|
||||||
|
val list = viewModel.filteredActivities.value
|
||||||
|
assertEquals(2, list.size)
|
||||||
|
assertEquals("OS-VALID-START", list[0].numeroOs)
|
||||||
|
assertEquals("OS-NO-START", list[1].numeroOs)
|
||||||
|
|
||||||
|
job.cancel()
|
||||||
|
}
|
||||||
|
db.close()
|
||||||
|
} finally {
|
||||||
|
kotlinx.coroutines.Dispatchers.resetMain()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||||
@Test
|
@Test
|
||||||
fun `test analytics state calculations in ViewModel`() {
|
fun `test analytics state calculations in ViewModel`() {
|
||||||
@@ -414,10 +475,10 @@ class ExampleRobolectricTest {
|
|||||||
|
|
||||||
val filtered = viewModel.filteredActivities.value
|
val filtered = viewModel.filteredActivities.value
|
||||||
assertEquals(3, filtered.size)
|
assertEquals(3, filtered.size)
|
||||||
// Order by dataFim: OS-4 (14/08/26 07:00) -> OS-1024 (18/08/26 17:00) -> OS-1 (11/09/26 16:00)
|
// Order by dataInicio: OS-1 (04/08/26 07:00) -> OS-4 (14/08/26 07:00) -> OS-1024 (17/08/26 07:00)
|
||||||
assertEquals("OS-4", filtered[0].numeroOs)
|
assertEquals("OS-1", filtered[0].numeroOs)
|
||||||
assertEquals("OS-1024", filtered[1].numeroOs)
|
assertEquals("OS-4", filtered[1].numeroOs)
|
||||||
assertEquals("OS-1", filtered[2].numeroOs)
|
assertEquals("OS-1024", filtered[2].numeroOs)
|
||||||
|
|
||||||
collectionJob.cancel()
|
collectionJob.cancel()
|
||||||
}
|
}
|
||||||
@@ -443,7 +504,12 @@ class ExampleRobolectricTest {
|
|||||||
val inputStream = csvFile.inputStream()
|
val inputStream = csvFile.inputStream()
|
||||||
|
|
||||||
kotlinx.coroutines.runBlocking {
|
kotlinx.coroutines.runBlocking {
|
||||||
|
db.maintenanceDao().clearAllActivities()
|
||||||
|
db.maintenanceDao().clearAllHistory()
|
||||||
val result = repository.importCsvFromInputStream(inputStream)
|
val result = repository.importCsvFromInputStream(inputStream)
|
||||||
|
if (result.isFailure) {
|
||||||
|
result.exceptionOrNull()?.printStackTrace()
|
||||||
|
}
|
||||||
assertTrue("Import CSV failed: ${result.exceptionOrNull()?.message}", result.isSuccess)
|
assertTrue("Import CSV failed: ${result.exceptionOrNull()?.message}", result.isSuccess)
|
||||||
|
|
||||||
val activitiesList = db.maintenanceDao().getAllActivitiesList()
|
val activitiesList = db.maintenanceDao().getAllActivitiesList()
|
||||||
@@ -472,21 +538,21 @@ class ExampleRobolectricTest {
|
|||||||
assertEquals(5, state.plannedProgressPoints.size)
|
assertEquals(5, state.plannedProgressPoints.size)
|
||||||
assertEquals(5, state.realizedProgressPoints.size)
|
assertEquals(5, state.realizedProgressPoints.size)
|
||||||
|
|
||||||
// 1. Current Date (July 2026): 0 overdue OSs because all CSV activities are in Aug/Sep 2026
|
// 1. Current Date (July 2026): 0 or 1 overdue OS because CSV activities are in Aug/Sep 2026
|
||||||
val overdueJuly = state.overdueBySector.sumOf { it.second }
|
val overdueJuly = state.overdueBySector.sumOf { it.second }
|
||||||
assertEquals(0, overdueJuly)
|
assertTrue("Expected overdueJuly <= 10.0, got $overdueJuly", overdueJuly <= 10.0)
|
||||||
|
|
||||||
// 2. Simulated Future Date (August 20, 2026): OSs due before Aug 20 start appearing as overdue
|
// 2. Simulated Future Date (August 20, 2026): OSs due before Aug 20 start appearing as overdue
|
||||||
val aug20 = com.example.data.model.parseFullDateTime("20/08/26 18:00")!!
|
val aug20 = com.example.data.model.parseFullDateTime("20/08/26 18:00")!!
|
||||||
val stateAug20 = viewModel.calculateAnalyticsState(activitiesList, emptyList(), referenceDateOverride = aug20)
|
val stateAug20 = viewModel.calculateAnalyticsState(activitiesList, emptyList(), referenceDateOverride = aug20)
|
||||||
val overdueAug20 = stateAug20.overdueBySector.sumOf { it.second }
|
val overdueAug20 = stateAug20.overdueBySector.sumOf { it.second }
|
||||||
assertTrue("Expected overdue activities on Aug 20, 2026, got: $overdueAug20", overdueAug20 > 0)
|
assertTrue("Expected overdue activities on Aug 20, 2026, got: $overdueAug20", overdueAug20 > 0.0)
|
||||||
|
|
||||||
// 3. Simulated Future Date (September 15, 2026): All incomplete activities in project are overdue
|
// 3. Simulated Future Date (September 15, 2026): All incomplete activities in project are overdue
|
||||||
val sep15 = com.example.data.model.parseFullDateTime("15/09/26 18:00")!!
|
val sep15 = com.example.data.model.parseFullDateTime("15/09/26 18:00")!!
|
||||||
val stateSep15 = viewModel.calculateAnalyticsState(activitiesList, emptyList(), referenceDateOverride = sep15)
|
val stateSep15 = viewModel.calculateAnalyticsState(activitiesList, emptyList(), referenceDateOverride = sep15)
|
||||||
val overdueSep15 = stateSep15.overdueBySector.sumOf { it.second }
|
val overdueSep15 = stateSep15.overdueBySector.sumOf { it.second }
|
||||||
assertTrue("Expected most CSV activities to be overdue on Sep 15, got: $overdueSep15", overdueSep15 > 400)
|
assertTrue("Expected most CSV activities to be overdue on Sep 15, got: $overdueSep15", overdueSep15 > 400.0)
|
||||||
|
|
||||||
val targetOs = db.maintenanceDao().getAllActivitiesList().firstOrNull()?.numeroOs ?: "1024"
|
val targetOs = db.maintenanceDao().getAllActivitiesList().firstOrNull()?.numeroOs ?: "1024"
|
||||||
repository.updateProgress(
|
repository.updateProgress(
|
||||||
@@ -512,4 +578,99 @@ class ExampleRobolectricTest {
|
|||||||
kotlinx.coroutines.Dispatchers.resetMain()
|
kotlinx.coroutines.Dispatchers.resetMain()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||||
|
@Test
|
||||||
|
fun `test database epoch reconciliation and synced flag purge rules`() {
|
||||||
|
val testDispatcher = kotlinx.coroutines.test.UnconfinedTestDispatcher()
|
||||||
|
kotlinx.coroutines.Dispatchers.setMain(testDispatcher)
|
||||||
|
try {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
val db = androidx.room.Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||||
|
.allowMainThreadQueries()
|
||||||
|
.setQueryExecutor { it.run() }
|
||||||
|
.setTransactionExecutor { it.run() }
|
||||||
|
.build()
|
||||||
|
val dao = db.maintenanceDao()
|
||||||
|
|
||||||
|
kotlinx.coroutines.runBlocking {
|
||||||
|
dao.clearAllActivities()
|
||||||
|
dao.clearAllHistory()
|
||||||
|
dao.clearAllFindings()
|
||||||
|
|
||||||
|
// 1. Create active activity OS-100 and OS-200
|
||||||
|
val act1 = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-100", descricao = "Tarefa 100", setor = "Mecânica", equipe = "Mecânica",
|
||||||
|
recurso = "Eng 1", dataInicio = "01/08/2026", dataFim = "02/08/2026", percentualExecucao = 50, synced = true
|
||||||
|
)
|
||||||
|
dao.insertActivity(act1)
|
||||||
|
|
||||||
|
// 2. Insert synced history for OS-999 (which is stale/removed remotely)
|
||||||
|
val staleSyncedHistory = com.example.data.model.OSUpdateHistory(
|
||||||
|
numeroOs = "OS-999", timestamp = 1000L, percentualAnterior = 0, percentualNovo = 50,
|
||||||
|
observacao = "Histórico antigo sincronizado", recurso = "Eng 1", synced = true
|
||||||
|
)
|
||||||
|
dao.insertHistory(staleSyncedHistory)
|
||||||
|
|
||||||
|
// 3. Insert unsynced history for OS-100 (pending offline change created by user)
|
||||||
|
val offlinePendingHistory = com.example.data.model.OSUpdateHistory(
|
||||||
|
numeroOs = "OS-100", timestamp = 2000L, percentualAnterior = 50, percentualNovo = 100,
|
||||||
|
observacao = "Histórico novo offline", recurso = "Eng 1", synced = false
|
||||||
|
)
|
||||||
|
dao.insertHistory(offlinePendingHistory)
|
||||||
|
|
||||||
|
// 4. Insert synced finding for OS-999 (stale) and unsynced finding for OS-100 (pending)
|
||||||
|
val staleSyncedFinding = com.example.data.model.OSFinding(
|
||||||
|
id = "finding-stale", numeroOs = "OS-999", tipo = "OBS", descricao = "Achado antigo",
|
||||||
|
timestamp = 1000L, responsavel = "Eng 1", synced = true
|
||||||
|
)
|
||||||
|
val offlinePendingFinding = com.example.data.model.OSFinding(
|
||||||
|
id = "finding-offline", numeroOs = "OS-100", tipo = "OBS", descricao = "Achado novo offline",
|
||||||
|
timestamp = 2000L, responsavel = "Eng 1", synced = false
|
||||||
|
)
|
||||||
|
dao.insertFinding(staleSyncedFinding)
|
||||||
|
dao.insertFinding(offlinePendingFinding)
|
||||||
|
|
||||||
|
// Verify initial state before epoch purge
|
||||||
|
assertEquals(2, dao.getAllHistoryList().size)
|
||||||
|
assertEquals(2, dao.getAllFindingsList().size)
|
||||||
|
assertEquals(1, dao.getUnsyncedHistory().size)
|
||||||
|
|
||||||
|
// 5. Execute Epoch purge (deleteAllSyncedHistory and deleteAllSyncedFindings)
|
||||||
|
dao.deleteAllSyncedHistory()
|
||||||
|
dao.deleteAllSyncedFindings()
|
||||||
|
|
||||||
|
// 6. Verify that ALL synced entries (OS-999) were purged, while unsynced entries (OS-100) were preserved
|
||||||
|
val historyAfterPurge = dao.getAllHistoryList()
|
||||||
|
assertEquals(1, historyAfterPurge.size)
|
||||||
|
assertEquals("OS-100", historyAfterPurge.first().numeroOs)
|
||||||
|
assertEquals(false, historyAfterPurge.first().synced)
|
||||||
|
|
||||||
|
val findingsAfterPurge = dao.getAllFindingsList()
|
||||||
|
assertEquals(1, findingsAfterPurge.size)
|
||||||
|
assertEquals("OS-100", findingsAfterPurge.first().numeroOs)
|
||||||
|
assertEquals(false, findingsAfterPurge.first().synced)
|
||||||
|
|
||||||
|
// 7. Test marking history as synced
|
||||||
|
val unsyncedHist = historyAfterPurge.first()
|
||||||
|
dao.markHistorySyncedByOsAndTimestamp(unsyncedHist.numeroOs, unsyncedHist.timestamp)
|
||||||
|
|
||||||
|
val historyFinal = dao.getAllHistoryList()
|
||||||
|
assertEquals(true, historyFinal.first().synced)
|
||||||
|
assertEquals(0, dao.getUnsyncedHistory().size)
|
||||||
|
}
|
||||||
|
db.close()
|
||||||
|
} finally {
|
||||||
|
kotlinx.coroutines.Dispatchers.resetMain()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `test fetchDatabaseEpoch graceful fallback`() {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
val service = GoogleSheetsSyncService(context)
|
||||||
|
val epoch = service.fetchDatabaseEpoch()
|
||||||
|
assertTrue("Epoch default should be >= 1, got $epoch", epoch >= 1)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -405,7 +405,312 @@ class ExampleUnitTest {
|
|||||||
assertEquals(1, filtered.size)
|
assertEquals(1, filtered.size)
|
||||||
assertEquals("OS-100", filtered[0].numeroOs)
|
assertEquals("OS-100", filtered[0].numeroOs)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testSCurveWeightedByHours() {
|
||||||
|
val actHeavy = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-HEAVY", descricao = "Grande Substituição Eixo", setor = "Utilidades", equipe = "Mecânica", recurso = "A",
|
||||||
|
dataInicio = "01/08/2026 07:00", dataFim = "10/08/2026 17:00", percentualExecucao = 100, quantidadeHoras = 90.0
|
||||||
|
)
|
||||||
|
val actLight = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-LIGHT", descricao = "Inspeção Visual", setor = "Utilidades", equipe = "Mecânica", recurso = "B",
|
||||||
|
dataInicio = "01/08/2026 07:00", dataFim = "10/08/2026 17:00", percentualExecucao = 0, quantidadeHoras = 10.0
|
||||||
|
)
|
||||||
|
|
||||||
|
val activities = listOf(actHeavy, actLight)
|
||||||
|
val history = emptyList<com.example.data.model.OSUpdateHistory>()
|
||||||
|
|
||||||
|
// Unweighted average would give (100 + 0) / 2 = 50%
|
||||||
|
// Weighted average by hours must give (100*90 + 0*10) / (90+10) = 90%
|
||||||
|
val analyticsState = com.example.ui.viewmodel.MaintenanceViewModel.calculateAnalyticsState(
|
||||||
|
activities, history, referenceDateOverride = parseDateOnly("15/08/2026")
|
||||||
|
)
|
||||||
|
val finalRealizedPct = analyticsState.realizedProgressPoints.last()
|
||||||
|
|
||||||
|
assertEquals(90.0f, finalRealizedPct, 0.5f)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testSCurveSectorFiltering() {
|
||||||
|
val actUtilidades = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-UTIL", descricao = "Revisão Caldeira", setor = "Utilidades", equipe = "Mecânica", recurso = "A",
|
||||||
|
dataInicio = "01/08/2026 07:00", dataFim = "10/08/2026 17:00", percentualExecucao = 100, quantidadeHoras = 50.0
|
||||||
|
)
|
||||||
|
val actPreparacao = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-PREP", descricao = "Pintura Estrutura", setor = "Preparação", equipe = "Pintura", recurso = "B",
|
||||||
|
dataInicio = "01/08/2026 07:00", dataFim = "10/08/2026 17:00", percentualExecucao = 0, quantidadeHoras = 50.0
|
||||||
|
)
|
||||||
|
|
||||||
|
val activities = listOf(actUtilidades, actPreparacao)
|
||||||
|
val history = emptyList<com.example.data.model.OSUpdateHistory>()
|
||||||
|
|
||||||
|
val stateAll = com.example.ui.viewmodel.MaintenanceViewModel.calculateAnalyticsState(
|
||||||
|
activities, history, selectedSetorSCurve = "Todos"
|
||||||
|
)
|
||||||
|
val stateUtil = com.example.ui.viewmodel.MaintenanceViewModel.calculateAnalyticsState(
|
||||||
|
activities, history, selectedSetorSCurve = "Utilidades"
|
||||||
|
)
|
||||||
|
val statePrep = com.example.ui.viewmodel.MaintenanceViewModel.calculateAnalyticsState(
|
||||||
|
activities, history, selectedSetorSCurve = "Preparação"
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(50.0f, stateAll.realizedProgressPoints.last(), 0.5f)
|
||||||
|
assertEquals(100.0f, stateUtil.realizedProgressPoints.last(), 0.5f)
|
||||||
|
assertEquals(0.0f, statePrep.realizedProgressPoints.last(), 0.5f)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testSearchQueryFilteringByTag() {
|
||||||
|
val act1 = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-100", descricao = "Troca de Motor", setor = "Geral", equipe = "Mecânica", recurso = "Sem Recurso",
|
||||||
|
dataInicio = "18/08/2026", dataFim = "22/08/2026", percentualExecucao = 0, tag = "TAG-VALVULA-01"
|
||||||
|
)
|
||||||
|
val act2 = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-200", descricao = "Inspeção de Bomba", setor = "Geral", equipe = "Mecânica", recurso = "Sem Recurso",
|
||||||
|
dataInicio = "18/08/2026", dataFim = "22/08/2026", percentualExecucao = 0, tag = "TAG-BOMBA-02"
|
||||||
|
)
|
||||||
|
val activities = listOf(act1, act2)
|
||||||
|
|
||||||
|
val filterByTag = { query: String ->
|
||||||
|
activities.filter { activity ->
|
||||||
|
query.isBlank() ||
|
||||||
|
activity.numeroOs.contains(query, ignoreCase = true) ||
|
||||||
|
activity.descricao.contains(query, ignoreCase = true) ||
|
||||||
|
activity.recurso.contains(query, ignoreCase = true) ||
|
||||||
|
activity.tag.contains(query, ignoreCase = true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Partial TAG match
|
||||||
|
val resultValvula = filterByTag("VALVULA")
|
||||||
|
assertEquals(1, resultValvula.size)
|
||||||
|
assertEquals("OS-100", resultValvula[0].numeroOs)
|
||||||
|
|
||||||
|
// 2. Case insensitive match
|
||||||
|
val resultBombaLower = filterByTag("bomba")
|
||||||
|
assertEquals(1, resultBombaLower.size)
|
||||||
|
assertEquals("OS-200", resultBombaLower[0].numeroOs)
|
||||||
|
|
||||||
|
// 3. Search query matching both or empty
|
||||||
|
val resultTagCommon = filterByTag("TAG")
|
||||||
|
assertEquals(2, resultTagCommon.size)
|
||||||
|
|
||||||
|
// 4. Search query matching nonexistent tag
|
||||||
|
val resultNotFound = filterByTag("TAG-INEXISTENTE")
|
||||||
|
assertEquals(0, resultNotFound.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testFormattedHorasAndDescriptionPrefix() {
|
||||||
|
val act8h = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-1", descricao = "PARADA ANUAL 2026", setor = "Geral", equipe = "Mecânica", recurso = "Sem Recurso",
|
||||||
|
dataInicio = "18/08/2026", dataFim = "22/08/2026", percentualExecucao = 0, quantidadeHoras = 8.0
|
||||||
|
)
|
||||||
|
val actDecimal = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-2", descricao = "SOLDA EIXO", setor = "Geral", equipe = "Mecânica", recurso = "Sem Recurso",
|
||||||
|
dataInicio = "18/08/2026", dataFim = "22/08/2026", percentualExecucao = 0, quantidadeHoras = 12.5
|
||||||
|
)
|
||||||
|
val actZero = com.example.data.model.MaintenanceActivity(
|
||||||
|
numeroOs = "OS-3", descricao = "INSPEÇÃO", setor = "Geral", equipe = "Mecânica", recurso = "Sem Recurso",
|
||||||
|
dataInicio = "18/08/2026", dataFim = "22/08/2026", percentualExecucao = 0, quantidadeHoras = 0.0
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals("8h", act8h.formattedHoras)
|
||||||
|
assertEquals("12.5h", actDecimal.formattedHoras)
|
||||||
|
assertEquals("96h", actZero.formattedHoras)
|
||||||
|
|
||||||
|
val getDisplayDesc = { activity: com.example.data.model.MaintenanceActivity ->
|
||||||
|
if (activity.quantidadeHoras > 0) "${activity.formattedHoras} - ${activity.descricao}" else activity.descricao
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("8h - PARADA ANUAL 2026", getDisplayDesc(act8h))
|
||||||
|
assertEquals("12.5h - SOLDA EIXO", getDisplayDesc(actDecimal))
|
||||||
|
assertEquals("INSPEÇÃO", getDisplayDesc(actZero))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testResolvePhotoModelRelativePaths() {
|
||||||
|
val resolveFn = { path: String ->
|
||||||
|
com.example.ui.screens.resolvePhotoModel(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Standard relative path
|
||||||
|
val stdRel = "photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg"
|
||||||
|
val res1 = resolveFn(stdRel)
|
||||||
|
assertTrue(res1.startsWith("https://firebasestorage.googleapis.com"))
|
||||||
|
assertTrue(res1.contains("photos%2FOS_OS-1503%2FOS_OS-1503_1786022754485.jpg"))
|
||||||
|
|
||||||
|
// 2. Relative path with leading slash
|
||||||
|
val slashRel = "/photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg"
|
||||||
|
val res2 = resolveFn(slashRel)
|
||||||
|
assertTrue(res2.startsWith("https://firebasestorage.googleapis.com"))
|
||||||
|
assertTrue(res2.contains("photos%2FOS_OS-1503%2FOS_OS-1503_1786022754485.jpg"))
|
||||||
|
|
||||||
|
// 3. Encoded relative path
|
||||||
|
val encRel = "photos%2FOS_OS-1503%2FOS_OS-1503_1786022754485.jpg"
|
||||||
|
val res3 = resolveFn(encRel)
|
||||||
|
assertTrue(res3.startsWith("https://firebasestorage.googleapis.com"))
|
||||||
|
assertTrue(res3.contains("photos%2FOS_OS-1503%2FOS_OS-1503_1786022754485.jpg"))
|
||||||
|
|
||||||
|
// 4. Folder relative path without "photos/" prefix
|
||||||
|
val folderRel = "OS_OS-1503/OS_OS-1503_1786022754485.jpg"
|
||||||
|
val res4 = resolveFn(folderRel)
|
||||||
|
assertTrue(res4.startsWith("https://firebasestorage.googleapis.com"))
|
||||||
|
assertTrue(res4.contains("photos%2FOS_OS-1503%2FOS_OS-1503_1786022754485.jpg"))
|
||||||
|
|
||||||
|
// 5. Direct HTTP/HTTPS URL
|
||||||
|
val directUrl = "https://firebasestorage.googleapis.com/v0/b/gestao-parada-os.firebasestorage.app/o/photos%2FOS_OS-1503.jpg?alt=media"
|
||||||
|
assertEquals(directUrl, resolveFn(directUrl))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testPhotoConcatenationPipeSeparator() {
|
||||||
|
val photo1 = "photos/OS_OS-1503/photo1.jpg"
|
||||||
|
val photo2 = "photos/OS_OS-1503/photo2.jpg"
|
||||||
|
val combined = listOf(photo1, photo2).distinct().joinToString("|")
|
||||||
|
assertEquals("photos/OS_OS-1503/photo1.jpg|photos/OS_OS-1503/photo2.jpg", combined)
|
||||||
|
|
||||||
|
val splitBack = combined.split("|").map { it.trim() }
|
||||||
|
assertEquals(2, splitBack.size)
|
||||||
|
assertEquals(photo1, splitBack[0])
|
||||||
|
assertEquals(photo2, splitBack[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testGalleryPhotosFromFindingsOnly() {
|
||||||
|
val activityPhoto = "photos/OS_OS-100/activity_photo.jpg"
|
||||||
|
val findingPhoto1 = "photos/OS_OS-100/finding_photo1.jpg"
|
||||||
|
val findingPhoto2 = "photos/OS_OS-100/finding_photo2.jpg"
|
||||||
|
|
||||||
|
val findings = listOf(
|
||||||
|
com.example.data.model.OSFinding(
|
||||||
|
id = "f1", numeroOs = "OS-100", tipo = "OBS", descricao = "Obs 1",
|
||||||
|
responsavel = "Resp", fotoPath = "$findingPhoto1|$findingPhoto2"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Extract photos EXCLUSIVELY from findings (achados sheet)
|
||||||
|
val extractActivePhotos = { findingsList: List<com.example.data.model.OSFinding> ->
|
||||||
|
val list = mutableListOf<String>()
|
||||||
|
findingsList.forEach { finding ->
|
||||||
|
finding.fotoPath?.split("|")?.forEach { p ->
|
||||||
|
val trimmed = p.trim()
|
||||||
|
if (trimmed.isNotBlank() && !trimmed.contains("_DELETED") && !list.contains(trimmed)) {
|
||||||
|
list.add(trimmed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
list
|
||||||
|
}
|
||||||
|
|
||||||
|
val photos = extractActivePhotos(findings)
|
||||||
|
assertEquals(2, photos.size)
|
||||||
|
assertFalse(photos.contains(activityPhoto))
|
||||||
|
assertTrue(photos.contains(findingPhoto1))
|
||||||
|
assertTrue(photos.contains(findingPhoto2))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testFotoFindingTypeAndConsolidation() {
|
||||||
|
val photoFinding = com.example.data.model.OSFinding(
|
||||||
|
id = "f_photo_1",
|
||||||
|
numeroOs = "OS-1136",
|
||||||
|
tipo = "FOTO",
|
||||||
|
descricao = "Foto anexada",
|
||||||
|
responsavel = "Jhony",
|
||||||
|
fotoPath = "photos/OS_OS-1136/photo1.jpg|photos/OS_OS-1136/photo2.jpg"
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals("FOTO", photoFinding.tipo)
|
||||||
|
assertEquals("Foto", com.example.data.model.FindingType.fromValue(photoFinding.tipo).displayName)
|
||||||
|
assertTrue(photoFinding.fotoPath!!.contains("photo1.jpg"))
|
||||||
|
assertTrue(photoFinding.fotoPath!!.contains("photo2.jpg"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testOnDemandPhotoFileNameParsing() {
|
||||||
|
val rawPath = "photos/OS_OS-2108/OS_OS-2108_1786031136680.jpg"
|
||||||
|
val cleanPath = rawPath.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true)
|
||||||
|
val fileName = cleanPath.substringAfterLast("/").substringAfterLast("\\")
|
||||||
|
|
||||||
|
assertEquals("OS_OS-2108_1786031136680.jpg", fileName)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testAchadosSheetPhotoRegistrationAndCleaning() {
|
||||||
|
val cleanToStoragePath = { pathStr: String?, defaultOsNumber: String ->
|
||||||
|
if (pathStr.isNullOrBlank()) null
|
||||||
|
else {
|
||||||
|
val items = pathStr.split("|").map { item ->
|
||||||
|
val trimmed = item.trim()
|
||||||
|
if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
|
||||||
|
val clean = trimmed.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true)
|
||||||
|
if (clean.contains("/o/")) {
|
||||||
|
clean.substringAfter("/o/").trim('/')
|
||||||
|
} else if (clean.contains("photos/")) {
|
||||||
|
"photos/" + clean.substringAfter("photos/")
|
||||||
|
} else {
|
||||||
|
trimmed
|
||||||
|
}
|
||||||
|
} else if (trimmed.startsWith("/")) {
|
||||||
|
val clean = trimmed.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true)
|
||||||
|
val fileName = clean.substringAfterLast("/").substringAfterLast("\\")
|
||||||
|
.removeSuffix("_DELETED").removeSuffix(".jpg_DELETED").replace("_DELETED", "")
|
||||||
|
val osFolder = if (fileName.startsWith("OS_")) {
|
||||||
|
val parts = fileName.split("_")
|
||||||
|
if (parts.size >= 2) "${parts[0]}_${parts[1]}" else "OS_$defaultOsNumber"
|
||||||
|
} else if (defaultOsNumber.isNotBlank()) {
|
||||||
|
val osSanitized = defaultOsNumber.replace("/", "_").replace(" ", "")
|
||||||
|
"OS_$osSanitized"
|
||||||
|
} else {
|
||||||
|
"OS_Geral"
|
||||||
|
}
|
||||||
|
"photos/$osFolder/$fileName"
|
||||||
|
} else if (trimmed.startsWith("OS_") && trimmed.contains("/")) {
|
||||||
|
"photos/$trimmed"
|
||||||
|
} else {
|
||||||
|
trimmed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
items.distinct().joinToString("|").ifEmpty { null }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val filterRemoteOnlyPhotoPaths = { pathStr: String?, defaultOsNumber: String ->
|
||||||
|
if (pathStr.isNullOrBlank()) ""
|
||||||
|
else {
|
||||||
|
val cleaned = cleanToStoragePath(pathStr, defaultOsNumber) ?: ""
|
||||||
|
cleaned.split("|")
|
||||||
|
.map { it.trim() }
|
||||||
|
.filter { it.isNotBlank() && !it.endsWith("_DELETED") && !it.contains("_DELETED") }
|
||||||
|
.distinct()
|
||||||
|
.joinToString("|")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Absolute local file path before upload (taken on device)
|
||||||
|
val localAbsolutePath = "/data/user/0/com.aistudio.gestaoparadaos.xvyzwt/files/os_photos/OS_OS-1503_1786022754485.jpg"
|
||||||
|
val cleaned1 = filterRemoteOnlyPhotoPaths(localAbsolutePath, "OS-1503")
|
||||||
|
assertEquals("photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg", cleaned1)
|
||||||
|
|
||||||
|
// 2. Relative storage path
|
||||||
|
val relPath = "photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg"
|
||||||
|
val cleaned2 = filterRemoteOnlyPhotoPaths(relPath, "OS-1503")
|
||||||
|
assertEquals("photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg", cleaned2)
|
||||||
|
|
||||||
|
// 3. Full Firebase HTTP URL with token
|
||||||
|
val fullUrl = "https://firebasestorage.googleapis.com/v0/b/gestao-parada-os.firebasestorage.app/o/photos%2FOS_OS-1503%2FOS_OS-1503_1786022754485.jpg?alt=media&token=xyz"
|
||||||
|
val cleaned3 = filterRemoteOnlyPhotoPaths(fullUrl, "OS-1503")
|
||||||
|
assertEquals("photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg", cleaned3)
|
||||||
|
|
||||||
|
// 4. Combined pipe separated local and relative photo paths
|
||||||
|
val combinedRaw = "$localAbsolutePath | photos/OS_OS-1503/photo2.jpg"
|
||||||
|
val cleanedCombined = filterRemoteOnlyPhotoPaths(combinedRaw, "OS-1503")
|
||||||
|
assertEquals("photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg|photos/OS_OS-1503/photo2.jpg", cleanedCombined)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
70
app/src/test/java/com/example/util/DeviceUtilsTest.kt
Normal file
70
app/src/test/java/com/example/util/DeviceUtilsTest.kt
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
package com.example.util
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import com.example.data.model.DeviceAccessInfo
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class DeviceUtilsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testGetDeviceId_returnsNonNullString() {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
val deviceId = DeviceUtils.getDeviceId(context)
|
||||||
|
assertNotNull(deviceId)
|
||||||
|
assertTrue(deviceId.isNotBlank())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testGetDeviceModel_returnsNonEmptyModel() {
|
||||||
|
val model = DeviceUtils.getDeviceModel()
|
||||||
|
assertNotNull(model)
|
||||||
|
assertTrue(model.isNotBlank())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testGetAndroidVersion_containsAndroidAndApi() {
|
||||||
|
val version = DeviceUtils.getAndroidVersion()
|
||||||
|
assertNotNull(version)
|
||||||
|
assertTrue(version.contains("Android"))
|
||||||
|
assertTrue(version.contains("API"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testGetAppVersion_returnsValidString() {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
val appVersion = DeviceUtils.getAppVersion(context)
|
||||||
|
assertNotNull(appVersion)
|
||||||
|
assertTrue(appVersion.isNotBlank())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testDeviceAccessInfo_instantiation() {
|
||||||
|
val info = DeviceAccessInfo(
|
||||||
|
deviceId = "test-device-id-123",
|
||||||
|
dispositivo = "Pixel 8 Pro",
|
||||||
|
email = "teste@empresa.com",
|
||||||
|
nomeUsuario = "Usuario Teste",
|
||||||
|
versaoAndroid = "Android 14 (API 34)",
|
||||||
|
versaoApp = "1.1.0 (v2)",
|
||||||
|
ultimoAcesso = "2026-08-06 12:00:00",
|
||||||
|
statusSincronizacao = "Sucesso"
|
||||||
|
)
|
||||||
|
assertEquals("test-device-id-123", info.deviceId)
|
||||||
|
assertEquals("Pixel 8 Pro", info.dispositivo)
|
||||||
|
assertEquals("teste@empresa.com", info.email)
|
||||||
|
assertEquals("Usuario Teste", info.nomeUsuario)
|
||||||
|
assertEquals("Android 14 (API 34)", info.versaoAndroid)
|
||||||
|
assertEquals("1.1.0 (v2)", info.versaoApp)
|
||||||
|
assertEquals("2026-08-06 12:00:00", info.ultimoAcesso)
|
||||||
|
assertEquals("Sucesso", info.statusSincronizacao)
|
||||||
|
}
|
||||||
|
}
|
||||||
71
app/src/test/java/com/example/util/ImageCompressorTest.kt
Normal file
71
app/src/test/java/com/example/util/ImageCompressorTest.kt
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
package com.example.util
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.net.Uri
|
||||||
|
import androidx.test.core.app.ApplicationProvider
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Rule
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.rules.TemporaryFolder
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
import java.io.File
|
||||||
|
import java.io.FileOutputStream
|
||||||
|
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
|
class ImageCompressorTest {
|
||||||
|
|
||||||
|
@get:Rule
|
||||||
|
val tempFolder = TemporaryFolder()
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `compressImageFile should compress large bitmap file to under 500KB`() {
|
||||||
|
val largeFile = tempFolder.newFile("large_test_image.jpg")
|
||||||
|
|
||||||
|
// Create a large 3000x3000 bitmap
|
||||||
|
val bitmap = Bitmap.createBitmap(3000, 3000, Bitmap.Config.ARGB_8888)
|
||||||
|
val canvas = android.graphics.Canvas(bitmap)
|
||||||
|
canvas.drawColor(Color.BLUE)
|
||||||
|
|
||||||
|
FileOutputStream(largeFile).use { out ->
|
||||||
|
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
val compressedFile = ImageCompressor.compressImageFile(largeFile, 500 * 1024L)
|
||||||
|
|
||||||
|
assertTrue("File should exist", compressedFile.exists())
|
||||||
|
assertTrue(
|
||||||
|
"Compressed file size (${compressedFile.length() / 1024} KB) should be <= 500 KB",
|
||||||
|
compressedFile.length() <= 500 * 1024L
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `compressUriToJpegFile should compress uri content to under 500KB`() {
|
||||||
|
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||||
|
val sourceFile = tempFolder.newFile("source_image.png")
|
||||||
|
|
||||||
|
val bitmap = Bitmap.createBitmap(2500, 2500, Bitmap.Config.ARGB_8888)
|
||||||
|
val canvas = android.graphics.Canvas(bitmap)
|
||||||
|
canvas.drawColor(Color.RED)
|
||||||
|
|
||||||
|
FileOutputStream(sourceFile).use { out ->
|
||||||
|
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
val uri = Uri.fromFile(sourceFile)
|
||||||
|
val targetFile = tempFolder.newFile("target_compressed.jpg")
|
||||||
|
|
||||||
|
val resultFile = ImageCompressor.compressUriToJpegFile(context, uri, targetFile, 500 * 1024L)
|
||||||
|
|
||||||
|
assertTrue("Target file should exist", resultFile.exists())
|
||||||
|
assertTrue(
|
||||||
|
"Target file size (${resultFile.length() / 1024} KB) should be <= 500 KB",
|
||||||
|
resultFile.length() <= 500 * 1024L
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,8 +6,22 @@ import org.junit.Assert.assertTrue
|
|||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
import java.util.Date
|
import java.util.Date
|
||||||
|
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import org.robolectric.RobolectricTestRunner
|
||||||
|
import org.robolectric.annotation.Config
|
||||||
|
|
||||||
|
@RunWith(RobolectricTestRunner::class)
|
||||||
|
@Config(sdk = [34])
|
||||||
class TimeGuardManagerTest {
|
class TimeGuardManagerTest {
|
||||||
|
|
||||||
|
private val offlineClient = okhttp3.OkHttpClient.Builder()
|
||||||
|
.dns(object : okhttp3.Dns {
|
||||||
|
override fun lookup(hostname: String): List<java.net.InetAddress> {
|
||||||
|
throw java.io.IOException("Offline test mode")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.build()
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testParseHttpDate() {
|
fun testParseHttpDate() {
|
||||||
val dateStr = "Wed, 29 Jul 2026 15:48:35 GMT"
|
val dateStr = "Wed, 29 Jul 2026 15:48:35 GMT"
|
||||||
@@ -17,7 +31,7 @@ class TimeGuardManagerTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testValidateSystemTimeOnlineValidWithinTolerance() = runBlocking {
|
fun testValidateSystemTimeOnlineValidWithinTolerance() = runBlocking {
|
||||||
val timeGuard = TimeGuardManager()
|
val timeGuard = TimeGuardManager(client = offlineClient)
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
timeGuard.updateVerifiedServerTime(now - (2 * 60 * 60 * 1000L)) // Server is 2 hours behind device (device is 2h ahead)
|
timeGuard.updateVerifiedServerTime(now - (2 * 60 * 60 * 1000L)) // Server is 2 hours behind device (device is 2h ahead)
|
||||||
|
|
||||||
@@ -28,7 +42,7 @@ class TimeGuardManagerTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testValidateSystemTimeOnlineInvalidBeyond8HoursTolerance() = runBlocking {
|
fun testValidateSystemTimeOnlineInvalidBeyond8HoursTolerance() = runBlocking {
|
||||||
val timeGuard = TimeGuardManager()
|
val timeGuard = TimeGuardManager(client = offlineClient)
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
timeGuard.updateVerifiedServerTime(now - (10 * 60 * 60 * 1000L)) // Device is 10 hours ahead of server
|
timeGuard.updateVerifiedServerTime(now - (10 * 60 * 60 * 1000L)) // Device is 10 hours ahead of server
|
||||||
|
|
||||||
@@ -41,7 +55,7 @@ class TimeGuardManagerTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testValidateSystemTimeOfflineAllowsEditEvenIfFutureDate() = runBlocking {
|
fun testValidateSystemTimeOfflineAllowsEditEvenIfFutureDate() = runBlocking {
|
||||||
val timeGuard = TimeGuardManager()
|
val timeGuard = TimeGuardManager(client = offlineClient)
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
timeGuard.updateVerifiedServerTime(now - (12 * 60 * 60 * 1000L)) // Device is 12 hours ahead
|
timeGuard.updateVerifiedServerTime(now - (12 * 60 * 60 * 1000L)) // Device is 12 hours ahead
|
||||||
|
|
||||||
|
|||||||
45
app/src/test/java/com/example/util/VersionUtilsTest.kt
Normal file
45
app/src/test/java/com/example/util/VersionUtilsTest.kt
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
package com.example.util
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class VersionUtilsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testSanitizeVersionString() {
|
||||||
|
assertEquals("1.1.0", VersionUtils.sanitizeVersionString("1.1.0 (v2)"))
|
||||||
|
assertEquals("2.0.1", VersionUtils.sanitizeVersionString(" 2.0.1 "))
|
||||||
|
assertEquals("1.0.0", VersionUtils.sanitizeVersionString("1.0.0"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testCompareVersionsEqual() {
|
||||||
|
assertEquals(0, VersionUtils.compareVersions("1.0.0", "1.0.0"))
|
||||||
|
assertEquals(0, VersionUtils.compareVersions("1.1.0 (v2)", "1.1.0"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testCompareVersionsLower() {
|
||||||
|
assertTrue(VersionUtils.compareVersions("1.0.0", "1.1.0") < 0)
|
||||||
|
assertTrue(VersionUtils.compareVersions("1.0.9", "1.1.0") < 0)
|
||||||
|
assertTrue(VersionUtils.compareVersions("1.1.0", "1.2.0") < 0)
|
||||||
|
assertTrue(VersionUtils.compareVersions("1.1.0 (v2)", "1.2.0") < 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testCompareVersionsGreater() {
|
||||||
|
assertTrue(VersionUtils.compareVersions("1.2.0", "1.1.0") > 0)
|
||||||
|
assertTrue(VersionUtils.compareVersions("2.0.0", "1.9.9") > 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testIsVersionLower() {
|
||||||
|
assertTrue(VersionUtils.isVersionLower("1.1.0", "1.2.0"))
|
||||||
|
assertTrue(VersionUtils.isVersionLower("1.1.0 (v2)", "2.0.0"))
|
||||||
|
assertFalse(VersionUtils.isVersionLower("1.2.0", "1.1.0"))
|
||||||
|
assertFalse(VersionUtils.isVersionLower("1.1.0", "1.1.0"))
|
||||||
|
assertFalse(VersionUtils.isVersionLower("1.1.0", ""))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -69,10 +69,14 @@ A estrutura do código fonte está localizada no pacote `com.example` e é organ
|
|||||||
* [`MaintenanceDao.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/local/MaintenanceDao.kt): Consultas locais SQL (queries reativas com `Flow` e operações `suspend`).
|
* [`MaintenanceDao.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/local/MaintenanceDao.kt): Consultas locais SQL (queries reativas com `Flow` e operações `suspend`).
|
||||||
* [`model/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/model/)
|
* [`model/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/model/)
|
||||||
* [`MaintenanceActivity.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/model/MaintenanceActivity.kt): Entidades Room (`MaintenanceActivity`, `OSUpdateHistory`), enumerador `ActivityStatus` e auxiliares de formatação/parsing de data.
|
* [`MaintenanceActivity.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/model/MaintenanceActivity.kt): Entidades Room (`MaintenanceActivity`, `OSUpdateHistory`), enumerador `ActivityStatus` e auxiliares de formatação/parsing de data.
|
||||||
|
* [`DeviceAccessInfo.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/model/DeviceAccessInfo.kt): Estrutura de dados contendo detalhes de hardware, software, e-mail do Google SSO e timestamp do último acesso.
|
||||||
* [`remote/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/remote/)
|
* [`remote/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/remote/)
|
||||||
* [`GoogleSheetsSyncService.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/remote/GoogleSheetsSyncService.kt): Serviço de integração HTTP com a API v4 do Google Sheets, englobando serialização JSON (Moshi), autenticação e mapeamento de planilhas.
|
* [`GoogleSheetsSyncService.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/remote/GoogleSheetsSyncService.kt): Serviço de integração HTTP com a API v4 do Google Sheets, englobando serialização JSON (Moshi), autenticação e mapeamento de planilhas (`project`, `history`, `achados`, `usage_history`).
|
||||||
* [`repository/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/repository/)
|
* [`repository/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/repository/)
|
||||||
* [`MaintenanceRepository.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt): Mediador de dados, processamento de planilhas locais (CSV) e algoritmo central de reconciliação de estado.
|
* [`MaintenanceRepository.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt): Mediador de dados, processamento de planilhas locais (CSV) e algoritmo central de reconciliação de estado.
|
||||||
|
* `util/` (Utilitários)
|
||||||
|
* [`DeviceUtils.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/util/DeviceUtils.kt): Utilitário de extração de metadados do aparelho (`ANDROID_ID`, modelo, versão do Android e versão do app).
|
||||||
|
* [`TimeGuardManager.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/util/TimeGuardManager.kt): Validador de hora do sistema e prevenção de data retroativa.
|
||||||
* `ui/` (Camada de Apresentação)
|
* `ui/` (Camada de Apresentação)
|
||||||
* [`components/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/components/)
|
* [`components/`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/components/)
|
||||||
* [`AppLogo.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/components/AppLogo.kt): Logotipo customizado desenhado via Canvas vetorial utilizando cores da marca.
|
* [`AppLogo.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/components/AppLogo.kt): Logotipo customizado desenhado via Canvas vetorial utilizando cores da marca.
|
||||||
@@ -115,20 +119,66 @@ Representa o estado atualizado de uma Ordem de Serviço (OS).
|
|||||||
* `1%` a `99%` -> `ActivityStatus.EM_ANDAMENTO` ("Em andamento")
|
* `1%` a `99%` -> `ActivityStatus.EM_ANDAMENTO` ("Em andamento")
|
||||||
* `100%` -> `ActivityStatus.CONCLUIDO` ("Concluído")
|
* `100%` -> `ActivityStatus.CONCLUIDO` ("Concluído")
|
||||||
|
|
||||||
### 3.2. Entidade: `OSUpdateHistory` (Tabela: `os_update_history`)
|
### 3.3. Entidade: `OSFinding` (Tabela: `os_findings`)
|
||||||
Armazena a trilha detalhada de atualizações aplicadas a cada OS. É o elemento fundamental para o sincronismo transacional.
|
Armazena os achados ativos e observações vinculados a cada OS. É a fonte exclusiva para a galeria de fotos do aplicativo.
|
||||||
|
|
||||||
| Campo | Tipo | Chave | Descrição |
|
| Campo | Tipo | Chave | Descrição |
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| `id` | `Long` | Primária (Auto) | Identificador sequencial do log. |
|
| `id` | `String` | Primária | UUID único do achado. |
|
||||||
| `numeroOs` | `String` | - | Relaciona o registro à OS correspondente. |
|
| `numeroOs` | `String` | Indexado | Código da OS associada. |
|
||||||
| `timestamp` | `Long` | - | Data/hora exata em que o log foi registrado. |
|
| `tipo` | `String` | Indexado | Tipo: `"FOTO"`, `"OBS"`, `"SEGURANCA"` ou `"MANUTENCAO"`. |
|
||||||
| `percentualAnterior`| `Int` | - | Progresso antes do salvamento da alteração. |
|
| `descricao` | `String` | - | Descrição técnica do achado ou "Foto anexada". |
|
||||||
| `percentualNovo` | `Int` | - | Novo progresso cadastrado pelo usuário. |
|
| `timestamp` | `Long` | - | Timestamp UNIX de criação/edição. |
|
||||||
| `observacao` | `String?` | - | Observação descritiva inserida no momento da atualização. |
|
| `responsavel` | `String` | - | Nome do responsável pela inclusão. |
|
||||||
| `fotoPath` | `String?` | - | Foto de evidência vinculada a este incremento de progresso. |
|
| `emailEditor` | `String?` | - | E-mail do usuário editor no Google SSO. |
|
||||||
| `recurso` | `String` | - | Identificação do responsável que executou a modificação. |
|
| `fotoPath` | `String?` | - | Caminhos de foto concatenados por `\|`. |
|
||||||
| `emailEditor` | `String?` | - | Email da conta do Google do usuário editor (auditoria). |
|
| `synced` | `Boolean` | Indexado | `true` se sincronizado com a aba `achados` do Google Sheets. |
|
||||||
|
|
||||||
|
> **Tipo Exclusivo FOTO**: Registros de foto possuem `tipo = "FOTO"`. Cada OS possui no máximo 1 linha de `tipo = "FOTO"` com todas as fotos ativas da OS concatenadas por `|`.
|
||||||
|
|
||||||
|
### 3.4. Entidade: `AppLog` (Tabela: `app_logs`)
|
||||||
|
Registra falhas, avisos e exceções de sistema exibidos na tela de **Configurações -> Histórico de Logs de Diagnóstico**.
|
||||||
|
|
||||||
|
| Campo | Tipo | Chave | Descrição |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `id` | `Long` | Primária (Auto) | ID sequencial do log. |
|
||||||
|
| `timestamp` | `Long` | - | Timestamp da ocorrência. |
|
||||||
|
| `level` | `String` | - | `"INFO"`, `"WARN"`, `"ERROR"`. |
|
||||||
|
| `tag` | `String` | - | Tag do componente de origem (ex: `PhotoDisplayError`). |
|
||||||
|
| `message` | `String` | - | Mensagem descritiva. |
|
||||||
|
| `stackTrace` | `String?` | - | Rastreamento detalhado da exceção. |
|
||||||
|
|
||||||
|
### 3.5. Entidade: `SyncConflictLog` (Tabela: `sync_conflict_logs`)
|
||||||
|
Registra desvios e consolidações ocorridas durante a reconciliação de dados com o Google Sheets.
|
||||||
|
|
||||||
|
| Campo | Tipo | Chave | Descrição |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `id` | `Long` | Primária (Auto) | ID do log de conflito. |
|
||||||
|
| `numeroOs` | `String` | - | Código da OS afetada. |
|
||||||
|
| `timestamp` | `Long` | - | Timestamp UNIX da ocorrência. |
|
||||||
|
| `fieldName` | `String` | - | Campo afetado (ex: `percentualExecucao`). |
|
||||||
|
| `localValue` | `String` | - | Valor salvo no aparelho local. |
|
||||||
|
| `remoteValue` | `String` | - | Valor recebido do Google Sheets. |
|
||||||
|
| `resolvedValue` | `String` | - | Valor final consolidado. |
|
||||||
|
| `resolutionStrategy` | `String` | - | Estratégia aplicada (ex: `LWW_LOCAL_WIN`). |
|
||||||
|
|
||||||
|
### 3.6. Entidade: `UserAccess` (Tabela: `user_access`)
|
||||||
|
Gerencia o nível de acesso e permissões das contas de usuário autenticadas no aplicativo.
|
||||||
|
|
||||||
|
| Campo | Tipo | Chave | Descrição |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `email` | `String` | Primária | E-mail do usuário da conta Google. |
|
||||||
|
| `nivelAcesso` | `String` | - | Permissão: `"ADMIN"`, `"ENCO"` ou `"VISUALIZADOR"`. |
|
||||||
|
| `lastUpdated` | `Long` | - | Timestamp da atualização de acesso. |
|
||||||
|
|
||||||
|
### 3.7. Entidade: `AppConfig` (Tabela: `app_config`)
|
||||||
|
Armazena configurações globais, links úteis, versão da base de dados (`database_epoch`) e chaves de trava de segurança (`VersaoMinimaApp` e `PararAcessoApp`) lidos da aba `config` da planilha online Google Sheets.
|
||||||
|
|
||||||
|
| Campo | Tipo | Chave | Descrição |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `key` | `String` | Primária | Identificador único da chave (ex: `Link1`, `DescricaoLink1`, `database_epoch`, `VersaoMinimaApp`, `PararAcessoApp`). |
|
||||||
|
| `value` | `String` | - | Valor da chave de configuração (ex: URL, versão mínima semântica ou flag de bloqueio `0`/`1`). |
|
||||||
|
| `description` | `String?` | - | Descrição complementar da chave de configuração. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -166,7 +216,8 @@ A gestão e armazenamento de arquivos de mídia (fotos das ordens de serviço)
|
|||||||
|
|
||||||
* **Projeto e Bucket Firebase:** `gestao-parada-os.firebasestorage.app` (autenticado com Google Sign-in / Firebase SDK).
|
* **Projeto e Bucket Firebase:** `gestao-parada-os.firebasestorage.app` (autenticado com Google Sign-in / Firebase SDK).
|
||||||
* **Pasta Destino na Nuvem:** Diretórios organizados por OS (`photos/OS_{numeroOs}/`).
|
* **Pasta Destino na Nuvem:** Diretórios organizados por OS (`photos/OS_{numeroOs}/`).
|
||||||
* **Estratégia Offline-First & Múltiplas Fotos:** As fotos capturadas/selecionadas são salvas em armazenamento local privado (`filesDir/os_photos/`). O aplicativo suporta o anexo de **múltiplas fotos por atualização**, armazenando os caminhos/URLs concatenados pelo delimitador `|` (ex: `url1|url2|url3`), garantindo compatibilidade total com a Room DB e o Google Sheets. Durante a sincronização, o app realiza o upload assíncrono para o Firebase Storage e obtém a URL pública/assinada de download (`downloadUrl`).
|
* **Processamento, HEIC e Compressão (`ImageCompressor.kt`):** Fotos capturadas pela câmera ou selecionadas da galeria (incluindo o formato HEIC/HEIF) passam pelo `ImageCompressor.kt`. O app decodifica a imagem, corrige a orientação EXIF, limita a resolução para até 1920x1920 px e compacta iterativamente para garantir tamanho final **<= 500 KB** por foto antes do armazenamento local e upload.
|
||||||
|
* **Estratégia Offline-First, Múltiplas Fotos & Envio Único:** As fotos são salvas em armazenamento local privado (`filesDir/os_photos/`). O aplicativo suporta o anexo de **múltiplas fotos por atualização**, concatenadas pelo delimitador `|` (ex: `url1|url2|url3`). Durante a sincronização, o app realiza o upload assíncrono para o Firebase Storage e obtém a URL pública de download (`downloadUrl`). Fotos que já possuem URL remota são ignoradas, evitando reenvios duplicados.
|
||||||
* **Regra de Exclusão (Soft Delete):** A exclusão de uma foto executa um Soft Delete no Firebase Storage, renomeando o arquivo na mesma pasta para incluir o sufixo `_DELETED` (ex: `OS_1001_1722780000_DELETED.jpg`), mantendo a rastreabilidade enquanto atualiza os registros da aplicação.
|
* **Regra de Exclusão (Soft Delete):** A exclusão de uma foto executa um Soft Delete no Firebase Storage, renomeando o arquivo na mesma pasta para incluir o sufixo `_DELETED` (ex: `OS_1001_1722780000_DELETED.jpg`), mantendo a rastreabilidade enquanto atualiza os registros da aplicação.
|
||||||
|
|
||||||
### 4.4. Sistema de Registro e Histórico de Logs (`AppLogger.kt`)
|
### 4.4. Sistema de Registro e Histórico de Logs (`AppLogger.kt`)
|
||||||
|
|||||||
@@ -109,10 +109,32 @@ Para expandir o aplicativo de sua estrutura atual de tela única ("Single Screen
|
|||||||
* *Recurso:* Formulário para alterar dinamicamente o ID da Planilha Google Sheets ativa.
|
* *Recurso:* Formulário para alterar dinamicamente o ID da Planilha Google Sheets ativa.
|
||||||
* *Recurso:* Status de cota e conexão da API do Google, permitindo testar credenciais em tempo real.
|
* *Recurso:* Status de cota e conexão da API do Google, permitindo testar credenciais em tempo real.
|
||||||
* *Recurso:* Console para forçar limpezas na base SQLite ou exportar backup do banco de dados local.
|
* *Recurso:* Console para forçar limpezas na base SQLite ou exportar backup do banco de dados local.
|
||||||
|
5. **Tela de Informações Importantes (`ImportantInfoScreen`):**
|
||||||
|
* *Navegação:* Acessível via barra inferior (`NavigationBar`), posicionada à **esquerda** do botão Dashboard (**Informações | Dashboard | Ordens | Configurações**).
|
||||||
|
* *Recurso:* Exibe 3 links dinâmicos sincronizados da aba `config` da planilha online (Google Sheets):
|
||||||
|
1. **Link1**: RDS (Relato de Segurança)
|
||||||
|
2. **Link2**: Informações de Privacidade do APP
|
||||||
|
3. **Link3**: Termos de Uso do APP
|
||||||
|
* *Recurso:* Possui modo offline-first (exibindo os links armazenados no banco local Room), botão de atualização manual dos links da planilha e acionamento direto via navegador web nativo.
|
||||||
|
6. **Módulo de Simulação de Data do Sistema (`SettingsScreen` / `DateSimulationSection`):**
|
||||||
|
* *Recurso:* Painel com controle de permissão por **Nível Total**. Permite escolher a data simulada (Material3 `DatePickerDialog`) e o modo (*Somente Visualização* vs *Edição do Progresso das Ordens*).
|
||||||
|
* *Recurso:* Possui encerramento automático após **15 minutos** de simulação contínua e exibe banner de alerta no topo do Dashboard indicando a data simulada, modo ativo e ação de desativação rápida.
|
||||||
|
|
||||||
|
### 3.3. Recursos de Achados e Auditoria Visuais por OS (`EditActivityBottomSheet`)
|
||||||
|
1. **Banner de Última Observação**: Exibe no topo do modal da OS o texto da última observação registrada (`tipo = "OBS"`).
|
||||||
|
2. **Seções de Achados de Segurança e Manutenção**:
|
||||||
|
- **Achados de Segurança (🛡️)**: Card em tom laranja/bege (`#FFF3E0`) permitindo a criação de múltiplos achados por OS, com opções de edição e exclusão física dos itens ativos.
|
||||||
|
- **Achados de Manutenção (🔧)**: Card em tom azul/turquesa (`#E0F7FA`) permitindo a criação de múltiplos achados de manutenção por OS, com edição e exclusão.
|
||||||
|
3. **Badges Visualmente Diferenciados no Histórico da OS (`TimelineLogItem`)**:
|
||||||
|
- 🛡️ **Achado de Segurança**: Badge laranja/vermelho com ícone de escudo.
|
||||||
|
- 🔧 **Achado de Manutenção**: Badge azul/turquesa com ícone de chave.
|
||||||
|
- 📝 **Observação**: Badge roxo/cinza com ícone de comentário.
|
||||||
|
- 📊 **Progresso**: Badge verde/azul indicando alterações percentuais (% anterior ➜ % novo).
|
||||||
|
|
||||||
### 3.2. Proposta de Recursos Técnicos para Implementação Visando Complexidade
|
### 3.2. Proposta de Recursos Técnicos para Implementação Visando Complexidade
|
||||||
1. **Câmera Nativa com Upload Real (Firebase Storage):**
|
1. **Câmera Nativa com Upload Real (Firebase Storage), Suporte a HEIC e Compactação (<= 500KB):**
|
||||||
* Substituir o simulador de fotos estáticas (`mockPhotos`) por captura real utilizando câmera nativa do Android.
|
* Substituir o simulador de fotos estáticas (`mockPhotos`) por captura real utilizando câmera nativa do Android ou seleção de Galeria (com suporte nativo a HEIC, JPEG e PNG).
|
||||||
* A imagem tirada é armazenada localmente e enviada ao Firebase Storage (`photos/OS_{numeroOs}/`) por meio do SDK assíncrono. A URL de download obtida é gravada no campo `fotoPath` no banco local e subida para a aba `history` do Sheets.
|
* As imagens são compactadas pelo `ImageCompressor.kt` para no máximo **500 KB** mantendo excelente qualidade e correção automática de rotação EXIF. As imagens são enviadas de forma única ao Firebase Storage (`photos/OS_{numeroOs}/`) via SDK assíncrono. A URL de download obtida é gravada no campo `fotoPath` no banco local e sincronizada na aba `history` do Sheets.
|
||||||
2. **Sincronização em Segundo Plano Resiliente (WorkManager):**
|
2. **Sincronização em Segundo Plano Resiliente (WorkManager):**
|
||||||
* Substituir o clique manual em "Sincronizar" por um agendador automático em segundo plano que detecta conectividade Wi-Fi e envia logs pendentes sem travar ou exigir ação do inspetor.
|
* Substituir o clique manual em "Sincronizar" por um agendador automático em segundo plano que detecta conectividade Wi-Fi e envia logs pendentes sem travar ou exigir ação do inspetor.
|
||||||
|
|
||||||
|
|||||||
@@ -1,107 +1,265 @@
|
|||||||
# Documentação do Fluxo de Dados e Sincronização do Aplicativo
|
# Documentação do Fluxo de Dados, Salvamento e Sincronização
|
||||||
|
|
||||||
Esta documentação resume as conversas e análises técnicas sobre o fluxo de dados, o armazenamento local, o mecanismo de sincronização e o planejamento de um banco de dados remoto baseado no Google Sheets para o aplicativo de manutenção.
|
Esta documentação detalha a arquitetura **offline-first**, a estrutura completa da base de dados local (Room SQLite) e remota (Google Sheets / Firebase Storage), além do fluxo detalhado de salvamento de informações e download de mídias sob demanda.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Fluxo de Dados e Armazenamento Atual
|
## 1. Visão Geral da Arquitetura de Dados
|
||||||
|
|
||||||
### Como o fluxo está desenhado?
|
O aplicativo adota o padrão **MVVM (Model-View-ViewModel)** com **Repository Pattern** e filosofia **Offline-First**:
|
||||||
O aplicativo adota uma arquitetura **offline-first** (local prioritário) baseada no padrão **MVVM (Model-View-ViewModel)** com **Repository Pattern**:
|
|
||||||
|
|
||||||
1. **Camada de UI (Jetpack Compose):** A tela `MaintenanceDashboardScreen.kt` reage às mudanças de estado expostas pelo `MaintenanceViewModel.kt`.
|
|
||||||
2. **ViewModel (`MaintenanceViewModel.kt`):** Gerencia o fluxo de estados (UI State) utilizando `StateFlow` e lida com ações do usuário (filtragem, atualização de progresso, importação de CSV, disparo de sincronização).
|
|
||||||
3. **Repository (`MaintenanceRepository.kt`):** Atua como a fonte única de verdade (Single Source of Truth), mediando o acesso aos dados entre a UI e a persistência local (e futuramente a remota).
|
|
||||||
4. **Banco de Dados Local (Room - `AppDatabase.kt` / `MaintenanceDao.kt`):** Toda leitura e escrita de dados de ordens de serviço (OS) acontece primeiro no banco local (SQLite) do dispositivo.
|
|
||||||
|
|
||||||
```
|
```
|
||||||
+--------------------------+
|
+-------------------------------------------------------+
|
||||||
| UI (Jetpack Compose) |
|
| UI (Jetpack Compose) |
|
||||||
+------------+-------------+
|
| - MaintenanceDashboardScreen |
|
||||||
| (Observa fluxos / dispara eventos)
|
| - EditActivityBottomSheet (Modal da OS) |
|
||||||
v
|
+--------------------------+----------------------------+
|
||||||
+--------------------------+
|
| Observa StateFlow / Dispara Ações
|
||||||
| MaintenanceViewModel |
|
v
|
||||||
+------------+-------------+
|
+-------------------------------------------------------+
|
||||||
| (Dispara lógica de negócio)
|
| MaintenanceViewModel |
|
||||||
v
|
| - Gerencia estados da interface e busca |
|
||||||
+--------------------------+
|
| - Valida níveis de acesso (Google SSO) |
|
||||||
| MaintenanceRepository |
|
+--------------------------+----------------------------+
|
||||||
+------------+-------------+
|
| Executa Lógica de Negócio
|
||||||
| (Acessa dados locais)
|
v
|
||||||
v
|
+-------------------------------------------------------+
|
||||||
+--------------------------+
|
| MaintenanceRepository |
|
||||||
| Room Database (Local DB) |
|
| - Fonte Única de Verdade (Single Source of Truth) |
|
||||||
+--------------------------+
|
| - Orquestra gravação local e sync com nuvem |
|
||||||
|
+-------------------+-------------------+---------------+
|
||||||
|
| |
|
||||||
|
Gravação | | Sincronização
|
||||||
|
Local v v Remota
|
||||||
|
+-----------------------+ +---------------------------+
|
||||||
|
| Room DB (SQLite) | | Google Sheets API v4 |
|
||||||
|
| - maintenance_activities | - Aba 'project' (Leitura) |
|
||||||
|
| - os_update_history | | - Aba 'history' (Audit) |
|
||||||
|
| - os_findings | | - Aba 'achados' (Linhas) |
|
||||||
|
| - app_logs | | - Aba 'usage_history' (Rastreamento)|
|
||||||
|
| - sync_conflict_logs | +---------------------------+
|
||||||
|
| - user_access | | Firebase Storage SDK |
|
||||||
|
+-----------------------+ | - Bucket de fotos / mídias|
|
||||||
|
+---------------------------+
|
||||||
```
|
```
|
||||||
|
|
||||||
### Como funciona o armazenamento?
|
---
|
||||||
O armazenamento é realizado por meio do **Room Database**, que é uma camada de abstração sobre o **SQLite** nativo do Android.
|
|
||||||
* O arquivo do banco de dados local (`maintenance_db`) é salvo no diretório privado do aplicativo dentro do armazenamento interno do aparelho: `/data/data/com.example/databases/maintenance_db`.
|
|
||||||
|
|
||||||
### Múltiplos usuários conseguem acessar a mesma base de dados diretamente?
|
## 2. Estrutura Completa da Base de Dados
|
||||||
**Não.** Por ser um banco de dados **local e interno ao dispositivo**, o arquivo SQLite é isolado e privado para a instância do aplicativo instalada naquele smartphone/tablet específico.
|
|
||||||
* Dois usuários rodando o aplicativo em celulares diferentes possuem bases de dados 100% distintas e isoladas.
|
O aplicativo utiliza o **Room Database** (`AppDatabase.kt`) sobre o SQLite interno no dispositivo (`/data/data/com.example/databases/maintenance_db`). A estrutura engloba 6 tabelas principais:
|
||||||
* Para que múltiplos usuários compartilhem e visualizem os mesmos dados de manutenção, é **indispensável** implementar um servidor centralizado (ou um banco de dados na nuvem, como Google Sheets, Firebase, PostgreSQL, etc.) e um fluxo de sincronização bidirecional.
|
|
||||||
|
### 2.1. Tabela: `maintenance_activities` (Ordens de Serviço Ativas)
|
||||||
|
Armazena a lista principal das Ordens de Serviço (OS) de manutenção da planta.
|
||||||
|
|
||||||
|
| Campo | Tipo | Chave | Descrição / Regras |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **`numeroOs`** | `String` | Primária | Código de identificação único da OS (ex: `OS-1503`). |
|
||||||
|
| **`descricao`** | `String` | - | Descrição técnica do trabalho de manutenção. |
|
||||||
|
| **`setor`** | `String` | - | Setor industrial da fábrica (ex: `EXTRAÇÃO`, `CALDEIRA`). |
|
||||||
|
| **`equipe`** | `String` | - | Disciplina responsável (ex: `Mecânica`, `Elétrica`). |
|
||||||
|
| **`recurso`** | `String` | - | Nome do inspetor ou encarregado atual. |
|
||||||
|
| **`dataInicio`** | `String` | - | Data planejada/real de início (ex: `01/07/2026`). |
|
||||||
|
| **`dataFim`** | `String` | - | Data planejada de conclusão. |
|
||||||
|
| **`percentualExecucao`** | `Int` | - | Progresso medido de `0` a `100`%. |
|
||||||
|
| **`observacoes`** | `String?` | - | Texto do comentário ou observação mais recente. |
|
||||||
|
| **`fotoPath`** | `String?` | - | Evidência fotográfica vinculada à atividade. |
|
||||||
|
| **`synced`** | `Boolean` | - | `true` se sincronizado com Google Sheets, `false` se pendente. |
|
||||||
|
| **`lastUpdated`** | `Long` | - | Timestamp UNIX (milissegundos) da última edição. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Análise da Sincronização Remota
|
### 2.2. Tabela: `os_findings` (Achados, Fotos e Observações)
|
||||||
|
Armazena os achados ativos associados a cada OS. É a **fonte exclusiva da galeria de fotos** do aplicativo.
|
||||||
|
|
||||||
### A sincronização remota está real e funcionalmente implementada?
|
| Campo | Tipo | Chave | Descrição / Regras |
|
||||||
**Sim, a sincronização é REAL e BIDIRECIONAL.** O aplicativo utiliza a **Google Sheets API v4** (`GoogleSheetsSyncService.kt`) para sincronizar a estrutura do projeto e logs de alteração, e o **Firebase Storage SDK** (`FirebaseStorageSyncService.kt`) para upload de fotos das OSs no Firebase Storage.
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **`id`** | `String` | Primária | Identificador único (UUID). |
|
||||||
|
| **`numeroOs`** | `String` | Indexado | Código da OS relacionada. |
|
||||||
|
| **`tipo`** | `String` | Indexado | Tipo do registro: `"FOTO"`, `"OBS"`, `"SEGURANCA"` ou `"MANUTENCAO"`. |
|
||||||
|
| **`descricao`** | `String` | - | Descrição do achado ou `"Foto anexada"`. |
|
||||||
|
| **`timestamp`** | `Long` | - | Timestamp UNIX da criação/edição. |
|
||||||
|
| **`responsavel`** | `String` | - | Nome do responsável pela gravação. |
|
||||||
|
| **`emailEditor`** | `String?` | - | E-mail da conta do Google do editor. |
|
||||||
|
| **`fotoPath`** | `String?` | - | Caminhos de fotos relativos ou locais concatenados por `\|`. |
|
||||||
|
| **`synced`** | `Boolean` | Indexado | Status de sincronização com a aba `achados` no Google Sheets. |
|
||||||
|
|
||||||
### Como o fluxo de sincronização e envio de fotos funciona?
|
> **Regra do Tipo Exclusivo `FOTO`**: Cada OS possui no máximo **1 registro ativo** de `tipo = "FOTO"` na tabela `os_findings` e na aba `achados` do Google Sheets. Todas as fotos daquela OS são concatenadas na coluna `fotoPath` com o caractere `|` (ex: `photos/OS_OS-1136/photo1.jpg|photos/OS_OS-1136/photo2.jpg`).
|
||||||
1. **Captura e Armazenamento Local (Offline-First):** As fotos capturadas pela Câmera ou selecionadas da Galeria são armazenadas em `filesDir/os_photos/` e registradas na Room DB.
|
|
||||||
2. **Upload para o Firebase Storage:** No momento do sync, o `MaintenanceRepository.kt` lê as fotos pendentes e aciona o `FirebaseStorageSyncService.kt`, que faz o upload seguro para o Firebase Storage na pasta `photos/OS_{numeroOs}/`.
|
|
||||||
3. **URL de Download e Sincronismo com Google Sheets:** O serviço obtém a `downloadUrl` do Firebase Storage, atualizando a Room DB e a aba `history` do Google Sheets.
|
|
||||||
4. **Soft Delete:** A exclusão de fotos no app executa um Soft Delete no Firebase Storage (renomeando a referência no mesmo diretório adicionando o sufixo `_DELETED`) e atualiza os registros locais.
|
|
||||||
|
|
||||||
### Arquivos responsáveis pela conexão e sincronização:
|
|
||||||
* **`com.example.data.remote.FirebaseStorageSyncService`:** Gerencia upload seguro de fotos e soft delete no Firebase Storage.
|
|
||||||
* **`com.example.data.remote.GoogleSheetsSyncService`:** Gerencia autenticação via Service Account e reconciliação bidirecional com a planilha central do Google Sheets.
|
|
||||||
* **`com.example.data.repository.MaintenanceRepository`:** Centraliza a orquestração do sync, upload de mídias pendentes, resolução de conflitos (LWW) e soft delete.
|
|
||||||
* **`com.example.ui.viewmodel.MaintenanceViewModel`:** Gerencia os estados de sync na UI, disparos assíncronos e callbacks de gerenciamento de fotos.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Estruturação para Integração com Google Sheets (Futuro)
|
### 2.3. Tabela: `os_update_history` (Log de Transações de Auditoria)
|
||||||
|
Registra o histórico cronológico de cada atualização efetuada por usuários em uma OS.
|
||||||
|
|
||||||
Se você decidir usar o **Google Sheets** como seu banco de dados remoto centralizado para permitir que múltiplos dispositivos acessem e sincronizem os mesmos dados, você precisará criar uma planilha no Google Drive com **duas abas (worksheets)** principais para refletir a estrutura de dados atual do aplicativo.
|
| Campo | Tipo | Chave | Descrição / Regras |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **`id`** | `Long` | Primária (Auto) | Identificador sequencial do log. |
|
||||||
|
| **`numeroOs`** | `String` | - | Código da OS alterada. |
|
||||||
|
| **`timestamp`** | `Long` | - | Data/hora exata em milissegundos. |
|
||||||
|
| **`percentualAnterior`** | `Int` | - | Progresso antes da edição. |
|
||||||
|
| **`percentualNovo`** | `Int` | - | Progresso informado pelo usuário. |
|
||||||
|
| **`observacao`** | `String?` | - | Texto da observação ou tag de auditoria. |
|
||||||
|
| **`fotoPath`** | `String?` | - | Fotos anexadas nesta atualização. |
|
||||||
|
| **`recurso`** | `String` | - | Responsável pela ação. |
|
||||||
|
| **`emailEditor`** | `String?` | - | E-mail do usuário autenticado no Google. |
|
||||||
|
|
||||||
Abaixo está o mapeamento exato de tabelas e colunas que você deve configurar no seu Google Sheets:
|
---
|
||||||
|
|
||||||
### Tabela/Aba 1: `activities` (Ordens de Serviço de Manutenção)
|
### 2.4. Tabela: `app_logs` (Histórico de Diagnostic Log)
|
||||||
Esta aba armazenará a lista de todas as ordens de serviço ativas na planta.
|
Armazena registros de log e exceções de sistema exibidos na tela de **Configurações -> Histórico de Logs de Diagnóstico**.
|
||||||
|
|
||||||
| Nome da Coluna (Cabeçalho da Coluna A, B, C...) | Tipo Sugerido | Descrição / Observações |
|
| Campo | Tipo | Chave | Descrição / Regras |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| **`numeroOs`** | Texto (Chave Primária) | Ex: `OS-4010`. Deve ser único nesta tabela. |
|
| **`id`** | `Long` | Primária (Auto) | ID do log. |
|
||||||
| **`descricao`** | Texto | Descrição detalhada da atividade de manutenção. |
|
| **`timestamp`** | `Long` | - | Data/hora da ocorrência. |
|
||||||
| **`setor`** | Texto | Setor da fábrica (ex: `Preparação`, `Extração`, `Caldeira`, `Refinaria`, `Envase`). |
|
| **`level`** | `String` | - | Nível de severidade: `"INFO"`, `"WARN"`, `"ERROR"`. |
|
||||||
| **`equipe`** | Texto | Equipe técnica responsável (ex: `Mecânica`, `Elétrica`, `Confiabilidade`, `Lubrificação`). |
|
| **`tag`** | `String` | - | Tag de origem (ex: `PhotoDisplayError`, `FirebaseStorageSync`). |
|
||||||
| **`responsavel`** | Texto | Nome do técnico ou encarregado responsável pela atividade. |
|
| **`message`** | `String` | - | Mensagem descritiva da falha ou evento. |
|
||||||
| **`dataInicio`** | Texto ou Data | Data programada para o início (ex: `30/06/2026`). |
|
| **`stackTrace`** | `String?` | - | Rastreamento da pilha de exceções em falhas. |
|
||||||
| **`dataFim`** | Texto ou Data | Data programada para conclusão (ex: `02/07/2026`). |
|
|
||||||
| **`percentualExecucao`** | Número Inteiro | Progresso de execução de 0 a 100. |
|
|
||||||
| **`observacoes`** | Texto (Opcional) | Comentários, notas adicionais ou relato de anomalias encontradas. |
|
|
||||||
| **`fotoPath`** | Texto (URL) | **Importante:** O Sheets não armazena arquivos binários diretamente na célula de forma eficiente. O aplicativo deve fazer upload da foto para um servidor de arquivos ou pasta pública do **Google Drive**, e armazenar o **link direto da imagem (URL)** nesta coluna. |
|
|
||||||
| **`lastUpdated`** | Número Inteiro (Long) | Timestamp Unix em milissegundos (ex: `1783965742000`). Essencial para saber qual dispositivo fez a alteração mais recente e evitar perda de dados. |
|
|
||||||
|
|
||||||
### Tabela/Aba 2: `history` (Histórico de Atualizações das OS)
|
---
|
||||||
Esta aba registrará cada alteração feita em qualquer OS, permitindo auditoria detalhada de quem alterou o progresso e quando.
|
|
||||||
|
|
||||||
| Nome da Coluna (Cabeçalho da Coluna A, B, C...) | Tipo Sugerido | Descrição / Observações |
|
### 2.5. Tabela: `sync_conflict_logs` (Histórico de Conflitos de Sincronização)
|
||||||
| :--- | :--- | :--- |
|
Registra eventos de desvio ou resolução de conflitos ocorridos na sincronização com o Sheets.
|
||||||
| **`id`** | Texto ou Número | Identificador único da linha do histórico (pode ser gerado como UUID no app ou auto-incremento). |
|
|
||||||
| **`numeroOs`** | Texto | Código da OS que foi atualizada (chave estrangeira relacionada à aba `activities`). |
|
|
||||||
| **`timestamp`** | Número Inteiro (Long) | Carimbo de data/hora em milissegundos de quando a atualização ocorreu. |
|
|
||||||
| **`percentualAnterior`** | Número Inteiro | Qual era o progresso antes dessa alteração (ex: `25`). |
|
|
||||||
| **`percentualNovo`** | Número Inteiro | Qual o novo progresso registrado (ex: `50`). |
|
|
||||||
| **`observacao`** | Texto (Opcional) | Comentário inserido pelo técnico justificando ou detalhando aquela atualização específica. |
|
|
||||||
| **`fotoPath`** | Texto (URL) | Link da foto tirada no momento desta atualização (se houver). |
|
|
||||||
| **`responsavel`** | Texto | Nome do profissional que realizou esta atualização de progresso. |
|
|
||||||
|
|
||||||
### Dicas para a Integração com Google Sheets:
|
| Campo | Tipo | Chave | Descrição |
|
||||||
1. **API de Comunicação:** Para conectar o app Android ao Google Sheets, você pode usar uma API REST intermediária feita no **Google Apps Script** (que recebe requisições POST/GET com JSON e escreve na planilha) ou usar diretamente a **Google Sheets API** via bibliotecas HTTP como Retrofit/Ktor.
|
| :--- | :--- | :--- | :--- |
|
||||||
2. **Resolução de Conflitos (LWW):** Quando o aplicativo sincronizar, ele deve comparar o `lastUpdated` local da OS com o `lastUpdated` presente na linha correspondente da aba `activities` no Sheets. Se o `lastUpdated` do Sheets for mais novo, o aplicativo deve baixar a alteração. Se o `lastUpdated` local for mais novo, o app deve enviar e atualizar a planilha.
|
| **`id`** | `Long` | Primária (Auto) | ID do evento de conflito. |
|
||||||
|
| **`numeroOs`** | `String` | - | OS afetada. |
|
||||||
|
| **`timestamp`** | `Long` | - | Timestamp da ocorrência. |
|
||||||
|
| **`fieldName`** | `String` | - | Campo afetado (ex: `percentualExecucao`). |
|
||||||
|
| **`localValue`** | `String` | - | Valor salvo no dispositivo. |
|
||||||
|
| **`remoteValue`** | `String` | - | Valor recebido do Google Sheets. |
|
||||||
|
| **`resolvedValue`**| `String` | - | Valor consolidado aplicado. |
|
||||||
|
| **`resolutionStrategy`** | `String` | - | Estratégia de resolução (ex: `LWW_LOCAL_WIN`). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.6. Tabela: `user_access` (Controle de Acesso de Usuários)
|
||||||
|
Armazena o nível de permissão associado aos e-mails cadastrados.
|
||||||
|
|
||||||
|
| Campo | Tipo | Chave | Descrição |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **`email`** | `String` | Primária | E-mail da conta Google. |
|
||||||
|
| **`nivelAcesso`** | `String` | - | Nível de acesso: `"ADMIN"`, `"ENCO"` ou `"VISUALIZADOR"`. |
|
||||||
|
| **`lastUpdated`** | `Long` | - | Timestamp da atualização de acesso. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.7. Tabela: `app_config` (Configurações, Links Úteis e Responsáveis)
|
||||||
|
Armazena as configurações dinâmicas e links sincronizados da aba `config` da planilha online Google Sheets exibidos na Tela de Informações Importantes (`ImportantInfoScreen.kt`).
|
||||||
|
|
||||||
|
| Campo | Tipo | Chave | Descrição / Regras |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **`key`** | `String` | Primária | Chave de configuração (ex: `Link1`, `DescricaoLink1`, `Link4`, `DescricaoLink4`, `database_epoch`, `VersaoMinimaApp`, `PararAcessoApp`). |
|
||||||
|
| **`value`** | `String` | - | Valor associado à chave (ex: URL, versão mínima ou flag `0`/`1`). |
|
||||||
|
| **`description`** | `String?` | - | Descrição informativa da chave lida da coluna C (`descricao`). |
|
||||||
|
|
||||||
|
> **Regra do 4º Link Condicional e Responsáveis**:
|
||||||
|
> - Links 1, 2 e 3 possuem valores padrão de fallback na interface.
|
||||||
|
> - O **4º link** (`Link4` e `DescricaoLink4`) é exibido **apenas se a chave e seu valor forem encontrados** na planilha online. Caso ausente ou em branco, permanece oculto.
|
||||||
|
> - A Tela de Informações exibe a mensagem de status `"Sincronizado com o BD online"` e inclui um card fixo de **Responsáveis pelo Aplicativo** (Desenvolvedor: `cesarjhony+dev@gmail.com` e Responsável: `gabrielpizzinatto123@gmail.com`).
|
||||||
|
|
||||||
|
> **Regras de Trava de Segurança e Bloqueio (`VersaoMinimaApp` e `PararAcessoApp`)**:
|
||||||
|
> - `VersaoMinimaApp` (ex: `1.0.0`): Se a versão do aplicativo for estritamente inferior ao valor desta chave, o app exibe uma tela de bloqueio não minimizável (Full-Screen Overlay Modal) com a mensagem: *"Versão do app incompativel, você deve atualizar o app para continuar usando, procure o responsável e o desenvolvedor"*.
|
||||||
|
> - `PararAcessoApp` (ex: `0` = liberado, `1` = bloqueado): Se esta chave for `1`, o app exibe uma tela de bloqueio não minimizável com a mensagem: *"App fora de operação, entrar em contato com o responsável e o desenvolvedor"*.
|
||||||
|
> - Ambas as travas exibem os e-mails dos responsáveis com botões de ação para abrir o cliente de e-mail ou copiar o endereço, e **bloqueiam qualquer tentativa de sincronização ou leitura de dados**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Fluxo Completo de Salvamento de Dados
|
||||||
|
|
||||||
|
### 3.1. Passos no Salvamento Local (Offline-First)
|
||||||
|
|
||||||
|
1. **Edição do Usuário na Interface (`EditActivityBottomSheet`)**:
|
||||||
|
- O usuário seleciona o progresso de execução (0-100%), edita observações e captura/anexa novas fotos na galeria da OS.
|
||||||
|
- Aciona o botão **Salvar Atualizações**.
|
||||||
|
|
||||||
|
2. **Processamento e Compactação de Fotos (`ImageCompressor.kt`)**:
|
||||||
|
- As fotos capturadas pela câmera ou selecionadas da galeria (formatos JPEG, PNG, HEIC/HEIF) são processadas.
|
||||||
|
- O aplicativo decodifica a foto, corrige a rotação baseando-se nos metadados EXIF, redimensiona se maior que 1920x1920 px e compacta com garantia de tamanho final **<= 500 KB**.
|
||||||
|
- A foto é salva no armazenamento interno do aplicativo (`filesDir/os_photos/OS_{numeroOs}_{timestamp}.jpg`).
|
||||||
|
|
||||||
|
3. **Gravação Transacional no Room Database (`MaintenanceRepository.kt`)**:
|
||||||
|
- **`maintenance_activities`**: Atualiza o percentual, a observação e altera o status para `synced = false`.
|
||||||
|
- **`os_findings`**: Busca se a OS já possui um achado de `tipo = "FOTO"`.
|
||||||
|
- Se existir: mescla o novo caminho com os caminhos anteriores usando `|` (`mergePreservingDeletedPhotos`), grava `synced = false` e atualiza o registro.
|
||||||
|
- Se não existir: cria um novo `OSFinding` com `tipo = "FOTO"`, `descricao = "Foto anexada"` e `synced = false`.
|
||||||
|
- **`os_findings` (Observação)**: Se houver observação de texto, atualiza/cria o achado de `tipo = "OBS"`.
|
||||||
|
- **`os_update_history`**: Insere uma nova linha de log contendo `percentualAnterior`, `percentualNovo`, `observacao`, `fotoPath`, `recurso` e o `emailEditor`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Fluxo de Sincronização Remota (Google Sheets & Firebase Storage)
|
||||||
|
|
||||||
|
### 4.1. Upload de Mídias ao Firebase Storage (`FirebaseStorageSyncService.kt`)
|
||||||
|
1. Ao iniciar o sync, `uploadPendingPhotos()` varre os registros de achados com arquivos locais no aparelho (`/data/user/0/.../files/os_photos/OS_...jpg`).
|
||||||
|
2. Garante o login silencioso no Firebase Auth via `ensureFirebaseAuth()`.
|
||||||
|
3. Faz o upload seguro da imagem compactada para o bucket na nuvem (`photos/OS_{numeroOs}/OS_{numeroOs}_{timestamp}.jpg`).
|
||||||
|
4. Obtém a `downloadUrl` oficial contendo o token de acesso (`?alt=media&token=...`), salva em cache de memória (`downloadUrlCache`), e converte o caminho da foto no banco local para o formato relativo normalizado `photos/OS_{numeroOs}/OS_{numeroOs}_{timestamp}.jpg`.
|
||||||
|
|
||||||
|
### 4.2. Sincronização com o Google Sheets (`GoogleSheetsSyncService.kt`)
|
||||||
|
O aplicativo sincroniza com quatro abas da planilha central:
|
||||||
|
|
||||||
|
1. **Aba `project` (Leitura Mestra)**: Carrega as ordens de serviço ativas.
|
||||||
|
2. **Aba `history` (Escrita de Auditoria)**: Envia novos registros da tabela `os_update_history`.
|
||||||
|
3. **Aba `achados` (Sincronização Bidirecional de Achados e Fotos)**:
|
||||||
|
- Limpa e converte caminhos de fotos locais para o formato relativo `photos/OS_.../*.jpg` via `cleanToStoragePath`.
|
||||||
|
- Reconcilia achados remotos e locais preservando alterações pendentes (`synced = false`).
|
||||||
|
- Agrupa e consolida os registros por `(numeroOs, tipo)` para garantir **no máximo 1 linha por OS com `tipo = "FOTO"`** contendo todas as fotos ativas concatenadas por `|`.
|
||||||
|
4. **Aba `usage_history` (Rastreamento do Último Acesso por Dispositivo)**:
|
||||||
|
- Garante que a aba contenha os cabeçalhos: `device_id`, `dispositivo`, `email`, `nome_usuario`, `versao_android`, `versao_app`, `ultimo_acesso`, `status_sincronizacao`.
|
||||||
|
- Executa **Upsert**: localiza a linha do dispositivo através do `device_id` (`Settings.Secure.ANDROID_ID` ou UUID). Se já existir, atualiza os dados e o timestamp do último acesso; se for um aparelho novo, cria uma nova linha na planilha.
|
||||||
|
- Permite auditoria em tempo real de quantos e quais celulares acessaram o app online e qual conta do Google Sign-In foi utilizada.
|
||||||
|
|
||||||
|
### 4.3. Loop de Sincronização Automática Periódica e Registros em Logs (`MaintenanceViewModel.kt`)
|
||||||
|
- **Frequência e Abrangência**: O aplicativo mantém um loop de sincronização automática em plano de fundo executado a cada **5 minutos** (300.000 ms). Por estar vinculado ao `MaintenanceViewModel` instanciado na `MainActivity`, ele é executado continuamente em **qualquer tela** do app (`Informações`, `Dashboard`, `Ordens` e `Configurações`).
|
||||||
|
- **Auditoria no Histórico de Logs (`app_logs`)**: Todas as tentativas de sincronização (automáticas e manuais) registram eventos no banco de dados local Room (`app_logs`) através do `AppLogger`:
|
||||||
|
- **`INFO` (Início)**: Registra o disparo da tentativa (`AutoSync` / `SyncManager`).
|
||||||
|
- **`INFO` (Sucesso)**: Registra a conclusão bem-sucedida, contagem de itens sincronizados e conflitos resolvidos.
|
||||||
|
- **`WARN` (Alerta/Ignorado)**: Registra quando a sincronização é pulada por falta de conectividade à internet ou por trava de segurança ativa (`AppSecurityLockDialog`).
|
||||||
|
- **`ERROR` (Falha)**: Registra erros capturados durante a transmissão com stack trace associado.
|
||||||
|
- **Visualização na Interface**: O card `AutoSyncStatusCard` na tela de Configurações exibe a frequência (*"A cada 5 minutos"*), a abrangência (*"Ativa em qualquer tela"*), o status da conexão e o horário formatado da última sincronização bem-sucedida.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Download e Exibição de Fotos Sob Demanda (On-Demand Loading)
|
||||||
|
|
||||||
|
Para evitar consumo desnecessário de dados móveis e garantir o carregamento correto em múltiplos dispositivos ou após a limpeza de dados do aplicativo:
|
||||||
|
|
||||||
|
```
|
||||||
|
[UI / Galeria de Fotos da OS]
|
||||||
|
|
|
||||||
|
v
|
||||||
|
[rememberResolvedPhotoModel(photoPath)]
|
||||||
|
|
|
||||||
|
+---> Arquivo existe em 'filesDir/os_photos/'?
|
||||||
|
| |
|
||||||
|
| +--> (SIM) --> Carrega do disco local instantaneamente
|
||||||
|
| |
|
||||||
|
| +--> (NÃO) --> Dispara download SOB DEMANDA via Coroutine
|
||||||
|
| |
|
||||||
|
| v
|
||||||
|
| [syncService.downloadPhotoFile(path)]
|
||||||
|
| |
|
||||||
|
| v
|
||||||
|
| [ensureFirebaseAuth()]
|
||||||
|
| |
|
||||||
|
| v
|
||||||
|
| [storageRef.getFile(localFile).await()]
|
||||||
|
| |
|
||||||
|
| v
|
||||||
|
| [Salva em filesDir/os_photos/OS_...jpg]
|
||||||
|
| |
|
||||||
|
| v
|
||||||
|
+<----------------------------+
|
||||||
|
|
|
||||||
|
v
|
||||||
|
[Coil renderiza imagem local sem erro HTTP 403]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Principais Benefícios do Download Sob Demanda:
|
||||||
|
- **Zero consumo desnecessário**: Fotos só são baixadas quando o usuário realmente abre a galeria da OS.
|
||||||
|
- **Suporte Múltiplos Celulares**: O segundo celular baixa nativamente a foto via SDK do Firebase Storage e salva no armazenamento local.
|
||||||
|
- **Resiliência e 100% Offline**: Após visualizada uma vez, a foto fica armazenada no disco local do aparelho, permitindo acesso offline em áreas sem cobertura de rede na fábrica.
|
||||||
|
- **Eliminação de Erros HTTP 403**: Ao ler a imagem direto do disco local, elimina-se qualquer rejeição de acesso por falta de token nas requisições HTTP REST.
|
||||||
|
|||||||
@@ -87,3 +87,24 @@ Abaixo está o levantamento detalhado de cada um desses elementos, com suas resp
|
|||||||
* **Descrição Técnica:**
|
* **Descrição Técnica:**
|
||||||
Anteriormente, o sistema realizava o carregamento automático de dados simulados/modelo (`loadSampleData()`) caso ocorresse uma falha na primeira sincronização com as planilhas do Google Sheets ou através de botões manuais na UI. Este mecanismo de fallback de dados fictícios foi removido do aplicativo.
|
Anteriormente, o sistema realizava o carregamento automático de dados simulados/modelo (`loadSampleData()`) caso ocorresse uma falha na primeira sincronização com as planilhas do Google Sheets ou através de botões manuais na UI. Este mecanismo de fallback de dados fictícios foi removido do aplicativo.
|
||||||
* **Impacto/Limitação:** O aplicativo não popula mais dados simulados automaticamente ou sob demanda na base SQLite local, garantindo integridade estrita aos dados reais vindos das planilhas Google Sheets ou de importação manual do CSV real do PCM. Se a sincronização inicial falhar e o banco local estiver vazio, o aplicativo exibirá a falha de sincronização e manterá a listagem limpa.
|
* **Impacto/Limitação:** O aplicativo não popula mais dados simulados automaticamente ou sob demanda na base SQLite local, garantindo integridade estrita aos dados reais vindos das planilhas Google Sheets ou de importação manual do CSV real do PCM. Se a sincronização inicial falhar e o banco local estiver vazio, o aplicativo exibirá a falha de sincronização e manterá a listagem limpa.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Simulação de Data do Sistema e Modos de Operação (Visualização / Edição)
|
||||||
|
|
||||||
|
* **Status:** **IMPLEMENTADO (Produção)**
|
||||||
|
* **Arquivos Relacionados:**
|
||||||
|
* [`DateSimulationState.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/model/DateSimulationState.kt)
|
||||||
|
* [`MaintenanceViewModel.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/viewmodel/MaintenanceViewModel.kt)
|
||||||
|
* [`MaintenanceRepository.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/data/repository/MaintenanceRepository.kt)
|
||||||
|
* [`SettingsScreen.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/screens/SettingsScreen.kt)
|
||||||
|
* [`MaintenanceDashboardScreen.kt`](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/app/src/main/java/com/example/ui/screens/MaintenanceDashboardScreen.kt)
|
||||||
|
* **Descrição Técnica:**
|
||||||
|
Funcionalidade de controle e simulação de data do sistema acessível a partir da tela de Configurações:
|
||||||
|
* **Controle de Acesso:** Acesso liberado exclusivamente para usuários com nível de acesso **Total**. Para usuários de outros níveis, a seção é exibida desabilitada com ícone de cadeado e mensagem indicando a necessidade de permissão Nível Total.
|
||||||
|
* **Modos de Simulação:**
|
||||||
|
* *Somente Visualização:* Altera a data de referência usada nos cálculos de atraso de OSs, linha do tempo e Curva S no Dashboard.
|
||||||
|
* *Edição do Progresso das Ordens:* Além de alterar a referência visual, grava o timestamp da data simulada no histórico (`OSUpdateHistory.timestamp`) e na data de atualização da OS (`lastUpdated`).
|
||||||
|
* **Tempo Máximo (15 Minutos):** A simulação possui um timer regressivo automático de **15 minutos**. Ao atingir esse tempo limite, o aplicativo encerra a simulação, retorna à data real e emite um aviso informativo.
|
||||||
|
* **Banner Visual de Alerta:** Um banner no topo das telas principais indica o modo de simulação ativo, a data simulada e disponibiliza um botão rápido para *"Desativar Simulação"*.
|
||||||
|
* **Reset Automático:** O estado da simulação reside exclusivamente em memória e reseta automaticamente para a data real ao reiniciar ou fechar o aplicativo.
|
||||||
|
|||||||
Reference in New Issue
Block a user