Compare commits
10 Commits
7759186234
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e26b98824 | ||
|
|
1ff582f60a | ||
|
|
7a9a782513 | ||
|
|
2c97b34f0f | ||
|
|
c0dfd700a0 | ||
|
|
aaa5871292 | ||
|
|
8f557b0581 | ||
|
|
4fbebd08de | ||
|
|
09bfc92e1c | ||
|
|
57dff9f819 |
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`.
|
||||||
@@ -7,13 +7,17 @@ Aplicativo Android **offline-first** desenvolvido em Kotlin e Jetpack Compose pa
|
|||||||
## 📚 Documentação Técnica do Projeto
|
## 📚 Documentação Técnica do Projeto
|
||||||
|
|
||||||
- **[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)**:
|
- **[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 6 tabelas do banco de dados local Room (`maintenance_activities`, `os_findings`, `os_update_history`, `app_logs`, `sync_conflict_logs`, `user_access`).
|
- 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`.
|
- Fluxo detalhado de salvamento de progresso e achados com tipo exclusivo `FOTO`.
|
||||||
- Processo de compactação (<= 500KB) e upload para Firebase Storage.
|
- Processo de compactação (<= 500KB) e upload para Firebase Storage.
|
||||||
- Sincronização bidirecional com Google Sheets (abas `project`, `history`, `achados` e `usage_history`).
|
- 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`.
|
- 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.
|
- Carregamento e download de fotos **sob demanda** (On-Demand Loading) para múltiplos celulares sem erros HTTP 403.
|
||||||
|
|
||||||
|
- **[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)**:
|
- **[Arquitetura do Sistema](file:///home/cesarjhony/dev/projects/gestao_de_manutencao/documentacao/arquitetura/arquitetura_do_sistema.md)**:
|
||||||
- Diagramas de arquitetura MVVM + Repository Pattern.
|
- Diagramas de arquitetura MVVM + Repository Pattern.
|
||||||
- Mapeamento de componentes Compose, ViewModel e Room DAO.
|
- Mapeamento de componentes Compose, ViewModel e Room DAO.
|
||||||
|
|||||||
@@ -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"
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ 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.OSFinding
|
||||||
@@ -12,8 +13,8 @@ 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, OSFinding::class],
|
entities = [MaintenanceActivity::class, OSUpdateHistory::class, SyncConflictLog::class, UserAccess::class, AppLog::class, OSFinding::class, AppConfig::class],
|
||||||
version = 8,
|
version = 10,
|
||||||
exportSchema = false
|
exportSchema = false
|
||||||
)
|
)
|
||||||
abstract class AppDatabase : RoomDatabase() {
|
abstract class AppDatabase : RoomDatabase() {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ 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.OSFinding
|
||||||
import com.example.data.model.OSUpdateHistory
|
import com.example.data.model.OSUpdateHistory
|
||||||
@@ -113,5 +114,40 @@ interface MaintenanceDao {
|
|||||||
|
|
||||||
@Query("DELETE FROM os_findings")
|
@Query("DELETE FROM os_findings")
|
||||||
suspend fun clearAllFindings()
|
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()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
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")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -82,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,
|
||||||
@@ -92,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(
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ 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.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
|
||||||
@@ -758,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.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -8,10 +8,15 @@ 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
|
||||||
@@ -34,11 +39,46 @@ 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)
|
||||||
@@ -440,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()
|
||||||
@@ -468,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()
|
||||||
|
|
||||||
@@ -511,9 +598,9 @@ class MaintenanceRepository(
|
|||||||
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 findings (achados) and history log
|
// 6. For each remote activity, determine its current state based on findings (achados) and history log
|
||||||
@@ -574,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 }
|
||||||
@@ -621,11 +708,18 @@ 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
|
// 10. Sync 'achados' sheet with local OSFinding database safely preserving local/uploaded photo paths
|
||||||
@@ -1061,6 +1155,37 @@ class MaintenanceRepository(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sealed interface SyncResult {
|
sealed interface SyncResult {
|
||||||
|
|||||||
@@ -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)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
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)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1303,30 +1303,49 @@ fun FullscreenPhotoViewerDialog(
|
|||||||
IconButton(
|
IconButton(
|
||||||
onClick = {
|
onClick = {
|
||||||
try {
|
try {
|
||||||
if (photoPath.startsWith("/")) {
|
val resolvedModel = resolvePhotoModel(photoPath, context)
|
||||||
val file = java.io.File(photoPath)
|
var targetFile: java.io.File? = null
|
||||||
if (file.exists()) {
|
|
||||||
val uri = androidx.core.content.FileProvider.getUriForFile(
|
if (resolvedModel.startsWith("/")) {
|
||||||
context,
|
val f = java.io.File(resolvedModel)
|
||||||
"${context.packageName}.fileprovider",
|
if (f.exists()) targetFile = f
|
||||||
file
|
}
|
||||||
)
|
if (targetFile == null && photoPath.startsWith("/")) {
|
||||||
val shareIntent = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
|
val f = java.io.File(photoPath)
|
||||||
type = "image/jpeg"
|
if (f.exists()) targetFile = f
|
||||||
putExtra(android.content.Intent.EXTRA_STREAM, uri)
|
}
|
||||||
addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
if (targetFile == null) {
|
||||||
}
|
val cleanPathForName = photoPath.substringBefore("?").substringBefore("#").replace("%2F", "/", ignoreCase = true)
|
||||||
context.startActivity(android.content.Intent.createChooser(shareIntent, "Compartilhar Foto OS"))
|
val fileName = cleanPathForName.substringAfterLast("/").substringAfterLast("\\")
|
||||||
} else {
|
.removeSuffix("_DELETED").removeSuffix(".jpg_DELETED").replace("_DELETED", "")
|
||||||
Toast.makeText(context, "Arquivo local não encontrado", Toast.LENGTH_SHORT).show()
|
if (fileName.isNotBlank()) {
|
||||||
|
val photosDir = java.io.File(context.filesDir, "os_photos")
|
||||||
|
val cachedFile = java.io.File(photosDir, fileName)
|
||||||
|
if (cachedFile.exists()) targetFile = cachedFile
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
|
|
||||||
|
if (targetFile != null && targetFile.exists()) {
|
||||||
|
val uri = androidx.core.content.FileProvider.getUriForFile(
|
||||||
|
context,
|
||||||
|
"${context.packageName}.fileprovider",
|
||||||
|
targetFile
|
||||||
|
)
|
||||||
|
val shareIntent = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
|
||||||
|
type = "image/jpeg"
|
||||||
|
putExtra(android.content.Intent.EXTRA_STREAM, uri)
|
||||||
|
addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||||
|
}
|
||||||
|
context.startActivity(android.content.Intent.createChooser(shareIntent, "Compartilhar Foto OS"))
|
||||||
|
} else if (resolvedModel.startsWith("http://") || resolvedModel.startsWith("https://")) {
|
||||||
val shareIntent = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
|
val shareIntent = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
|
||||||
type = "text/plain"
|
type = "text/plain"
|
||||||
putExtra(android.content.Intent.EXTRA_SUBJECT, "Foto OS $osNumber")
|
putExtra(android.content.Intent.EXTRA_SUBJECT, "Foto OS $osNumber")
|
||||||
putExtra(android.content.Intent.EXTRA_TEXT, photoPath)
|
putExtra(android.content.Intent.EXTRA_TEXT, resolvedModel)
|
||||||
}
|
}
|
||||||
context.startActivity(android.content.Intent.createChooser(shareIntent, "Compartilhar Link da Foto"))
|
context.startActivity(android.content.Intent.createChooser(shareIntent, "Compartilhar Link da Foto"))
|
||||||
|
} else {
|
||||||
|
Toast.makeText(context, "Arquivo da foto não encontrado localmente", Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Toast.makeText(context, "Erro ao compartilhar: ${e.message}", Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, "Erro ao compartilhar: ${e.message}", Toast.LENGTH_SHORT).show()
|
||||||
|
|||||||
@@ -67,6 +67,9 @@ fun SettingsScreen(
|
|||||||
val appLogs by viewModel.appLogsState.collectAsStateWithLifecycle()
|
val appLogs by viewModel.appLogsState.collectAsStateWithLifecycle()
|
||||||
val userAccessLevel by viewModel.userAccessLevel.collectAsStateWithLifecycle()
|
val userAccessLevel by viewModel.userAccessLevel.collectAsStateWithLifecycle()
|
||||||
val simulationConfig by viewModel.simulationConfig.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) {
|
val hasTotalAccess = remember(userAccessLevel) {
|
||||||
userAccessLevel?.trim()?.equals("total", ignoreCase = true) == true
|
userAccessLevel?.trim()?.equals("total", ignoreCase = true) == true
|
||||||
@@ -152,6 +155,14 @@ fun SettingsScreen(
|
|||||||
verticalArrangement = Arrangement.spacedBy(20.dp)
|
verticalArrangement = Arrangement.spacedBy(20.dp)
|
||||||
) {
|
) {
|
||||||
|
|
||||||
|
// Seção: Status da Sincronização Automática
|
||||||
|
AutoSyncStatusCard(
|
||||||
|
autoSyncIntervalMinutes = autoSyncIntervalMinutes,
|
||||||
|
isNetworkConnected = isNetworkConnected,
|
||||||
|
isSyncing = isSyncing,
|
||||||
|
lastSyncTimestamp = lastSyncTimestamp
|
||||||
|
)
|
||||||
|
|
||||||
// Seção: Painel do Administrador
|
// Seção: Painel do Administrador
|
||||||
Column {
|
Column {
|
||||||
Text(
|
Text(
|
||||||
@@ -225,6 +236,21 @@ fun SettingsScreen(
|
|||||||
viewModel.clearDateSimulation()
|
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
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1028,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
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ 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.AnalyticsState
|
||||||
import com.example.data.model.parseDateOnly
|
import com.example.data.model.parseDateOnly
|
||||||
|
import com.example.data.model.AppSecurityState
|
||||||
import com.example.data.model.DateSimulationConfig
|
import com.example.data.model.DateSimulationConfig
|
||||||
import com.example.data.model.DateSimulationMode
|
import com.example.data.model.DateSimulationMode
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
@@ -36,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()
|
||||||
@@ -68,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()
|
||||||
|
|
||||||
@@ -372,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?) {
|
||||||
@@ -433,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 }
|
||||||
}
|
}
|
||||||
@@ -461,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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -747,6 +967,9 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
|||||||
): AnalyticsState = Companion.calculateAnalyticsState(activities, history, referenceDateOverride, selectedSetorSCurve)
|
): AnalyticsState = Companion.calculateAnalyticsState(activities, history, referenceDateOverride, selectedSetorSCurve)
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
private const val AUTO_SYNC_INTERVAL_MINUTES = 5
|
||||||
|
private const val AUTO_SYNC_INTERVAL_MS = AUTO_SYNC_INTERVAL_MINUTES * 60 * 1000L
|
||||||
|
|
||||||
fun calculateAnalyticsState(
|
fun calculateAnalyticsState(
|
||||||
activities: List<MaintenanceActivity>,
|
activities: List<MaintenanceActivity>,
|
||||||
history: List<OSUpdateHistory>,
|
history: List<OSUpdateHistory>,
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ object DeviceUtils {
|
|||||||
fun getAppVersion(context: Context): String {
|
fun getAppVersion(context: Context): String {
|
||||||
return try {
|
return try {
|
||||||
val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
|
val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
|
||||||
val versionName = packageInfo.versionName ?: "1.0.0"
|
val versionName = packageInfo.versionName ?: "1.4.0"
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
val versionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
val versionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||||
packageInfo.longVersionCode
|
packageInfo.longVersionCode
|
||||||
@@ -55,7 +55,7 @@ object DeviceUtils {
|
|||||||
}
|
}
|
||||||
"$versionName (v$versionCode)"
|
"$versionName (v$versionCode)"
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
"1.0.0"
|
"1.4.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -578,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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -689,7 +689,7 @@ class ExampleUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 1. Absolute local file path before upload (taken on device)
|
// 1. Absolute local file path before upload (taken on device)
|
||||||
val localAbsolutePath = "/data/user/0/com.aistudio.cargillparadaos.xvyzwt/files/os_photos/OS_OS-1503_1786022754485.jpg"
|
val localAbsolutePath = "/data/user/0/com.aistudio.gestaoparadaos.xvyzwt/files/os_photos/OS_OS-1503_1786022754485.jpg"
|
||||||
val cleaned1 = filterRemoteOnlyPhotoPaths(localAbsolutePath, "OS-1503")
|
val cleaned1 = filterRemoteOnlyPhotoPaths(localAbsolutePath, "OS-1503")
|
||||||
assertEquals("photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg", cleaned1)
|
assertEquals("photos/OS_OS-1503/OS_OS-1503_1786022754485.jpg", cleaned1)
|
||||||
|
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ class DeviceUtilsTest {
|
|||||||
email = "teste@empresa.com",
|
email = "teste@empresa.com",
|
||||||
nomeUsuario = "Usuario Teste",
|
nomeUsuario = "Usuario Teste",
|
||||||
versaoAndroid = "Android 14 (API 34)",
|
versaoAndroid = "Android 14 (API 34)",
|
||||||
versaoApp = "1.0.0 (v1)",
|
versaoApp = "1.1.0 (v2)",
|
||||||
ultimoAcesso = "2026-08-06 12:00:00",
|
ultimoAcesso = "2026-08-06 12:00:00",
|
||||||
statusSincronizacao = "Sucesso"
|
statusSincronizacao = "Sucesso"
|
||||||
)
|
)
|
||||||
@@ -63,7 +63,7 @@ class DeviceUtilsTest {
|
|||||||
assertEquals("teste@empresa.com", info.email)
|
assertEquals("teste@empresa.com", info.email)
|
||||||
assertEquals("Usuario Teste", info.nomeUsuario)
|
assertEquals("Usuario Teste", info.nomeUsuario)
|
||||||
assertEquals("Android 14 (API 34)", info.versaoAndroid)
|
assertEquals("Android 14 (API 34)", info.versaoAndroid)
|
||||||
assertEquals("1.0.0 (v1)", info.versaoApp)
|
assertEquals("1.1.0 (v2)", info.versaoApp)
|
||||||
assertEquals("2026-08-06 12:00:00", info.ultimoAcesso)
|
assertEquals("2026-08-06 12:00:00", info.ultimoAcesso)
|
||||||
assertEquals("Sucesso", info.statusSincronizacao)
|
assertEquals("Sucesso", info.statusSincronizacao)
|
||||||
}
|
}
|
||||||
|
|||||||
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", ""))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -171,6 +171,15 @@ Gerencia o nível de acesso e permissões das contas de usuário autenticadas no
|
|||||||
| `nivelAcesso` | `String` | - | Permissão: `"ADMIN"`, `"ENCO"` ou `"VISUALIZADOR"`. |
|
| `nivelAcesso` | `String` | - | Permissão: `"ADMIN"`, `"ENCO"` ou `"VISUALIZADOR"`. |
|
||||||
| `lastUpdated` | `Long` | - | Timestamp da atualização de acesso. |
|
| `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. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Integração Remota (Google Sheets API v4)
|
## 4. Integração Remota (Google Sheets API v4)
|
||||||
|
|||||||
@@ -109,7 +109,14 @@ 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. **Módulo de Simulação de Data do Sistema (`SettingsScreen` / `DateSimulationSection`):**
|
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:* 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.
|
* *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.
|
||||||
|
|
||||||
|
|||||||
@@ -140,9 +140,30 @@ Armazena o nível de permissão associado aos e-mails cadastrados.
|
|||||||
|
|
||||||
| Campo | Tipo | Chave | Descrição |
|
| Campo | Tipo | Chave | Descrição |
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| **`email`** | `String` | Primária | E-mail do usuário da conta Google. |
|
| **`email`** | `String` | Primária | E-mail da conta Google. |
|
||||||
| **`nivelAcesso`** | `String` | - | Permissão: `"ADMIN"`, `"ENCO"` (Encarregado) ou `"VISUALIZADOR"`. |
|
| **`nivelAcesso`** | `String` | - | Nível de acesso: `"ADMIN"`, `"ENCO"` ou `"VISUALIZADOR"`. |
|
||||||
| **`lastUpdated`** | `Long` | - | Data de atualização da regra. |
|
| **`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**.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -191,6 +212,15 @@ O aplicativo sincroniza com quatro abas da planilha central:
|
|||||||
- 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.
|
- 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.
|
- 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)
|
## 5. Download e Exibição de Fotos Sob Demanda (On-Demand Loading)
|
||||||
|
|||||||
Reference in New Issue
Block a user