Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c7eff3f93 | ||
|
|
7e87306c9d | ||
|
|
88906e827b | ||
|
|
2aa4fd21b1 | ||
|
|
3089dd3724 | ||
|
|
d412399d13 | ||
|
|
c14582e92c | ||
|
|
c10248be2c | ||
|
|
7217c11e8b | ||
|
|
95012cf373 | ||
|
|
fc8c3ba7ef | ||
|
|
95c5f4d0ca | ||
|
|
ca36140255 | ||
|
|
ed3c2c295a | ||
|
|
ea46be666f | ||
|
|
147e26b887 | ||
|
|
9d0ca7ebd8 | ||
|
|
f23f29b546 | ||
|
|
c2c917e440 | ||
|
|
51f476ce3e | ||
|
|
0a1c382254 | ||
|
|
e3231c5d04 |
@@ -0,0 +1,11 @@
|
||||
# F6.4 · Android Campo Moderno
|
||||
|
||||
Criterios de aceptación:
|
||||
|
||||
- el buscador de Instalación padre consulta mientras se escribe y cada resultado se puede seleccionar directamente;
|
||||
- la selección de Instalación abre la clasificación compatible de Subinstalación;
|
||||
- Actas utiliza un read-model móvil desacoplado del módulo documental de oficina;
|
||||
- la APK conserva GPS + foto antes de habilitar Hallazgos sobre Inventario nacido en campo;
|
||||
- el lifecycle Acta DRAFT → LOCKED → SEALED no cambia;
|
||||
- la interfaz de campo usa el tema DH moderno y mantiene acceso claro a Actas, Inventario y Hallazgos;
|
||||
- Android lint/tests/debug/release, API tests/build, WEB build y Docker contract deben quedar verdes.
|
||||
+31
-13
@@ -1,17 +1,41 @@
|
||||
# DH Inspección Android · release F6.1
|
||||
# DH Inspección Android · release Campo Moderno 0.18.0
|
||||
|
||||
## Candidata vigente
|
||||
|
||||
- Fase funcional: **F6.1**.
|
||||
- `versionName`: **0.15.1**.
|
||||
- `versionCode`: **23**.
|
||||
- Fase funcional: **Campo Moderno / UX dinámica de Inventario y Actas**.
|
||||
- `versionName`: **0.18.0**.
|
||||
- `versionCode`: **27**.
|
||||
- Application ID release: `com.korexlabs.dhinspeccion`.
|
||||
- Application ID debug/QA: `com.korexlabs.dhinspeccion.debug`.
|
||||
- API: `https://dhv2.korexlabs.com/api/v3/`.
|
||||
- Launcher de presentación: adaptación vectorial local inspirada en el escudo institucional publicado por Gobierno de Mendoza en `mendoza.gov.ar`, para reemplazar el ícono genérico del sistema.
|
||||
|
||||
La variante debug es independiente de la app productiva y puede instalarse para QA/presentación sin sobrescribir una instalación release histórica.
|
||||
|
||||
## Novedades de campo 0.18.0
|
||||
|
||||
La APK adopta una capa visual Material 3 propia de DH: superficies más limpias, jerarquía visual más clara, botones y estados más legibles, tarjetas con menor ruido y una navegación consistente entre Inspección, Actas e Inventario.
|
||||
|
||||
La carga de una Subinstalación mantiene la integridad del modelo físico pero reduce pasos:
|
||||
|
||||
1. el buscador de **Instalaciones padre** ahora consulta mientras el inspector escribe;
|
||||
2. cada coincidencia aparece como tarjeta seleccionable y tocarla avanza directamente a la identificación de la Subinstalación;
|
||||
3. la clasificación técnica continúa filtrada por compatibilidad con la Instalación elegida;
|
||||
4. **Guardar y tomar foto** captura GPS y abre la cámara automáticamente.
|
||||
|
||||
Se conserva la regla de que un elemento nacido en campo no puede recibir Hallazgos hasta contar con GPS y fotografía.
|
||||
|
||||
## Actas en Android
|
||||
|
||||
El espacio de Actas fue rediseñado para mostrar con claridad:
|
||||
|
||||
- contexto de la Inspección y Yacimiento;
|
||||
- estado de cada Acta y cantidad de Hallazgos;
|
||||
- urgencia mediante selección explícita;
|
||||
- responsable de empresa, bloqueo, firmas, manifestación y sellado;
|
||||
- condición necesaria para cerrar la Inspección.
|
||||
|
||||
El listado que consume Android usa un read-model móvil liviano (`/inspection-visits/:visitId/acts/mobile`). Esta lectura no depende del módulo documental de oficina ni de `inspection_reports`, de modo que entrar a una Inspección en campo no queda acoplado a la proyección de Informes/GEDO.
|
||||
|
||||
## Barrera obligatoria
|
||||
|
||||
Todo cambio Android o de API que pueda afectar al cliente móvil debe pasar `Android CI / RC`:
|
||||
@@ -23,13 +47,7 @@ Todo cambio Android o de API que pueda afectar al cliente móvil debe pasar `And
|
||||
5. `assembleRelease` para comprobar que la variante productiva compile;
|
||||
6. empaquetado del APK debug con SHA-256 y metadata de commit/versionado.
|
||||
|
||||
La barrera de lint exige además manejo explícito de la revocación de permisos de ubicación durante una captura GPS y declara la cámara como capacidad de hardware opcional, sin relajar permisos ni desactivar reglas globalmente.
|
||||
|
||||
El artefacto de CI contiene:
|
||||
|
||||
- APK debug;
|
||||
- archivo `.sha256`;
|
||||
- `release-metadata.txt` con fase, versión, versionCode, commit, applicationId, API base y canal.
|
||||
Además, `DH V2 CI` debe mantener verdes API, WEB y contrato Docker/migraciones antes de promover el cambio.
|
||||
|
||||
## Firma release
|
||||
|
||||
@@ -44,5 +62,5 @@ Antes de distribuir una APK productiva:
|
||||
- todas las barreras de CI del SHA exacto deben estar verdes;
|
||||
- comprobar certificado/huella de firma contra la versión histórica;
|
||||
- realizar actualización sobre al menos una tablet con la versión productiva anterior;
|
||||
- ejecutar smoke funcional contra el entorno objetivo: login, lista de inspecciones, inicio, inventario, alta de campo, foto/GPS, Acta, Hallazgo y cierre;
|
||||
- ejecutar smoke funcional contra el entorno objetivo: login, abrir Inspección, abrir Actas sin error, crear Acta, búsqueda dinámica de Instalación, selección de padre, alta de Subinstalación, GPS/foto, Hallazgo y cierre;
|
||||
- registrar el SHA Git y SHA-256 de la APK distribuida.
|
||||
|
||||
@@ -12,8 +12,8 @@ android {
|
||||
applicationId = "com.korexlabs.dhinspeccion"
|
||||
minSdk = 26
|
||||
targetSdk = 36
|
||||
versionCode = 25
|
||||
versionName = "0.16.0"
|
||||
versionCode = 27
|
||||
versionName = "0.18.0"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
vectorDrawables.useSupportLibrary = true
|
||||
|
||||
@@ -207,7 +207,7 @@ data class MobileCloseVisitRequest(
|
||||
)
|
||||
|
||||
private interface MobileActsApi {
|
||||
@GET("inspection-visits/{visitId}/acts")
|
||||
@GET("inspection-visits/{visitId}/acts/mobile")
|
||||
suspend fun listActs(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Path("visitId") visitId: String,
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.korexlabs.dhinspeccion.ui
|
||||
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
private val DhLightColors = lightColorScheme(
|
||||
primary = Color(0xFF075E63),
|
||||
onPrimary = Color(0xFFFFFFFF),
|
||||
primaryContainer = Color(0xFFD6F0F0),
|
||||
onPrimaryContainer = Color(0xFF073F43),
|
||||
secondary = Color(0xFF445E74),
|
||||
onSecondary = Color(0xFFFFFFFF),
|
||||
secondaryContainer = Color(0xFFDCE7F1),
|
||||
onSecondaryContainer = Color(0xFF243F54),
|
||||
tertiary = Color(0xFF6A5A42),
|
||||
background = Color(0xFFF6F8FA),
|
||||
onBackground = Color(0xFF182025),
|
||||
surface = Color(0xFFFFFFFF),
|
||||
onSurface = Color(0xFF182025),
|
||||
surfaceVariant = Color(0xFFEDF1F4),
|
||||
onSurfaceVariant = Color(0xFF455158),
|
||||
outline = Color(0xFF77848B),
|
||||
outlineVariant = Color(0xFFD7DEE2),
|
||||
error = Color(0xFFB3261E),
|
||||
onError = Color(0xFFFFFFFF),
|
||||
errorContainer = Color(0xFFF9DEDC),
|
||||
onErrorContainer = Color(0xFF6F1713),
|
||||
)
|
||||
|
||||
private val DhDarkColors = darkColorScheme(
|
||||
primary = Color(0xFF88D4D7),
|
||||
onPrimary = Color(0xFF00373A),
|
||||
primaryContainer = Color(0xFF074F53),
|
||||
onPrimaryContainer = Color(0xFFB7EBED),
|
||||
secondary = Color(0xFFB6CBE0),
|
||||
onSecondary = Color(0xFF203646),
|
||||
secondaryContainer = Color(0xFF344C60),
|
||||
onSecondaryContainer = Color(0xFFDCE7F1),
|
||||
background = Color(0xFF101416),
|
||||
onBackground = Color(0xFFE0E4E6),
|
||||
surface = Color(0xFF171C1F),
|
||||
onSurface = Color(0xFFE0E4E6),
|
||||
surfaceVariant = Color(0xFF263035),
|
||||
onSurfaceVariant = Color(0xFFC3CDD2),
|
||||
outline = Color(0xFF8C989E),
|
||||
error = Color(0xFFFFB4AB),
|
||||
onError = Color(0xFF690005),
|
||||
errorContainer = Color(0xFF93000A),
|
||||
onErrorContainer = Color(0xFFFFDAD6),
|
||||
)
|
||||
|
||||
private val DhShapes = androidx.compose.material3.Shapes(
|
||||
extraSmall = RoundedCornerShape(8.dp),
|
||||
small = RoundedCornerShape(12.dp),
|
||||
medium = RoundedCornerShape(16.dp),
|
||||
large = RoundedCornerShape(22.dp),
|
||||
extraLarge = RoundedCornerShape(28.dp),
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun DhTheme(content: @Composable () -> Unit) {
|
||||
MaterialTheme(
|
||||
colorScheme = if (isSystemInDarkTheme()) DhDarkColors else DhLightColors,
|
||||
shapes = DhShapes,
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,972 @@
|
||||
package com.korexlabs.dhinspeccion.ui
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Environment
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AssistChip
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import com.google.android.gms.location.LocationServices
|
||||
import com.google.android.gms.location.Priority
|
||||
import com.google.android.gms.tasks.CancellationTokenSource
|
||||
import com.korexlabs.dhinspeccion.MainViewModel
|
||||
import com.korexlabs.dhinspeccion.data.FieldAttributeDefinition
|
||||
import com.korexlabs.dhinspeccion.data.FieldInventoryItem
|
||||
import com.korexlabs.dhinspeccion.data.FieldType
|
||||
import com.korexlabs.dhinspeccion.data.VisitDetail
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import java.io.File
|
||||
import java.time.Instant
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
private data class DynamicGeoSnapshot(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val accuracyM: Double?,
|
||||
)
|
||||
|
||||
private enum class DynamicInventoryMode {
|
||||
BROWSE,
|
||||
PICK_PARENT,
|
||||
CREATE_INSTALLATION,
|
||||
CREATE_SUBINSTALLATION,
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun DynamicVisitRoot(model: MainViewModel) {
|
||||
var inventoryMode by rememberSaveable(model.visit?.id) { mutableStateOf(false) }
|
||||
var actsMode by rememberSaveable(model.visit?.id) { mutableStateOf(false) }
|
||||
|
||||
when {
|
||||
actsMode -> MobileActsScreen(
|
||||
model = model,
|
||||
onBack = { actsMode = false },
|
||||
onGoInventory = {
|
||||
actsMode = false
|
||||
inventoryMode = true
|
||||
},
|
||||
)
|
||||
inventoryMode -> DynamicFieldInventoryScreen(
|
||||
model = model,
|
||||
onBack = {
|
||||
inventoryMode = false
|
||||
actsMode = true
|
||||
},
|
||||
)
|
||||
else -> DynamicVisitOverview(
|
||||
model = model,
|
||||
onInventory = { inventoryMode = true },
|
||||
onActs = { actsMode = true },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DynamicVisitOverview(
|
||||
model: MainViewModel,
|
||||
onInventory: () -> Unit,
|
||||
onActs: () -> Unit,
|
||||
) {
|
||||
val visit = model.visit ?: return
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(top = 28.dp, start = 16.dp, end = 16.dp, bottom = 30.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
OutlinedButton(onClick = { model.closeVisitView() }) { Text("Volver") }
|
||||
Text(dynamicStatusLabel(visit.status), fontWeight = FontWeight.Bold)
|
||||
}
|
||||
Text(visit.code, style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
|
||||
Text("${visit.operatorCompany?.name ?: "Sin operadora"} · ${visit.operationalArea?.name ?: "Sin área"}")
|
||||
visit.scopeAsset?.let {
|
||||
Text("Yacimiento: ${it.name}", style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
visit.plannedStartAt?.let {
|
||||
Text("Planificada: ${dynamicShortDate(it)}", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
visit.instructions?.takeIf { it.isNotBlank() }?.let {
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
Text("Instrucciones", fontWeight = FontWeight.Bold)
|
||||
Text(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
DynamicMessageStrip(model)
|
||||
|
||||
if (visit.status == "PLANNED") {
|
||||
Card(
|
||||
Modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer),
|
||||
) {
|
||||
Column(Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("Todo listo para comenzar", fontWeight = FontWeight.Bold)
|
||||
Text("Al iniciar se habilitan Actas, Hallazgos y altas rápidas de campo.")
|
||||
Button(
|
||||
onClick = { model.startVisit(); onActs() },
|
||||
enabled = !model.busy,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text(if (model.busy) "Iniciando…" else "Iniciar inspección") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (visit.status == "IN_PROGRESS") {
|
||||
Card(
|
||||
Modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer),
|
||||
) {
|
||||
Column(Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("Modo campo rápido", fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"Desde Inventario podés cargar una Subinstalación en tres pasos: elegir Instalación, identificarla y capturar GPS + foto.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Button(onClick = onInventory, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("+ Nueva subinstalación / inventario")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Button(onClick = onActs, modifier = Modifier.fillMaxWidth()) {
|
||||
val open = model.acts.count { it.status == "DRAFT" || it.status == "READY" }
|
||||
Text("Abrir Actas · ${model.acts.size}${if (open > 0) " · $open abiertas" else ""}")
|
||||
}
|
||||
OutlinedButton(onClick = onInventory, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("Buscar Inventario / Hallazgos")
|
||||
}
|
||||
} else if (visit.status == "CLOSED") {
|
||||
OutlinedButton(onClick = onActs, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("Ver Actas · ${model.acts.size}")
|
||||
}
|
||||
}
|
||||
|
||||
DynamicChecklistCard(visit)
|
||||
|
||||
Text("Inventario planificado", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
if (visit.planningAssets.none { it.included }) {
|
||||
Text("Sin elementos planificados.")
|
||||
}
|
||||
visit.planningAssets.filter { it.included }.forEach { asset ->
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(10.dp)) {
|
||||
Text(asset.name, fontWeight = FontWeight.SemiBold)
|
||||
Text("${asset.code} · ${asset.typeName.orEmpty()}", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DynamicChecklistCard(visit: VisitDetail) {
|
||||
val checklist = visit.checklist
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Text("Antecedentes antes de salir", fontWeight = FontWeight.Bold)
|
||||
Text("Vencidos empresa: ${checklist.companyOverdue} · Verificaciones vencidas: ${checklist.verificationOverdue}")
|
||||
Text("Antecedentes: ${checklist.antecedents} · Próximos controles: ${checklist.upcomingControls}")
|
||||
if (checklist.stale) {
|
||||
Text("El checklist requiere revisión/actualización.", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DynamicFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val visit = model.visit ?: return
|
||||
|
||||
var modeName by rememberSaveable(visit.id) { mutableStateOf(DynamicInventoryMode.BROWSE.name) }
|
||||
val mode = runCatching { DynamicInventoryMode.valueOf(modeName) }.getOrDefault(DynamicInventoryMode.BROWSE)
|
||||
var search by rememberSaveable(visit.id) { mutableStateOf("") }
|
||||
var parentSearch by rememberSaveable(visit.id) { mutableStateOf("") }
|
||||
var parentId by rememberSaveable(visit.id) { mutableStateOf<String?>(null) }
|
||||
var parentLabel by rememberSaveable(visit.id) { mutableStateOf("") }
|
||||
var name by rememberSaveable(visit.id) { mutableStateOf("") }
|
||||
var commonName by rememberSaveable(visit.id) { mutableStateOf("") }
|
||||
var selectedTypeId by rememberSaveable(visit.id) { mutableStateOf<String?>(null) }
|
||||
var selectedFamilyId by rememberSaveable(visit.id) { mutableStateOf<String?>(null) }
|
||||
var familySearch by rememberSaveable(visit.id) { mutableStateOf("") }
|
||||
val attributeValues = remember { mutableStateMapOf<String, String>() }
|
||||
var pendingAutoPhoto by rememberSaveable(visit.id) { mutableStateOf(false) }
|
||||
var localError by rememberSaveable(visit.id) { mutableStateOf<String?>(null) }
|
||||
var permissionAction by rememberSaveable(visit.id) { mutableStateOf("PHOTO") }
|
||||
|
||||
var mergeSearch by rememberSaveable(visit.id) { mutableStateOf("") }
|
||||
var mergeCandidateId by rememberSaveable(visit.id) { mutableStateOf<String?>(null) }
|
||||
var mergeReason by rememberSaveable(visit.id) { mutableStateOf("") }
|
||||
|
||||
fun resetForm() {
|
||||
name = ""
|
||||
commonName = ""
|
||||
selectedTypeId = null
|
||||
selectedFamilyId = null
|
||||
familySearch = ""
|
||||
attributeValues.clear()
|
||||
localError = null
|
||||
}
|
||||
|
||||
fun backToBrowse() {
|
||||
modeName = DynamicInventoryMode.BROWSE.name
|
||||
parentId = null
|
||||
parentLabel = ""
|
||||
parentSearch = ""
|
||||
resetForm()
|
||||
model.loadFieldTypes(null)
|
||||
}
|
||||
|
||||
fun startInstallation() {
|
||||
model.clearSelectedFieldAsset()
|
||||
modeName = DynamicInventoryMode.CREATE_INSTALLATION.name
|
||||
parentId = null
|
||||
parentLabel = visit.scopeAsset?.name ?: "Yacimiento de la inspección"
|
||||
resetForm()
|
||||
model.loadFieldTypes(null)
|
||||
}
|
||||
|
||||
fun startSubinstallation() {
|
||||
model.clearSelectedFieldAsset()
|
||||
modeName = DynamicInventoryMode.PICK_PARENT.name
|
||||
parentId = null
|
||||
parentLabel = ""
|
||||
parentSearch = ""
|
||||
resetForm()
|
||||
model.searchInventory("", visit.scopeAsset?.id)
|
||||
}
|
||||
|
||||
fun chooseParent(item: FieldInventoryItem) {
|
||||
parentId = item.id
|
||||
parentLabel = "${item.name} (${item.code})"
|
||||
modeName = DynamicInventoryMode.CREATE_SUBINSTALLATION.name
|
||||
resetForm()
|
||||
model.loadFieldTypes(item.id)
|
||||
}
|
||||
|
||||
LaunchedEffect(visit.id) {
|
||||
model.searchInventory("", visit.scopeAsset?.id)
|
||||
}
|
||||
|
||||
LaunchedEffect(model.fieldTypes, modeName) {
|
||||
if (mode == DynamicInventoryMode.CREATE_INSTALLATION || mode == DynamicInventoryMode.CREATE_SUBINSTALLATION) {
|
||||
val preferred = model.fieldTypes.firstOrNull { type ->
|
||||
val normalized = dynamicNormalize(type.structuralKind ?: type.code.ifBlank { type.name })
|
||||
when (mode) {
|
||||
DynamicInventoryMode.CREATE_INSTALLATION -> normalized.contains("instalacion") && !normalized.contains("subinstalacion")
|
||||
DynamicInventoryMode.CREATE_SUBINSTALLATION -> normalized.contains("subinstalacion")
|
||||
else -> false
|
||||
}
|
||||
} ?: model.fieldTypes.firstOrNull()
|
||||
if (model.fieldTypes.none { it.id == selectedTypeId }) {
|
||||
selectedTypeId = preferred?.id
|
||||
selectedFamilyId = null
|
||||
familySearch = ""
|
||||
attributeValues.clear()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val selectedType = model.fieldTypes.firstOrNull { it.id == selectedTypeId }
|
||||
val selectedFamily = selectedType?.families?.firstOrNull { it.id == selectedFamilyId }
|
||||
val filteredFamilies = remember(selectedType, familySearch) {
|
||||
val needle = dynamicNormalize(familySearch)
|
||||
selectedType?.families.orEmpty().filter { family ->
|
||||
needle.isBlank() || dynamicNormalize("${family.code} ${family.name}").contains(needle)
|
||||
}
|
||||
}
|
||||
|
||||
var pendingPhotoFile by remember { mutableStateOf<File?>(null) }
|
||||
var pendingPhotoGeo by remember { mutableStateOf<DynamicGeoSnapshot?>(null) }
|
||||
|
||||
val takePicture = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { success ->
|
||||
val file = pendingPhotoFile
|
||||
val geo = pendingPhotoGeo
|
||||
if (success && file != null && geo != null) {
|
||||
runCatching { writeDynamicExif(file, geo) }
|
||||
model.uploadFieldPhoto(file, geo.latitude, geo.longitude, geo.accuracyM)
|
||||
} else if (!success) {
|
||||
localError = "La foto quedó pendiente. Podés tomarla cuando estés listo."
|
||||
}
|
||||
pendingPhotoFile = null
|
||||
pendingPhotoGeo = null
|
||||
}
|
||||
|
||||
val beginPhoto: () -> Unit = {
|
||||
scope.launch {
|
||||
runCatching { currentDynamicGeo(context) }
|
||||
.onSuccess { geo ->
|
||||
val (file, uri) = newDynamicPhoto(context)
|
||||
pendingPhotoFile = file
|
||||
pendingPhotoGeo = geo
|
||||
takePicture.launch(uri)
|
||||
}
|
||||
.onFailure { localError = it.message ?: "No se pudo obtener el GPS para la fotografía." }
|
||||
}
|
||||
}
|
||||
|
||||
fun createWithLocation() {
|
||||
val type = selectedType ?: return
|
||||
val effectiveParent = when (mode) {
|
||||
DynamicInventoryMode.CREATE_SUBINSTALLATION -> parentId
|
||||
else -> null
|
||||
}
|
||||
scope.launch {
|
||||
runCatching { currentDynamicGeo(context) }
|
||||
.onSuccess { geo ->
|
||||
pendingAutoPhoto = true
|
||||
model.createFieldAsset(
|
||||
type = type,
|
||||
parentId = effectiveParent,
|
||||
familyId = selectedFamilyId,
|
||||
name = name,
|
||||
commonName = commonName,
|
||||
attributes = buildDynamicAttributes(type, attributeValues),
|
||||
latitude = geo.latitude,
|
||||
longitude = geo.longitude,
|
||||
accuracyM = geo.accuracyM,
|
||||
)
|
||||
}
|
||||
.onFailure { localError = it.message ?: "No se pudo capturar la ubicación GPS." }
|
||||
}
|
||||
}
|
||||
|
||||
val permissionsLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
|
||||
val cameraAllowed = result[Manifest.permission.CAMERA] == true || dynamicHasPermission(context, Manifest.permission.CAMERA)
|
||||
val locationAllowed = result[Manifest.permission.ACCESS_FINE_LOCATION] == true ||
|
||||
result[Manifest.permission.ACCESS_COARSE_LOCATION] == true || dynamicHasLocation(context)
|
||||
when (permissionAction) {
|
||||
"CREATE" -> {
|
||||
if (cameraAllowed && locationAllowed) createWithLocation()
|
||||
else localError = "Para el alta rápida se necesitan cámara y ubicación."
|
||||
}
|
||||
else -> {
|
||||
if (cameraAllowed && locationAllowed) beginPhoto()
|
||||
else localError = "Para completar el alta se necesitan cámara y ubicación."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun requestCreate() {
|
||||
permissionAction = "CREATE"
|
||||
if (dynamicHasPermission(context, Manifest.permission.CAMERA) && dynamicHasLocation(context)) {
|
||||
createWithLocation()
|
||||
} else {
|
||||
permissionsLauncher.launch(
|
||||
arrayOf(
|
||||
Manifest.permission.CAMERA,
|
||||
Manifest.permission.ACCESS_FINE_LOCATION,
|
||||
Manifest.permission.ACCESS_COARSE_LOCATION,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun requestPhoto() {
|
||||
permissionAction = "PHOTO"
|
||||
if (dynamicHasPermission(context, Manifest.permission.CAMERA) && dynamicHasLocation(context)) {
|
||||
beginPhoto()
|
||||
} else {
|
||||
permissionsLauncher.launch(
|
||||
arrayOf(
|
||||
Manifest.permission.CAMERA,
|
||||
Manifest.permission.ACCESS_FINE_LOCATION,
|
||||
Manifest.permission.ACCESS_COARSE_LOCATION,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val selectedCapture = model.selectedFieldAsset
|
||||
LaunchedEffect(selectedCapture?.asset?.id, pendingAutoPhoto) {
|
||||
val capture = selectedCapture?.capture
|
||||
if (pendingAutoPhoto && capture?.captureRequired == true && capture.creationGpsCaptured && capture.fieldPhotoCount == 0) {
|
||||
pendingAutoPhoto = false
|
||||
requestPhoto()
|
||||
}
|
||||
}
|
||||
|
||||
val mergeSource = selectedCapture?.takeIf {
|
||||
it.capture.captureRequired && dynamicItemTypeCode(it.asset) in setOf("instalacion", "subinstalacion")
|
||||
}
|
||||
val mergeCandidates = remember(model.inventory, mergeSource) {
|
||||
if (mergeSource == null) emptyList() else model.inventory.filter { candidate ->
|
||||
candidate.id != mergeSource.asset.id &&
|
||||
candidate.informationStatus != "INACTIVE" &&
|
||||
candidate.type?.id == mergeSource.asset.type?.id &&
|
||||
candidate.parent?.id == mergeSource.asset.parent?.id &&
|
||||
!candidate.captureRequired
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().padding(top = 28.dp)) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
OutlinedButton(onClick = { if (mode == DynamicInventoryMode.BROWSE) onBack() else backToBrowse() }) {
|
||||
Text(if (mode == DynamicInventoryMode.BROWSE) "Acta" else "Atrás")
|
||||
}
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
Text(
|
||||
when (mode) {
|
||||
DynamicInventoryMode.PICK_PARENT -> "Elegir Instalación"
|
||||
DynamicInventoryMode.CREATE_INSTALLATION -> "Nueva Instalación"
|
||||
DynamicInventoryMode.CREATE_SUBINSTALLATION -> "Nueva Subinstalación"
|
||||
else -> "Inventario de campo"
|
||||
},
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
Text(visit.scopeAsset?.name ?: visit.code, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.padding(horizontal = 16.dp)) {
|
||||
DynamicMessageStrip(model)
|
||||
localError?.let {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer),
|
||||
onClick = { localError = null },
|
||||
) { Text(it, Modifier.padding(12.dp)) }
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedCapture != null) {
|
||||
DynamicCaptureCard(
|
||||
item = selectedCapture.asset,
|
||||
gps = selectedCapture.capture.creationGpsCaptured,
|
||||
photos = selectedCapture.capture.fieldPhotoCount,
|
||||
ready = selectedCapture.capture.readyForFinding,
|
||||
onPhoto = { requestPhoto() },
|
||||
onClose = { model.clearSelectedFieldAsset() },
|
||||
onCreateAnother = {
|
||||
if (dynamicItemTypeCode(selectedCapture.asset) == "subinstalacion" && selectedCapture.asset.parent != null) {
|
||||
chooseParent(
|
||||
FieldInventoryItem(
|
||||
id = selectedCapture.asset.parent.id,
|
||||
code = selectedCapture.asset.parent.code,
|
||||
name = selectedCapture.asset.parent.name,
|
||||
type = null,
|
||||
),
|
||||
)
|
||||
} else {
|
||||
startSubinstallation()
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (mergeSource != null && !mergeSource.capture.readyForFinding) {
|
||||
Card(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer),
|
||||
) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("¿Ya existía?", fontWeight = FontWeight.Bold)
|
||||
Text("Antes de seguir, podés fusionar el alta con un registro existente compatible.", style = MaterialTheme.typography.bodySmall)
|
||||
OutlinedTextField(
|
||||
value = mergeSearch,
|
||||
onValueChange = { mergeSearch = it },
|
||||
label = { Text("Buscar posible duplicado") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
)
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
mergeCandidateId = null
|
||||
model.searchInventory(mergeSearch, mergeSource.asset.parent?.id)
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Buscar coincidencias") }
|
||||
mergeCandidates.take(6).forEach { candidate ->
|
||||
AssistChip(
|
||||
onClick = { mergeCandidateId = candidate.id },
|
||||
label = {
|
||||
Text(if (mergeCandidateId == candidate.id) "✓ ${candidate.code} · ${candidate.name}" else "${candidate.code} · ${candidate.name}")
|
||||
},
|
||||
)
|
||||
}
|
||||
if (mergeCandidateId != null) {
|
||||
OutlinedTextField(
|
||||
value = mergeReason,
|
||||
onValueChange = { mergeReason = it },
|
||||
label = { Text("Motivo de la fusión") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
minLines = 2,
|
||||
)
|
||||
Button(
|
||||
onClick = { model.mergeCreatedFieldAsset(mergeCandidateId!!, mergeReason) },
|
||||
enabled = mergeReason.trim().length >= 8 && !model.busy,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Fusionar con el existente") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
when (mode) {
|
||||
DynamicInventoryMode.BROWSE -> {
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Card(
|
||||
Modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer),
|
||||
) {
|
||||
Column(Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("Alta rápida en campo", fontWeight = FontWeight.Bold)
|
||||
Text("La Subinstalación se carga guiada, sin navegar por formularios largos.", style = MaterialTheme.typography.bodySmall)
|
||||
Button(onClick = { startSubinstallation() }, modifier = Modifier.fillMaxWidth(), enabled = visit.status == "IN_PROGRESS") {
|
||||
Text("+ Nueva Subinstalación")
|
||||
}
|
||||
OutlinedButton(onClick = { startInstallation() }, modifier = Modifier.fillMaxWidth(), enabled = visit.status == "IN_PROGRESS") {
|
||||
Text("+ Nueva Instalación")
|
||||
}
|
||||
}
|
||||
}
|
||||
OutlinedTextField(
|
||||
value = search,
|
||||
onValueChange = { search = it },
|
||||
label = { Text("Buscar instalación, subinstalación o código") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
)
|
||||
Button(
|
||||
onClick = { model.searchInventory(search) },
|
||||
enabled = !model.busy,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Buscar") }
|
||||
}
|
||||
|
||||
Text("Inventario disponible", Modifier.padding(horizontal = 16.dp, vertical = 8.dp), fontWeight = FontWeight.Bold)
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize().padding(horizontal = 16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
items(
|
||||
model.inventory.filter { dynamicItemTypeCode(it) in setOf("instalacion", "subinstalacion") },
|
||||
key = { it.id },
|
||||
) { item ->
|
||||
DynamicInventoryCard(
|
||||
item = item,
|
||||
onInspect = { model.selectExisting(item) },
|
||||
onAddChild = { chooseParent(item) },
|
||||
)
|
||||
}
|
||||
item { Spacer(Modifier.height(30.dp)) }
|
||||
}
|
||||
}
|
||||
|
||||
DynamicInventoryMode.PICK_PARENT -> {
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
DynamicStepHeader(1, "Elegí la Instalación padre")
|
||||
Text("Solo se muestran Instalaciones del Yacimiento de esta inspección.", style = MaterialTheme.typography.bodySmall)
|
||||
OutlinedTextField(
|
||||
value = parentSearch,
|
||||
onValueChange = { parentSearch = it },
|
||||
label = { Text("Buscar Instalación por nombre o código") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
)
|
||||
Button(
|
||||
onClick = { model.searchInventory(parentSearch, visit.scopeAsset?.id) },
|
||||
enabled = !model.busy,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Buscar Instalación") }
|
||||
}
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
items(
|
||||
model.inventory.filter { dynamicItemTypeCode(it) == "instalacion" },
|
||||
key = { it.id },
|
||||
) { item ->
|
||||
Card(onClick = { chooseParent(item) }, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(item.name, fontWeight = FontWeight.Bold)
|
||||
Text(item.code, style = MaterialTheme.typography.bodySmall)
|
||||
Text("Tocar para agregar una Subinstalación", color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
item { Spacer(Modifier.height(24.dp)) }
|
||||
}
|
||||
}
|
||||
|
||||
DynamicInventoryMode.CREATE_INSTALLATION,
|
||||
DynamicInventoryMode.CREATE_SUBINSTALLATION -> {
|
||||
val isSubinstallation = mode == DynamicInventoryMode.CREATE_SUBINSTALLATION
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.padding(horizontal = 16.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
DynamicStepHeader(if (isSubinstallation) 2 else 1, if (isSubinstallation) "Identificá la Subinstalación" else "Identificá la Instalación")
|
||||
Text("Ubicación: $parentLabel", style = MaterialTheme.typography.bodySmall, fontWeight = FontWeight.SemiBold)
|
||||
if (isSubinstallation) {
|
||||
OutlinedButton(onClick = { startSubinstallation() }, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("Cambiar Instalación padre")
|
||||
}
|
||||
}
|
||||
|
||||
if (model.fieldTypes.isEmpty()) {
|
||||
Text("No hay un tipo habilitado para esta ubicación.", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
|
||||
if (model.fieldTypes.size > 1) {
|
||||
Text("Nivel de Inventario", fontWeight = FontWeight.Bold)
|
||||
model.fieldTypes.forEach { type ->
|
||||
AssistChip(
|
||||
onClick = {
|
||||
selectedTypeId = type.id
|
||||
selectedFamilyId = null
|
||||
attributeValues.clear()
|
||||
},
|
||||
label = { Text(if (selectedTypeId == type.id) "✓ ${type.name}" else type.name) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedType?.familyRequired == true) {
|
||||
Text("Clasificación técnica *", fontWeight = FontWeight.Bold)
|
||||
OutlinedTextField(
|
||||
value = familySearch,
|
||||
onValueChange = { familySearch = it },
|
||||
label = { Text("Buscar clasificación") },
|
||||
supportingText = { Text("${filteredFamilies.size} opciones compatibles") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
)
|
||||
filteredFamilies.take(12).forEach { family ->
|
||||
AssistChip(
|
||||
onClick = { selectedFamilyId = family.id },
|
||||
label = {
|
||||
val prefix = when {
|
||||
selectedFamilyId == family.id -> "✓ "
|
||||
family.isOther -> "+ "
|
||||
else -> ""
|
||||
}
|
||||
Text(prefix + family.name)
|
||||
},
|
||||
)
|
||||
}
|
||||
if (filteredFamilies.size > 12) {
|
||||
Text("Escribí parte del nombre para reducir la lista.", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
selectedFamily?.let { family ->
|
||||
if (family.isOther) {
|
||||
Text("Quedará marcado como no catalogado para revisión en oficina.", color = MaterialTheme.colorScheme.secondary)
|
||||
}
|
||||
if (family.informationLabels.isNotEmpty()) {
|
||||
Text("Datos esperados: ${family.informationLabels.joinToString(" · ")}", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
label = { Text("Nombre o código visible *") },
|
||||
supportingText = { Text("Usá lo que ve el inspector en la placa o en campo.") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = commonName,
|
||||
onValueChange = { commonName = it },
|
||||
label = { Text("Nombre habitual") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
)
|
||||
|
||||
selectedType?.attributes?.forEach { definition ->
|
||||
OutlinedTextField(
|
||||
value = attributeValues[definition.code].orEmpty(),
|
||||
onValueChange = { attributeValues[definition.code] = it },
|
||||
label = { Text(definition.name + if (definition.isRequired) " *" else "") },
|
||||
supportingText = {
|
||||
val details = listOfNotNull(definition.unit, definition.options?.toString()).joinToString(" · ")
|
||||
if (details.isNotBlank()) Text(details)
|
||||
},
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = if (definition.dataType.uppercase() in setOf("NUMBER", "DECIMAL", "INTEGER", "FLOAT")) KeyboardType.Decimal else KeyboardType.Text,
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
DynamicStepHeader(if (isSubinstallation) 3 else 2, "GPS + foto en un solo paso")
|
||||
Text(
|
||||
"Al guardar se captura la ubicación actual y la cámara se abre automáticamente. La foto sigue siendo obligatoria antes de crear Hallazgos.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
|
||||
val attributesReady = selectedType?.attributes
|
||||
?.filter { it.isRequired }
|
||||
?.all { attributeValues[it.code].orEmpty().isNotBlank() }
|
||||
?: false
|
||||
val familyReady = selectedType?.familyRequired != true || selectedFamilyId != null
|
||||
Button(
|
||||
onClick = { requestCreate() },
|
||||
enabled = selectedType != null && name.isNotBlank() && attributesReady && familyReady && !model.busy,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text(if (model.busy) "Guardando…" else "Guardar y tomar foto") }
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DynamicStepHeader(step: Int, title: String) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer)) {
|
||||
Text(step.toString(), Modifier.padding(horizontal = 10.dp, vertical = 6.dp), fontWeight = FontWeight.Bold)
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DynamicCaptureCard(
|
||||
item: FieldInventoryItem,
|
||||
gps: Boolean,
|
||||
photos: Int,
|
||||
ready: Boolean,
|
||||
onPhoto: () -> Unit,
|
||||
onClose: () -> Unit,
|
||||
onCreateAnother: () -> Unit,
|
||||
) {
|
||||
Card(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = if (ready) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant,
|
||||
),
|
||||
) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(7.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(item.name, fontWeight = FontWeight.Bold)
|
||||
Text(item.code, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
OutlinedButton(onClick = onClose) { Text("Cerrar") }
|
||||
}
|
||||
Text("GPS: ${if (gps) "OK" else "pendiente"} · Fotos: $photos")
|
||||
if (!ready) {
|
||||
Text("Falta la fotografía obligatoria.", color = MaterialTheme.colorScheme.error)
|
||||
Button(onClick = onPhoto, modifier = Modifier.fillMaxWidth()) { Text("Tomar foto ahora") }
|
||||
} else {
|
||||
Text("Alta completa · lista para Hallazgos", color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.Bold)
|
||||
OutlinedButton(onClick = onCreateAnother, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("+ Crear otra Subinstalación")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DynamicInventoryCard(
|
||||
item: FieldInventoryItem,
|
||||
onInspect: () -> Unit,
|
||||
onAddChild: () -> Unit,
|
||||
) {
|
||||
val typeCode = dynamicItemTypeCode(item)
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
Text(item.name, fontWeight = FontWeight.SemiBold)
|
||||
Text(if (typeCode == "subinstalacion") "Subinstalación" else "Instalación", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
Text(item.code, style = MaterialTheme.typography.bodySmall)
|
||||
item.commonName?.takeIf { it.isNotBlank() }?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
Text(
|
||||
if (item.readyForFinding) "Disponible" else "GPS/foto pendiente",
|
||||
color = if (item.readyForFinding) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Button(onClick = onInspect, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(if (item.selectedInInspection) "Abrir para Hallazgo" else "Usar para Hallazgo")
|
||||
}
|
||||
if (typeCode == "instalacion") {
|
||||
OutlinedButton(onClick = onAddChild, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("+ Agregar Subinstalación")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DynamicMessageStrip(model: MainViewModel) {
|
||||
val error = model.error
|
||||
val notice = model.notice
|
||||
if (error != null || notice != null) {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = if (error != null) MaterialTheme.colorScheme.errorContainer else MaterialTheme.colorScheme.secondaryContainer,
|
||||
),
|
||||
onClick = { model.clearMessages() },
|
||||
) {
|
||||
Text(error ?: notice.orEmpty(), Modifier.padding(12.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun dynamicItemTypeCode(item: FieldInventoryItem): String {
|
||||
val type = item.type ?: return ""
|
||||
return dynamicNormalize(type.typeName ?: type.name)
|
||||
}
|
||||
|
||||
private fun dynamicNormalize(value: String): String = value.trim().lowercase()
|
||||
.replace('ó', 'o')
|
||||
.replace('í', 'i')
|
||||
.replace('á', 'a')
|
||||
.replace('é', 'e')
|
||||
.replace('ú', 'u')
|
||||
.replace("_", "")
|
||||
.replace("-", "")
|
||||
.replace(" ", "")
|
||||
|
||||
private fun dynamicStatusLabel(status: String): String = when (status) {
|
||||
"PLANNED" -> "Planificada"
|
||||
"IN_PROGRESS" -> "En curso"
|
||||
"CLOSED" -> "Cerrada"
|
||||
"CANCELLED" -> "Cancelada"
|
||||
else -> status
|
||||
}
|
||||
|
||||
private fun buildDynamicAttributes(type: FieldType, values: Map<String, String>): Map<String, Any?> =
|
||||
type.attributes.mapNotNull { definition ->
|
||||
val raw = values[definition.code]?.trim().orEmpty()
|
||||
if (raw.isBlank()) return@mapNotNull null
|
||||
definition.code to coerceDynamicAttribute(definition, raw)
|
||||
}.toMap()
|
||||
|
||||
private fun coerceDynamicAttribute(definition: FieldAttributeDefinition, raw: String): Any = when (definition.dataType.uppercase()) {
|
||||
"INTEGER", "INT" -> raw.toLongOrNull() ?: raw
|
||||
"NUMBER", "DECIMAL", "FLOAT", "DOUBLE" -> raw.replace(',', '.').toDoubleOrNull() ?: raw
|
||||
"BOOLEAN", "BOOL" -> raw.lowercase() in setOf("true", "1", "si", "sí", "yes")
|
||||
else -> raw
|
||||
}
|
||||
|
||||
private fun dynamicHasPermission(context: Context, permission: String): Boolean =
|
||||
ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
private fun dynamicHasLocation(context: Context): Boolean =
|
||||
dynamicHasPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) ||
|
||||
dynamicHasPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
|
||||
|
||||
private suspend fun currentDynamicGeo(context: Context): DynamicGeoSnapshot = suspendCancellableCoroutine { continuation ->
|
||||
if (!dynamicHasLocation(context)) {
|
||||
continuation.resumeWithException(SecurityException("Se necesita permiso de ubicación."))
|
||||
return@suspendCancellableCoroutine
|
||||
}
|
||||
val source = CancellationTokenSource()
|
||||
val client = LocationServices.getFusedLocationProviderClient(context)
|
||||
try {
|
||||
client.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, source.token)
|
||||
.addOnSuccessListener { location ->
|
||||
if (!continuation.isActive) return@addOnSuccessListener
|
||||
if (location == null) {
|
||||
continuation.resumeWithException(IllegalStateException("No se pudo obtener una ubicación GPS actual."))
|
||||
} else {
|
||||
continuation.resume(DynamicGeoSnapshot(location.latitude, location.longitude, location.accuracy.toDouble()))
|
||||
}
|
||||
}
|
||||
.addOnFailureListener { if (continuation.isActive) continuation.resumeWithException(it) }
|
||||
} catch (error: SecurityException) {
|
||||
if (continuation.isActive) continuation.resumeWithException(error)
|
||||
}
|
||||
continuation.invokeOnCancellation { source.cancel() }
|
||||
}
|
||||
|
||||
private fun newDynamicPhoto(context: Context): Pair<File, Uri> {
|
||||
val directory = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
|
||||
?: throw IllegalStateException("No se pudo acceder al almacenamiento de fotografías.")
|
||||
directory.mkdirs()
|
||||
val file = File.createTempFile("DH_FAST_${System.currentTimeMillis()}_", ".jpg", directory)
|
||||
val uri = FileProvider.getUriForFile(context, "${context.packageName}.files", file)
|
||||
return file to uri
|
||||
}
|
||||
|
||||
private fun writeDynamicExif(file: File, geo: DynamicGeoSnapshot) {
|
||||
val now = Instant.now()
|
||||
val exif = ExifInterface(file)
|
||||
exif.setLatLong(geo.latitude, geo.longitude)
|
||||
val formatter = DateTimeFormatter.ofPattern("yyyy:MM:dd HH:mm:ss").withZone(ZoneId.systemDefault())
|
||||
exif.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, formatter.format(now))
|
||||
exif.setAttribute(ExifInterface.TAG_DATETIME_DIGITIZED, formatter.format(now))
|
||||
exif.saveAttributes()
|
||||
}
|
||||
|
||||
private fun dynamicShortDate(value: String): String = value.replace('T', ' ').take(16)
|
||||
@@ -74,7 +74,7 @@ fun DhRoot(model: MainViewModel, activity: FragmentActivity) {
|
||||
if (model.session == null) unlocked = false
|
||||
}
|
||||
|
||||
MaterialTheme {
|
||||
DhTheme {
|
||||
Surface(Modifier.fillMaxSize()) {
|
||||
when {
|
||||
model.session == null -> EnhancedLoginScreen(model) {
|
||||
@@ -91,7 +91,7 @@ fun DhRoot(model: MainViewModel, activity: FragmentActivity) {
|
||||
},
|
||||
)
|
||||
model.fieldFindingOptions != null -> FieldFindingScreen(model)
|
||||
model.visit != null -> F3VisitRoot(model)
|
||||
model.visit != null -> ModernVisitRoot(model)
|
||||
else -> MobileHomeScreen(model)
|
||||
}
|
||||
}
|
||||
|
||||
+565
@@ -0,0 +1,565 @@
|
||||
package com.korexlabs.dhinspeccion.ui
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Assignment
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.EditNote
|
||||
import androidx.compose.material.icons.filled.ErrorOutline
|
||||
import androidx.compose.material.icons.filled.Lock
|
||||
import androidx.compose.material.icons.filled.Person
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ElevatedCard
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
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.core.content.ContextCompat
|
||||
import com.google.android.gms.location.LocationServices
|
||||
import com.google.android.gms.location.Priority
|
||||
import com.google.android.gms.tasks.CancellationTokenSource
|
||||
import com.korexlabs.dhinspeccion.MainViewModel
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import java.io.File
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
private data class ModernActSignatureGeo(
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val accuracyM: Double?,
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun ModernMobileActsScreen(
|
||||
model: MainViewModel,
|
||||
onBack: () -> Unit,
|
||||
onGoInventory: () -> Unit,
|
||||
) {
|
||||
val visit = model.visit ?: return
|
||||
val selected = model.selectedAct
|
||||
val closure = model.actClosure
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
var newActUrgency by rememberSaveable(visit.id) { mutableStateOf("NON_URGENT") }
|
||||
var attendance by rememberSaveable(selected?.id) { mutableStateOf(closure?.responsible?.attendanceStatus ?: "PRESENT") }
|
||||
var fullName by rememberSaveable(selected?.id) { mutableStateOf(closure?.responsible?.fullName.orEmpty()) }
|
||||
var documentType by rememberSaveable(selected?.id) { mutableStateOf(closure?.responsible?.documentType ?: "DNI") }
|
||||
var documentNumber by rememberSaveable(selected?.id) { mutableStateOf(closure?.responsible?.documentNumber.orEmpty()) }
|
||||
var position by rememberSaveable(selected?.id) { mutableStateOf(closure?.responsible?.position.orEmpty()) }
|
||||
var email by rememberSaveable(selected?.id) { mutableStateOf(closure?.responsible?.email.orEmpty()) }
|
||||
var phone by rememberSaveable(selected?.id) { mutableStateOf(closure?.responsible?.phone.orEmpty()) }
|
||||
var absenceReason by rememberSaveable(selected?.id) { mutableStateOf(closure?.responsible?.absenceReason.orEmpty()) }
|
||||
var refusalReason by rememberSaveable(selected?.id) { mutableStateOf("") }
|
||||
var manifestation by rememberSaveable(selected?.id) { mutableStateOf("CONFORMITY") }
|
||||
var dissentStatement by rememberSaveable(selected?.id) { mutableStateOf("") }
|
||||
|
||||
LaunchedEffect(visit.id) { model.reloadActs() }
|
||||
|
||||
fun signWithGeo(file: File, company: Boolean) {
|
||||
scope.launch {
|
||||
val geo = runCatching { currentModernActSignatureGeo(context) }.getOrNull()
|
||||
if (company) {
|
||||
model.signSelectedActAsCompany(
|
||||
png = file,
|
||||
latitude = geo?.latitude,
|
||||
longitude = geo?.longitude,
|
||||
accuracyM = geo?.accuracyM,
|
||||
manifestation = manifestation,
|
||||
statement = dissentStatement.takeIf { manifestation == "DISSENT" },
|
||||
)
|
||||
} else {
|
||||
model.signSelectedActAsInspector(
|
||||
png = file,
|
||||
latitude = geo?.latitude,
|
||||
longitude = geo?.longitude,
|
||||
accuracyM = geo?.accuracyM,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = 18.dp, vertical = 16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
ModernHeader(title = "Actas", subtitle = visit.code, onBack = onBack)
|
||||
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.large,
|
||||
tonalElevation = 1.dp,
|
||||
) {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||
Text(
|
||||
visit.scopeAsset?.name ?: "Yacimiento",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
visit.operatorCompany?.name?.takeIf { it.isNotBlank() }?.let {
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ModernMessage(model)
|
||||
|
||||
if (model.acts.isEmpty()) {
|
||||
ElevatedCard(Modifier.fillMaxWidth()) {
|
||||
Column(
|
||||
Modifier.padding(20.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Icon(Icons.Filled.Assignment, contentDescription = null, tint = MaterialTheme.colorScheme.secondary)
|
||||
Text("Todavía no hay Actas", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"Creá la primera Acta y después incorporá Hallazgos seleccionando el Inventario.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Text("Actas de esta inspección", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
model.acts.forEach { act ->
|
||||
val active = selected?.id == act.id
|
||||
Surface(
|
||||
onClick = { model.selectAct(act.id) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.large,
|
||||
color = if (active) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surface,
|
||||
tonalElevation = if (active) 1.dp else 0.dp,
|
||||
border = BorderStroke(
|
||||
if (active) 2.dp else 1.dp,
|
||||
if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outlineVariant,
|
||||
),
|
||||
) {
|
||||
Row(
|
||||
Modifier.padding(15.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Icon(
|
||||
when (act.status) {
|
||||
"LOCKED" -> Icons.Filled.Lock
|
||||
"SEALED" -> Icons.Filled.CheckCircle
|
||||
else -> Icons.Filled.EditNote
|
||||
},
|
||||
contentDescription = null,
|
||||
tint = if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.secondary,
|
||||
)
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text(act.code, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"${modernActStatusLabel(act.status)} · ${if (act.urgency == "URGENT") "Urgente" else "No urgente"}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
"${act.findingCount} Hallazgo${if (act.findingCount == 1) "" else "s"} · ${act.assetCount} elemento${if (act.assetCount == 1) "" else "s"}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
if (active) Icon(Icons.Filled.CheckCircle, "Seleccionada", tint = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val hasDraftAct = model.acts.any { it.status == "DRAFT" }
|
||||
if (visit.status == "IN_PROGRESS" && !hasDraftAct) {
|
||||
ElevatedCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Surface(shape = MaterialTheme.shapes.medium, color = MaterialTheme.colorScheme.primaryContainer) {
|
||||
Icon(Icons.Filled.Add, null, Modifier.padding(10.dp), tint = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column {
|
||||
Text("Nueva Acta", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text("Un solo borrador activo por vez", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
Text("Urgencia", fontWeight = FontWeight.SemiBold)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
FilterChip(
|
||||
selected = newActUrgency == "NON_URGENT",
|
||||
onClick = { newActUrgency = "NON_URGENT" },
|
||||
label = { Text("No urgente") },
|
||||
)
|
||||
FilterChip(
|
||||
selected = newActUrgency == "URGENT",
|
||||
onClick = { newActUrgency = "URGENT" },
|
||||
label = { Text("Urgente") },
|
||||
)
|
||||
}
|
||||
Surface(
|
||||
Modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
) {
|
||||
Text(
|
||||
if (newActUrgency == "URGENT") {
|
||||
"El plazo urgente se computará desde el Acta conforme a la política institucional vigente al bloquearla."
|
||||
} else {
|
||||
"El plazo no urgente comienza con la oficialización GEDO, no al crear el Acta."
|
||||
},
|
||||
Modifier.padding(12.dp),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
Button(
|
||||
onClick = { model.createAct(newActUrgency) },
|
||||
enabled = !model.busy,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Icon(Icons.Filled.Add, null)
|
||||
Spacer(Modifier.width(7.dp))
|
||||
Text(if (model.busy) "Creando…" else "Crear nueva Acta")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (selected != null) {
|
||||
HorizontalDivider()
|
||||
Surface(
|
||||
Modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.large,
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
) {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(selected.code, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
StatusPill(modernActStatusLabel(selected.status))
|
||||
}
|
||||
Text(if (selected.urgency == "URGENT") "Urgente" else "No urgente", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Text("${selected.findingCount} Hallazgos · ${selected.assetCount} elementos de Inventario", style = MaterialTheme.typography.bodySmall)
|
||||
selected.deadlineAt?.let { Text("Vencimiento · $it", style = MaterialTheme.typography.bodySmall) }
|
||||
if (selected.deadlineAt == null && selected.deadlineBasis == "GEDO_DATE") {
|
||||
Text("Vencimiento pendiente de fecha GEDO", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
when (selected.status) {
|
||||
"DRAFT" -> {
|
||||
ElevatedCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text("Hallazgos", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"Elegí una Instalación o Subinstalación existente, o creala en campo si todavía no está registrada.",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Button(onClick = onGoInventory, modifier = Modifier.fillMaxWidth()) {
|
||||
Icon(Icons.Filled.Add, null)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("Agregar Hallazgo")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ElevatedCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Person, null, tint = MaterialTheme.colorScheme.primary)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("Responsable de la empresa", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
FilterChip(selected = attendance == "PRESENT", onClick = { attendance = "PRESENT" }, label = { Text("Presente") })
|
||||
FilterChip(selected = attendance == "ABSENT", onClick = { attendance = "ABSENT" }, label = { Text("Ausente") })
|
||||
}
|
||||
if (attendance == "PRESENT") {
|
||||
OutlinedTextField(fullName, { fullName = it }, label = { Text("Nombre y apellido *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
listOf("DNI", "CUIL", "PASSPORT", "OTHER").forEach { kind ->
|
||||
FilterChip(selected = documentType == kind, onClick = { documentType = kind }, label = { Text(kind) })
|
||||
}
|
||||
}
|
||||
OutlinedTextField(documentNumber, { documentNumber = it }, label = { Text("Documento *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||
OutlinedTextField(position, { position = it }, label = { Text("Cargo *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||
OutlinedTextField(email, { email = it }, label = { Text("Email") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||
OutlinedTextField(phone, { phone = it }, label = { Text("Teléfono") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||
Button(
|
||||
onClick = { model.setCompanyResponsiblePresent(fullName, documentType, documentNumber, position, email, phone) },
|
||||
enabled = !model.busy && fullName.isNotBlank() && documentNumber.isNotBlank() && position.isNotBlank(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Guardar responsable") }
|
||||
} else {
|
||||
OutlinedTextField(
|
||||
absenceReason,
|
||||
{ absenceReason = it },
|
||||
label = { Text("Motivo de ausencia *") },
|
||||
minLines = 2,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Button(
|
||||
onClick = { model.setCompanyResponsibleAbsent(absenceReason) },
|
||||
enabled = !model.busy && absenceReason.trim().length >= 10,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Guardar ausencia") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ElevatedCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Lock, null, tint = MaterialTheme.colorScheme.error)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("Finalizar contenido", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
Text(
|
||||
"Al bloquear el Acta, su contenido y sus Hallazgos quedan inmutables.",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Button(
|
||||
onClick = { model.prepareSelectedAct() },
|
||||
enabled = !model.busy && closure?.responsible != null,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Finalizar y BLOQUEAR Acta") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
"LOCKED" -> {
|
||||
val signatures = closure?.signatures.orEmpty()
|
||||
val inspectorSigned = signatures.any { it.signerType == "INSPECTOR" && it.status == "SIGNED" }
|
||||
val companyOutcome = signatures.firstOrNull { it.signerType == "COMPANY_RESPONSIBLE" }
|
||||
val companyResolved = companyOutcome?.status == "SIGNED" || companyOutcome?.status == "REFUSED"
|
||||
|
||||
ElevatedCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Lock, null, tint = MaterialTheme.colorScheme.secondary)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("Acta BLOQUEADA", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
Text("El contenido ya es inmutable. Restan firmas y manifestaciones para poder sellarla.")
|
||||
closure?.closure?.preparedSha256?.let { Text("Hash · $it", style = MaterialTheme.typography.bodySmall) }
|
||||
|
||||
HorizontalDivider()
|
||||
Text("Firma del inspector", fontWeight = FontWeight.Bold)
|
||||
if (inspectorSigned) {
|
||||
SuccessLine("Firma del inspector registrada")
|
||||
} else {
|
||||
Text(closure?.consents?.inspector.orEmpty(), style = MaterialTheme.typography.bodySmall)
|
||||
SignaturePad(
|
||||
label = "Firmá como inspector/a",
|
||||
enabled = !model.busy,
|
||||
onCaptured = { file -> signWithGeo(file, company = false) },
|
||||
)
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Text("Manifestación de la empresa", fontWeight = FontWeight.Bold)
|
||||
if (companyOutcome != null && companyResolved) {
|
||||
val detail = when (companyOutcome.status) {
|
||||
"SIGNED" -> if (companyOutcome.companyManifestation == "DISSENT") "Firma en disidencia" else "Firma en conformidad"
|
||||
"REFUSED" -> "Negativa a firmar"
|
||||
else -> companyOutcome.status
|
||||
}
|
||||
SuccessLine(detail)
|
||||
companyOutcome.reason?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
companyOutcome.companyStatement?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
} else if (closure?.responsible?.attendanceStatus == "ABSENT") {
|
||||
Surface(Modifier.fillMaxWidth(), shape = MaterialTheme.shapes.medium, color = MaterialTheme.colorScheme.errorContainer) {
|
||||
Row(Modifier.padding(12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Icon(Icons.Filled.ErrorOutline, null, tint = MaterialTheme.colorScheme.error)
|
||||
Text(
|
||||
"La ausencia no resuelve la manifestación. Debe registrarse firma o negativa antes de sellar.",
|
||||
Modifier.weight(1f),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Text(closure?.consents?.company.orEmpty(), style = MaterialTheme.typography.bodySmall)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
FilterChip(selected = manifestation == "CONFORMITY", onClick = { manifestation = "CONFORMITY" }, label = { Text("Conforme") })
|
||||
FilterChip(selected = manifestation == "DISSENT", onClick = { manifestation = "DISSENT" }, label = { Text("En disidencia") })
|
||||
}
|
||||
if (manifestation == "DISSENT") {
|
||||
OutlinedTextField(
|
||||
dissentStatement,
|
||||
{ dissentStatement = it },
|
||||
label = { Text("Manifestación de disidencia *") },
|
||||
minLines = 2,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
SignaturePad(
|
||||
label = "Firma del responsable de empresa",
|
||||
enabled = !model.busy && inspectorSigned && (manifestation != "DISSENT" || dissentStatement.trim().length >= 10),
|
||||
onCaptured = { file -> signWithGeo(file, company = true) },
|
||||
)
|
||||
Text("Si se niega a firmar, registrá el motivo.", style = MaterialTheme.typography.bodySmall)
|
||||
OutlinedTextField(
|
||||
refusalReason,
|
||||
{ refusalReason = it },
|
||||
label = { Text("Motivo de negativa") },
|
||||
minLines = 2,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
OutlinedButton(
|
||||
onClick = { model.recordCompanyOutcome("REFUSED", refusalReason) },
|
||||
enabled = !model.busy && inspectorSigned && refusalReason.trim().length >= 10,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Registrar negativa a firmar") }
|
||||
}
|
||||
|
||||
if (inspectorSigned && companyResolved) {
|
||||
Button(
|
||||
onClick = { model.closeSelectedAct() },
|
||||
enabled = !model.busy,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Icon(Icons.Filled.CheckCircle, null)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("SELLAR Acta definitivamente")
|
||||
}
|
||||
} else {
|
||||
Text(
|
||||
"La Inspección no puede cerrarse hasta completar las manifestaciones de esta Acta.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
"SEALED" -> {
|
||||
ElevatedCard(Modifier.fillMaxWidth()) {
|
||||
Row(Modifier.padding(18.dp), horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.Top) {
|
||||
Icon(Icons.Filled.CheckCircle, null, tint = MaterialTheme.colorScheme.primary)
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||
Text("Acta SELLADA e inmutable", fontWeight = FontWeight.Bold)
|
||||
Text("Desde este sellado se genera el PDF del Acta y el INF Word editable para el Inspector.")
|
||||
closure?.closure?.finalSha256?.let { Text("SHA-256 · $it", style = MaterialTheme.typography.bodySmall) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
"CANCELLED" -> {
|
||||
Surface(Modifier.fillMaxWidth(), shape = MaterialTheme.shapes.medium, color = MaterialTheme.colorScheme.surfaceVariant) {
|
||||
Text("Esta Acta fue cancelada y permanece como antecedente.", Modifier.padding(14.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (visit.status == "IN_PROGRESS" && model.acts.isNotEmpty()) {
|
||||
val activeActs = model.acts.filter { it.status != "CANCELLED" }
|
||||
val pendingActs = activeActs.filter { it.status != "SEALED" }
|
||||
ElevatedCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(9.dp)) {
|
||||
Text("Finalizar Inspección", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
if (pendingActs.isEmpty()) {
|
||||
SuccessLine("Todas las Actas están SELLADAS")
|
||||
} else {
|
||||
Text(
|
||||
"Falta SELLAR: ${pendingActs.joinToString { it.code }}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
Button(
|
||||
onClick = { model.closeInspection() },
|
||||
enabled = !model.busy && activeActs.isNotEmpty() && pendingActs.isEmpty(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Cerrar Inspección y salir") }
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(32.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SuccessLine(text: String) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp)) {
|
||||
Icon(Icons.Filled.CheckCircle, null, tint = MaterialTheme.colorScheme.primary)
|
||||
Text(text, color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
|
||||
private fun modernActStatusLabel(status: String): String = when (status) {
|
||||
"DRAFT" -> "Borrador"
|
||||
"LOCKED" -> "Bloqueada"
|
||||
"SEALED" -> "Sellada"
|
||||
"CANCELLED" -> "Cancelada"
|
||||
else -> status
|
||||
}
|
||||
|
||||
private fun hasModernActLocation(context: Context): Boolean =
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
private suspend fun currentModernActSignatureGeo(context: Context): ModernActSignatureGeo = suspendCancellableCoroutine { continuation ->
|
||||
if (!hasModernActLocation(context)) {
|
||||
continuation.resumeWithException(SecurityException("Ubicación no autorizada"))
|
||||
return@suspendCancellableCoroutine
|
||||
}
|
||||
val source = CancellationTokenSource()
|
||||
try {
|
||||
LocationServices.getFusedLocationProviderClient(context)
|
||||
.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, source.token)
|
||||
.addOnSuccessListener { location ->
|
||||
if (!continuation.isActive) return@addOnSuccessListener
|
||||
if (location == null) continuation.resumeWithException(IllegalStateException("Ubicación no disponible"))
|
||||
else continuation.resume(ModernActSignatureGeo(location.latitude, location.longitude, location.accuracy.toDouble()))
|
||||
}
|
||||
.addOnFailureListener { if (continuation.isActive) continuation.resumeWithException(it) }
|
||||
} catch (error: SecurityException) {
|
||||
if (continuation.isActive) continuation.resumeWithException(error)
|
||||
}
|
||||
continuation.invokeOnCancellation { source.cancel() }
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+26
@@ -0,0 +1,26 @@
|
||||
package com.korexlabs.dhinspeccion
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class DynamicFieldFlowContractTest {
|
||||
private val source = File("src/main/java/com/korexlabs/dhinspeccion/ui/DynamicVisitRoot.kt").readText()
|
||||
|
||||
@Test
|
||||
fun fastSubinstallationFlowKeepsParentClassificationAndCaptureSteps() {
|
||||
assertTrue(source.contains("Elegí la Instalación padre"))
|
||||
assertTrue(source.contains("Clasificación técnica *"))
|
||||
assertTrue(source.contains("Guardar y tomar foto"))
|
||||
assertTrue(source.contains("model.loadFieldTypes(item.id)"))
|
||||
assertTrue(source.contains("parentId = item.id"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fieldCaptureStillRequiresGpsAndPhotoBeforeFindings() {
|
||||
assertTrue(source.contains("La foto sigue siendo obligatoria antes de crear Hallazgos"))
|
||||
assertTrue(source.contains("creationGpsCaptured"))
|
||||
assertTrue(source.contains("fieldPhotoCount == 0"))
|
||||
assertTrue(source.contains("model.uploadFieldPhoto"))
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,8 @@ class ReleaseMetadataTest {
|
||||
@Test
|
||||
fun debugBuildKeepsSeparateApplicationIdentity() {
|
||||
assertEquals("com.korexlabs.dhinspeccion.debug", BuildConfig.APPLICATION_ID)
|
||||
assertEquals(25, BuildConfig.VERSION_CODE)
|
||||
assertEquals("0.16.0-debug", BuildConfig.VERSION_NAME)
|
||||
assertEquals(27, BuildConfig.VERSION_CODE)
|
||||
assertEquals("0.18.0-debug", BuildConfig.VERSION_NAME)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -5,10 +5,16 @@ import {
|
||||
InspectionVisitActsController,
|
||||
} from './inspection-acts.controller';
|
||||
import { InspectionActsService } from './inspection-acts.service';
|
||||
import { MobileInspectionActsController } from './mobile-inspection-acts.controller';
|
||||
import { MobileInspectionActsService } from './mobile-inspection-acts.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuditModule],
|
||||
controllers: [InspectionVisitActsController, InspectionActsController],
|
||||
providers: [InspectionActsService],
|
||||
controllers: [
|
||||
InspectionVisitActsController,
|
||||
MobileInspectionActsController,
|
||||
InspectionActsController,
|
||||
],
|
||||
providers: [InspectionActsService, MobileInspectionActsService],
|
||||
})
|
||||
export class InspectionActsModule {}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Controller, Get, Param, ParseUUIDPipe, Query } from '@nestjs/common';
|
||||
import { RequirePermissions } from '../authorization/decorators/require-permissions.decorator';
|
||||
import { ListInspectionActsQueryDto } from './dto/list-inspection-acts-query.dto';
|
||||
import { MobileInspectionActsService } from './mobile-inspection-acts.service';
|
||||
|
||||
@Controller('inspection-visits/:visitId/acts/mobile')
|
||||
export class MobileInspectionActsController {
|
||||
constructor(private readonly acts: MobileInspectionActsService) {}
|
||||
|
||||
@Get()
|
||||
@RequirePermissions('inspection_acts.read')
|
||||
list(
|
||||
@Param('visitId', new ParseUUIDPipe({ version: '4' })) visitId: string,
|
||||
@Query() query: ListInspectionActsQueryDto,
|
||||
) {
|
||||
return this.acts.listForVisit(visitId, query);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
import type { ListInspectionActsQueryDto } from './dto/list-inspection-acts-query.dto';
|
||||
|
||||
/**
|
||||
* Read model intentionally kept small for the field client.
|
||||
*
|
||||
* The Android app only needs the Act identity/lifecycle, deadlines and counters to
|
||||
* open an Inspection. It must not fail because an office-document/report module is
|
||||
* unavailable or temporarily schema-drifted. The canonical office endpoints keep
|
||||
* their richer projection in InspectionActsService.
|
||||
*/
|
||||
@Injectable()
|
||||
export class MobileInspectionActsService {
|
||||
constructor(private readonly dataSource: DataSource) {}
|
||||
|
||||
async listForVisit(visitId: string, query: ListInspectionActsQueryDto) {
|
||||
const [visit] = (await this.dataSource.query(
|
||||
'SELECT id FROM inspection_visits WHERE id = $1::uuid',
|
||||
[visitId],
|
||||
)) as Array<{ id: string }>;
|
||||
if (!visit) {
|
||||
throw new NotFoundException({
|
||||
code: 'INSPECTION_VISIT_NOT_FOUND',
|
||||
message: 'Visita de inspección no encontrada',
|
||||
});
|
||||
}
|
||||
|
||||
const conditions = ['act.visit_id = $1::uuid'];
|
||||
const parameters: unknown[] = [visitId];
|
||||
const add = (value: unknown): string => {
|
||||
parameters.push(value);
|
||||
return `$${parameters.length}`;
|
||||
};
|
||||
|
||||
if (query.search?.trim()) {
|
||||
const search = add(`%${query.search.trim()}%`);
|
||||
conditions.push(`(act.code ILIKE ${search} OR act.title ILIKE ${search})`);
|
||||
}
|
||||
if (query.status) conditions.push(`act.status = ${add(query.status)}`);
|
||||
if (query.year) conditions.push(`act.act_year = ${add(query.year)}`);
|
||||
if (query.dateFrom) conditions.push(`act.occurred_at::date >= ${add(query.dateFrom)}::date`);
|
||||
if (query.dateTo) conditions.push(`act.occurred_at::date <= ${add(query.dateTo)}::date`);
|
||||
|
||||
const where = `WHERE ${conditions.join(' AND ')}`;
|
||||
const [countRow] = (await this.dataSource.query(
|
||||
`SELECT COUNT(*)::integer AS total FROM inspection_acts act ${where}`,
|
||||
parameters,
|
||||
)) as Array<{ total: number }>;
|
||||
const total = Number(countRow?.total ?? 0);
|
||||
|
||||
const limit = add(query.pageSize);
|
||||
const offset = add((query.page - 1) * query.pageSize);
|
||||
const data = await this.dataSource.query(`
|
||||
SELECT
|
||||
act.id,
|
||||
act.visit_id AS "visitId",
|
||||
act.code,
|
||||
act.status,
|
||||
act.occurred_at AS "occurredAt",
|
||||
act.title,
|
||||
act.summary,
|
||||
act.observations,
|
||||
act.urgency,
|
||||
act.deadline_days AS "deadlineDays",
|
||||
act.deadline_day_type AS "deadlineDayType",
|
||||
act.deadline_basis AS "deadlineBasis",
|
||||
act.deadline_base_at AS "deadlineBaseAt",
|
||||
act.deadline_at AS "deadlineAt",
|
||||
act.locked_at AS "lockedAt",
|
||||
act.locked_sha256 AS "lockedSha256",
|
||||
act.sealed_at AS "sealedAt",
|
||||
act.current_version AS "currentVersion",
|
||||
act.closed_at AS "closedAt",
|
||||
act.closure_sha256 AS "closureSha256",
|
||||
COALESCE((
|
||||
SELECT COUNT(*)::integer
|
||||
FROM inspection_act_assets link
|
||||
WHERE link.act_id = act.id AND link.included = true
|
||||
), 0)::integer AS "assetCount",
|
||||
COALESCE((
|
||||
SELECT COUNT(*)::integer
|
||||
FROM inspection_findings finding
|
||||
WHERE finding.act_id = act.id AND finding.status <> 'VOIDED'
|
||||
), 0)::integer AS "findingCount"
|
||||
FROM inspection_acts act
|
||||
${where}
|
||||
ORDER BY act.act_year DESC, act.act_number DESC
|
||||
LIMIT ${limit} OFFSET ${offset}
|
||||
`, parameters);
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
page: query.page,
|
||||
pageSize: query.pageSize,
|
||||
total,
|
||||
totalPages: total === 0 ? 0 : Math.ceil(total / query.pageSize),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,8 @@ function mountedRepoFile(path: string): string {
|
||||
test('F6.3 Android test cut targets production API and has a distinct installable debug version', () => {
|
||||
const gradle = mountedRepoFile('android-app/app/build.gradle.kts');
|
||||
|
||||
assert.match(gradle, /versionCode = 25/);
|
||||
assert.match(gradle, /versionName = "0\.16\.0"/);
|
||||
assert.match(gradle, /versionCode = 27/);
|
||||
assert.match(gradle, /versionName = "0\.18\.0"/);
|
||||
assert.match(gradle, /https:\/\/dhv2\.korexlabs\.com\/api\/v3\//);
|
||||
assert.match(gradle, /applicationIdSuffix = "\.debug"/);
|
||||
});
|
||||
@@ -25,4 +25,4 @@ test('F5/F6.3 field inventory exposes Other families as reviewable choices to An
|
||||
assert.match(service, /F5:SYSTEM:OTHER:%/);
|
||||
assert.match(service, /AS "isOther"/);
|
||||
assert.match(service, /isOtherFamily: family\.isOther/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import test from 'node:test';
|
||||
|
||||
function apiFile(path: string): string {
|
||||
return readFileSync(resolve(process.cwd(), path), 'utf8');
|
||||
}
|
||||
|
||||
function repoFile(path: string): string {
|
||||
return readFileSync(resolve(process.cwd(), '..', path), 'utf8');
|
||||
}
|
||||
|
||||
test('F6.4 Android Installation picker searches live and selects a concrete parent', () => {
|
||||
const screen = repoFile('android-app/app/src/main/java/com/korexlabs/dhinspeccion/ui/ModernVisitRoot.kt');
|
||||
|
||||
assert.match(screen, /LaunchedEffect\(modeName, parentSearch\)/);
|
||||
assert.match(screen, /delay\(280\)/);
|
||||
assert.match(screen, /model\.searchInventory\(parentSearch\.trim\(\), visit\.scopeAsset\?\.id\)/);
|
||||
assert.match(screen, /ElevatedCard\(onClick = \{ chooseParent\(item\) \}/);
|
||||
assert.match(screen, /model\.loadFieldTypes\(item\.id\)/);
|
||||
});
|
||||
|
||||
test('F6.4 Android field shell uses the modern theme and workspace', () => {
|
||||
const gate = repoFile('android-app/app/src/main/java/com/korexlabs/dhinspeccion/ui/LoginGate.kt');
|
||||
const theme = repoFile('android-app/app/src/main/java/com/korexlabs/dhinspeccion/ui/DhTheme.kt');
|
||||
|
||||
assert.match(gate, /DhTheme \{/);
|
||||
assert.match(gate, /model\.visit != null -> ModernVisitRoot\(model\)/);
|
||||
assert.match(theme, /RoundedCornerShape\(16\.dp\)/);
|
||||
});
|
||||
|
||||
test('F6.4 Android Act list uses a mobile read model independent from office reports', () => {
|
||||
const android = repoFile('android-app/app/src/main/java/com/korexlabs/dhinspeccion/data/MobileActs.kt');
|
||||
const controller = apiFile('src/inspection-acts/mobile-inspection-acts.controller.ts');
|
||||
const service = apiFile('src/inspection-acts/mobile-inspection-acts.service.ts');
|
||||
|
||||
assert.match(android, /inspection-visits\/\{visitId\}\/acts\/mobile/);
|
||||
assert.match(controller, /inspection-visits\/:visitId\/acts\/mobile/);
|
||||
assert.match(service, /FROM inspection_acts act/);
|
||||
assert.doesNotMatch(service, /inspection_reports/);
|
||||
assert.doesNotMatch(service, /inspection_document/);
|
||||
});
|
||||
Reference in New Issue
Block a user