Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
23880521d9 | ||
|
|
637c28dc2f | ||
|
|
fc0c62c70a | ||
|
|
3ab10b37ea | ||
|
|
c6475c851e | ||
|
|
b757bf7729 | ||
|
|
e30e5d90ea | ||
|
|
d44ae049f3 | ||
|
|
78e92970ff | ||
|
|
7fcb1d42b6 |
@@ -63,7 +63,7 @@ jobs:
|
||||
|
||||
- name: Android lint
|
||||
working-directory: android-app
|
||||
run: gradle --no-daemon :app:lintDebug
|
||||
run: gradle --no-daemon :app:lintDebug :app:lintRelease
|
||||
|
||||
- name: Print complete lint failures
|
||||
if: failure()
|
||||
@@ -130,6 +130,14 @@ jobs:
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
|
||||
- name: Upload unsigned release candidate
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: DH-Inspeccion-${{ steps.package.outputs.version }}-vc${{ steps.package.outputs.version_code }}-${{ steps.package.outputs.short_sha }}-UNSIGNED
|
||||
path: android-app/app/build/outputs/apk/release/app-release-unsigned.apk
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
|
||||
- name: Upload Android diagnostics
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
# Checklist final Android 0.19.0
|
||||
# Checklist final Android 0.19.2
|
||||
|
||||
La candidata sólo se promueve si el mismo SHA cumple:
|
||||
|
||||
- iniciar Inspección;
|
||||
- crear/abrir Acta;
|
||||
- seleccionar o crear Instalación/Subinstalación;
|
||||
- crear/abrir Acta sin pedir urgencia ni Inventario;
|
||||
- entrar a **Agregar Hallazgo** y recién allí seleccionar o crear Instalación/Subinstalación;
|
||||
- exigir GPS + fotografía para Inventario nacido en campo antes de Hallazgos;
|
||||
- registrar Hallazgos sobre el elemento seleccionado;
|
||||
- cerrar contenido del Acta y mostrar **Pendiente de firma**;
|
||||
- al cerrar el contenido, exigir Urgente/No urgente, persistir esa decisión y mostrar **Pendiente de firma**;
|
||||
- completar firma del Inspector y manifestación/firma o negativa de la empresa;
|
||||
- mostrar el Acta como **Firmada y cerrada**;
|
||||
- permitir cerrar la Inspección sólo con todas las Actas activas firmadas y cerradas;
|
||||
- no mostrar **Inventario de campo** como acción paralela de la Inspección;
|
||||
- no exponer estados internos en inglés en la interfaz de campo;
|
||||
- Android CI / RC, DH V2 CI y auditoría de dependencias en verde.
|
||||
|
||||
+39
-9
@@ -1,27 +1,28 @@
|
||||
# DH Inspección Android · release final de campo 0.19.0
|
||||
# DH Inspección Android · release final de campo 0.19.2
|
||||
|
||||
## Candidata vigente
|
||||
|
||||
- Fase funcional: **Flujo final de campo · Inspección → Acta → Hallazgos → Firma**.
|
||||
- `versionName`: **0.19.0**.
|
||||
- `versionCode`: **28**.
|
||||
- `versionName`: **0.19.2**.
|
||||
- `versionCode`: **30**.
|
||||
- Application ID release: `com.korexlabs.dhinspeccion`.
|
||||
- Application ID debug/QA: `com.korexlabs.dhinspeccion.debug`.
|
||||
- API: `https://dhv2.korexlabs.com/api/v3/`.
|
||||
- Servidor compatible de esta candidata: **API 0.29.0-2 / WEB 0.23.0-2**.
|
||||
|
||||
La variante debug es independiente de la app productiva y puede instalarse para QA/presentación sin sobrescribir una instalación release histórica.
|
||||
|
||||
## Procedimiento operativo validado
|
||||
|
||||
La APK 0.19.0 fija como recorrido principal de campo:
|
||||
La APK 0.19.2 fija como recorrido principal de campo:
|
||||
|
||||
1. **Iniciar Inspección**. Al iniciarla se habilitan Actas, Hallazgos e Inventario de campo.
|
||||
2. **Crear o abrir un Acta**. Puede haber varias Actas dentro de una misma Inspección, pero sólo una puede permanecer en elaboración al mismo tiempo.
|
||||
3. **Agregar Hallazgos** sobre una Instalación o Subinstalación seleccionada.
|
||||
1. **Iniciar Inspección**. Al iniciarla se habilita el circuito de **Actas y Hallazgos**; Inventario no es una acción independiente de la Inspección.
|
||||
2. **Crear o abrir un Acta**. Puede haber varias Actas dentro de una misma Inspección, pero sólo una puede permanecer en elaboración al mismo tiempo. La urgencia todavía no se define.
|
||||
3. **Agregar Hallazgos**. Recién desde esta acción se selecciona la Instalación/Subinstalación afectada.
|
||||
4. Si el elemento ya existe, se lo selecciona desde el Inventario del Área/Yacimiento de la Inspección.
|
||||
5. Si no existe, se da de alta desde campo sin abandonar el Acta.
|
||||
6. Un elemento nuevo debe completar **GPS + fotografía** antes de poder recibir Hallazgos.
|
||||
7. Al terminar el contenido del Acta se usa **Cerrar Acta y dejar pendiente de firma**. Desde ese momento el contenido queda inmutable y el estado visible es **Pendiente de firma**.
|
||||
7. Al terminar el contenido del Acta se elige **Urgente / No urgente** y luego se usa **Cerrar Acta y dejar pendiente de firma**. La urgencia queda fijada con el cierre; desde ese momento el contenido queda inmutable y el estado visible es **Pendiente de firma**.
|
||||
8. La firma del Inspector y la manifestación/firma o negativa de la empresa completan el Acta, que pasa a **Firmada y cerrada**.
|
||||
9. La Inspección sólo puede cerrarse cuando todas sus Actas no canceladas están firmadas y cerradas.
|
||||
|
||||
@@ -57,7 +58,7 @@ La terminología visible se simplifica:
|
||||
- `LOCKED` → **Pendiente de firma**;
|
||||
- `SEALED` → **Firmada y cerrada**.
|
||||
|
||||
Cerrar el contenido no cierra automáticamente la Inspección y tampoco obliga a terminar la firma en ese instante: puede continuarse con otra Acta. Una vez cerrado el contenido, el Acta es inmutable.
|
||||
Cerrar el contenido no cierra automáticamente la Inspección y tampoco obliga a terminar la firma en ese instante: puede continuarse con otra Acta. La urgencia se decide en ese cierre, nunca al crear el borrador. Una vez cerrado el contenido, el Acta es inmutable.
|
||||
|
||||
Después de la firma/cierre definitivo se mantiene el circuito documental existente: PDF del Acta e informe INF editable (DOCX) para oficina.
|
||||
|
||||
@@ -95,3 +96,32 @@ Antes de distribuir una APK productiva:
|
||||
- realizar actualización sobre al menos una tablet con la versión productiva anterior cuando corresponda;
|
||||
- ejecutar smoke funcional: ingreso, iniciar Inspección, crear Acta, seleccionar/crear Instalación o Subinstalación, GPS/foto, Hallazgo, cerrar Acta → Pendiente de firma, firma/manifestación, cierre de Acta y cierre de Inspección;
|
||||
- registrar el SHA Git y SHA-256 de la APK distribuida.
|
||||
|
||||
## Revisión 0.19.1
|
||||
|
||||
- Renovación de sesión coordinada entre los cuatro clientes API; no cierra sesión por pérdida de red, HTTP 429/500 o cancelación.
|
||||
- Una respuesta tardía no puede restaurar una sesión cerrada ni usar la de otro inspector.
|
||||
- Guardia de escrituras contra doble toque y conteo correcto de operaciones pendientes.
|
||||
- Búsquedas descartan respuestas antiguas. Cambio de inspección limpia el Acta anterior.
|
||||
- Mensajes visibles de permisos/GPS en evidencia y respeto de barras de sistema/teclado.
|
||||
- Diez nuevas pruebas de comportamiento sobre sesión y concurrencia.
|
||||
|
||||
### Alcance real
|
||||
|
||||
Esta candidata requiere conexión. No implementa trabajo offline ni cola persistente de sincronización; un fallo de red no equivale a guardado. Tras un timeout de escritura debe verificarse el registro antes de repetir. No se presenta el artefacto debug como una release productiva. La firma histórica y el smoke en tablet siguen siendo requisitos para distribuir la release final.
|
||||
|
||||
### Segunda pasada funcional
|
||||
|
||||
- Coordenadas normalizadas al contrato API (6 decimales, precisión 3).
|
||||
- Yacimiento seleccionable para Hallazgos y como padre explícito de nuevas Instalaciones. Se elimina el fallback que podía presentar un tipo Yacimiento como alta de Instalación.
|
||||
- Formulario Datos técnicos sobre el elemento seleccionado: carga y guarda las definiciones/valores por familia mediante los endpoints existentes del Dashboard; valida obligatorios, números, Sí/No, fechas y opciones. Es un paso separado del alta estructural y GPS/foto.
|
||||
- Se agregan siete pruebas para coordenadas y valores técnicos.
|
||||
|
||||
|
||||
## Revisión 0.19.2 · flujo conceptual corregido
|
||||
|
||||
- Se elimina **Inventario de campo** como acción independiente de la pantalla de Inspección.
|
||||
- El alta o selección de Inventario existe únicamente dentro de **Agregar Hallazgo**.
|
||||
- El borrador de Acta nace vacío, sin Inventario y sin urgencia predeterminada.
|
||||
- La urgencia se exige al cerrar el Acta y se persiste en la misma operación que la vuelve inmutable.
|
||||
- `inspection_acts.urgency` puede quedar pendiente durante el borrador; el bloqueo exige la decisión y calcula el vencimiento desde allí.
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# DH Android 0.19.1 · revisión de candidata
|
||||
|
||||
## Idea funcional verificada contra código y API
|
||||
|
||||
La app es la herramienta del inspector en campo. Oficina administra territorio, operadoras, clasificaciones, campos y catálogo; la APK consulta esas fuentes. Una Inspección contiene varias Actas, con una sola en elaboración simultánea. El Hallazgo pertenece al Acta y al elemento seleccionado. Cerrar contenido lo deja inmutable y pendiente de firma. Firma del inspector y manifestación/firma o negativa de empresa permiten sellar el Acta. La Inspección exige todas sus Actas activas selladas.
|
||||
|
||||
Yacimiento, Instalación y Subinstalación son destinos de Hallazgos. Una Instalación nueva debe crearse dentro de un Yacimiento y una Subinstalación dentro de una Instalación compatible. El inventario nacido en campo necesita GPS y foto antes del Hallazgo.
|
||||
|
||||
## Hallazgos corregidos
|
||||
|
||||
| Problema observado | Corrección |
|
||||
| --- | --- |
|
||||
| Cuatro clientes renovaban por separado la misma sesión | Coordinador compartido; protege rotación, logout y cambio de usuario |
|
||||
| Cortes de red durante refresh borraban la sesión | Sólo una respuesta 401 de la sesión vigente la invalida |
|
||||
| Operaciones solapadas liberaban ocupado antes de terminar | Conteo de pendientes y rechazo del segundo guardado |
|
||||
| Respuestas de búsquedas antiguas sobrescribían resultados recientes | Generación de búsqueda y verificación del ID de inspección |
|
||||
| Un Acta anterior podía persistir al cambiar de inspección | Limpieza de estado de Acta al abrir otra inspección |
|
||||
| Coordenadas crudas excedían decimales admitidos | Normalización 6 decimales para coordenadas y 3 para precisión |
|
||||
| Inventario móvil ocultaba Yacimientos | Selección para Hallazgos y alta de Instalación dentro de Yacimiento |
|
||||
| Alta de Instalación podía adoptar otro tipo por fallback | Eliminado; pide elegir el Yacimiento padre correcto |
|
||||
| Datos técnicos por familia no estaban editables | Formulario conectado a technical-values; mismos campos de oficina |
|
||||
| Fallos de GPS/permisos en evidencia sin mensaje | Error visible y accionable |
|
||||
| Barras del sistema/teclado podían tapar controles | Insets de sistema y teclado en la raíz |
|
||||
|
||||
## Evidencia automática
|
||||
|
||||
25 pruebas Android: 8 contratos existentes y 17 pruebas nuevas de comportamiento (sesión 7, concurrencia 3, GPS 3, campos técnicos 4). Lint debug/release y compilación debug/release en workflow Android. CI general comprueba API, WEB, scripts y migraciones; la auditoría de dependencias se ejecuta separadamente. Consultar las ejecuciones del SHA de la entrega, no sólo un resultado anterior.
|
||||
|
||||
## Límites de esta candidata
|
||||
|
||||
- Requiere conexión. No existe cola persistente offline ni resolución de conflictos sin señal.
|
||||
- Un timeout de escritura puede ocurrir después de guardar en servidor. Revisar el registro antes de repetir; no se afirma idempotencia general de todas las escrituras.
|
||||
- Los datos técnicos por familia se completan en un paso separado tras seleccionar/crear el elemento. GPS/foto continúa siendo la barrera de Hallazgos del servidor.
|
||||
- No se ejecutó aceptación en tablet física: quedan por comprobar cámara, GPS, biometría, rotación/recreación de actividad, firmas y actualización sobre la APK instalada.
|
||||
- La release compila sin firma. Se requiere la clave histórica y su certificado de referencia para distribuir una actualización productiva. No crear otra clave como sustituto.
|
||||
- La candidata debug usa com.korexlabs.dhinspeccion.debug y no reemplaza la app productiva. La compatibilidad con una debug anterior depende también de su certificado; no desinstalar una app con información pendiente sin revisar antes.
|
||||
|
||||
## Recorrido de aceptación en tablet
|
||||
|
||||
1. Ingresar con inspector y cargar inspecciones asignadas.
|
||||
2. Iniciar una inspección, crear Acta, seleccionar Yacimiento/Instalación/Subinstalación.
|
||||
3. Crear Instalación bajo Yacimiento y Subinstalación compatible; probar GPS permitido/denegado y foto tomada/cancelada.
|
||||
4. Completar campos técnicos requeridos, incluyendo No booleano, decimal con coma, fecha y opción de lista; volver a abrir para comprobar persistencia.
|
||||
5. Crear Hallazgo catalogado y OTROS, adjuntar evidencia.
|
||||
6. Cerrar contenido, comprobar inmutabilidad y estado Pendiente de firma.
|
||||
7. Registrar firmas o negativa de empresa; sellar Acta.
|
||||
8. Crear otra Acta, comprobar que una pendiente impide cerrar la Inspección; completar y cerrar.
|
||||
9. Cortar conexión y recuperarla: errores visibles, sin pérdida de sesión por red ni falso aviso de guardado.
|
||||
10. Verificar en Dashboard los mismos registros y documentos.
|
||||
@@ -12,8 +12,8 @@ android {
|
||||
applicationId = "com.korexlabs.dhinspeccion"
|
||||
minSdk = 26
|
||||
targetSdk = 36
|
||||
versionCode = 28
|
||||
versionName = "0.19.0"
|
||||
versionCode = 30
|
||||
versionName = "0.19.2"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
vectorDrawables.useSupportLibrary = true
|
||||
|
||||
@@ -6,6 +6,7 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.korexlabs.dhinspeccion.data.FieldCoordinates
|
||||
import com.korexlabs.dhinspeccion.data.CreateFieldFindingRequest
|
||||
import com.korexlabs.dhinspeccion.data.CreateFieldInventoryRequest
|
||||
import com.korexlabs.dhinspeccion.data.DhRepository
|
||||
@@ -24,11 +25,14 @@ import com.korexlabs.dhinspeccion.data.MobileResponsibleRequest
|
||||
import com.korexlabs.dhinspeccion.data.StoredSession
|
||||
import com.korexlabs.dhinspeccion.data.VisitDetail
|
||||
import com.korexlabs.dhinspeccion.data.VisitSummary
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
import java.time.Instant
|
||||
|
||||
class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
private val operations = OperationTracker()
|
||||
private var inventorySearchGeneration = 0
|
||||
private val repository = DhRepository(application)
|
||||
private val findingsRepository = FieldFindingsRepository(application)
|
||||
private val actsRepository = MobileActsRepository(application)
|
||||
@@ -84,7 +88,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
error = "Ingresá usuario y contraseña."
|
||||
return
|
||||
}
|
||||
launchBusy {
|
||||
launchBusy(mutation = true) {
|
||||
session = repository.login(identifier, password)
|
||||
notice = "Sesión iniciada."
|
||||
loadVisitsInternal()
|
||||
@@ -113,7 +117,9 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
|
||||
fun openVisit(id: String) = launchBusy {
|
||||
visit = repository.visit(id)
|
||||
val loadedVisit = repository.visit(id)
|
||||
clearActState()
|
||||
visit = loadedVisit
|
||||
inventory = emptyList()
|
||||
inventoryParentId = visit?.scopeAsset?.id ?: visit?.operationalArea?.id
|
||||
fieldTypes = emptyList()
|
||||
@@ -123,6 +129,8 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
|
||||
fun closeVisitView() {
|
||||
if (busy) return
|
||||
inventorySearchGeneration += 1
|
||||
visit = null
|
||||
inventory = emptyList()
|
||||
inventoryParentId = null
|
||||
@@ -135,7 +143,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
|
||||
fun startVisit() {
|
||||
val id = visit?.id ?: return
|
||||
launchBusy {
|
||||
launchBusy(mutation = true) {
|
||||
visit = repository.startVisit(id)
|
||||
inventoryParentId = visit?.scopeAsset?.id ?: visit?.operationalArea?.id
|
||||
notice = "Inspección iniciada."
|
||||
@@ -157,45 +165,31 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
}
|
||||
|
||||
fun createActForSelectedInventory(urgency: String = "NON_URGENT") {
|
||||
fun createAct() {
|
||||
val currentVisit = visit ?: return
|
||||
val asset = selectedFieldAsset?.asset
|
||||
if (currentVisit.status != "IN_PROGRESS") {
|
||||
error = "La Inspección debe estar en curso para crear un Acta."
|
||||
return
|
||||
}
|
||||
if (urgency !in setOf("URGENT", "NON_URGENT")) {
|
||||
error = "Elegí si el Acta es urgente o no urgente."
|
||||
return
|
||||
}
|
||||
if (acts.any { it.status == "DRAFT" }) {
|
||||
error = "Ya existe un Acta en elaboración. Cerrala o cancelala antes de crear la siguiente."
|
||||
return
|
||||
}
|
||||
launchBusy {
|
||||
val created = actsRepository.create(
|
||||
currentVisit.id,
|
||||
asset?.id,
|
||||
currentVisit.code,
|
||||
urgency,
|
||||
)
|
||||
launchBusy(mutation = true) {
|
||||
val created = actsRepository.create(currentVisit.id, currentVisit.code)
|
||||
selectedAct = created
|
||||
actClosure = actsRepository.closure(created.id)
|
||||
loadActsInternal(currentVisit.id, selectDraft = false)
|
||||
val urgencyLabel = if (urgency == "URGENT") "urgente" else "no urgente"
|
||||
notice = "${created.code} creada como $urgencyLabel. Los Hallazgos nuevos quedarán vinculados explícitamente a esta Acta."
|
||||
if (asset != null && selectedFieldAsset?.capture?.readyForFinding == true) {
|
||||
loadFindingOptionsInternal(currentVisit.id, asset.id, created.id)
|
||||
}
|
||||
notice = "${created.code} creada. La urgencia se define recién al cerrar el Acta; los Hallazgos se agregan desde su propio flujo."
|
||||
}
|
||||
}
|
||||
|
||||
fun createAct(urgency: String = "NON_URGENT") = createActForSelectedInventory(urgency)
|
||||
|
||||
fun searchInventory(search: String, parentId: String? = null) {
|
||||
val currentVisit = visit ?: return
|
||||
val generation = ++inventorySearchGeneration
|
||||
launchBusy {
|
||||
inventory = repository.fieldInventory(currentVisit.id, search, parentId).data
|
||||
val result = repository.fieldInventory(currentVisit.id, search, parentId).data
|
||||
if (generation == inventorySearchGeneration && visit?.id == currentVisit.id) inventory = result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,6 +197,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
val currentVisit = visit ?: return
|
||||
launchBusy {
|
||||
val effectiveParentId = parentId ?: currentVisit.scopeAsset?.id ?: currentVisit.operationalArea?.id
|
||||
inventorySearchGeneration += 1
|
||||
inventoryParentId = effectiveParentId
|
||||
fieldTypes = repository.fieldTypes(currentVisit.id, parentId).data
|
||||
inventory = repository.fieldInventory(currentVisit.id, null, effectiveParentId).data
|
||||
@@ -216,7 +211,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
|
||||
fun selectExisting(item: FieldInventoryItem) {
|
||||
val visitId = visit?.id ?: return
|
||||
launchBusy {
|
||||
launchBusy(mutation = true) {
|
||||
selectedFieldAsset = repository.selectFieldAsset(visitId, item.id)
|
||||
notice = "Inventario agregado a la Inspección."
|
||||
reloadCurrentInventory(visitId)
|
||||
@@ -252,7 +247,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
error = "Elegí una clasificación técnica o la opción Otro / no catalogado."
|
||||
return
|
||||
}
|
||||
launchBusy {
|
||||
launchBusy(mutation = true) {
|
||||
val request = CreateFieldInventoryRequest(
|
||||
typeId = type.id,
|
||||
parentId = parentId,
|
||||
@@ -261,9 +256,9 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
commonName = commonName?.trim()?.takeIf { it.isNotBlank() },
|
||||
description = description?.trim()?.takeIf { it.isNotBlank() },
|
||||
attributes = attributes,
|
||||
deviceLatitude = latitude,
|
||||
deviceLongitude = longitude,
|
||||
deviceAccuracyM = accuracyM,
|
||||
deviceLatitude = FieldCoordinates.latitude(latitude),
|
||||
deviceLongitude = FieldCoordinates.longitude(longitude),
|
||||
deviceAccuracyM = accuracyM?.let(FieldCoordinates::accuracy),
|
||||
deviceCapturedAt = Instant.now().toString(),
|
||||
)
|
||||
selectedFieldAsset = repository.createFieldAsset(visitId, request)
|
||||
@@ -283,7 +278,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
error = "Explicá brevemente por qué se trata de un duplicado."
|
||||
return
|
||||
}
|
||||
launchBusy {
|
||||
launchBusy(mutation = true) {
|
||||
val result = repository.mergeFieldAsset(
|
||||
visitId = visitId,
|
||||
assetId = source.id,
|
||||
@@ -310,7 +305,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
) {
|
||||
val visitId = visit?.id ?: return
|
||||
val asset = selectedFieldAsset?.asset ?: return
|
||||
launchBusy {
|
||||
launchBusy(mutation = true) {
|
||||
val response = repository.uploadFieldPhoto(
|
||||
visitId = visitId,
|
||||
assetId = asset.id,
|
||||
@@ -345,7 +340,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
error = "Creá o seleccioná el Acta en elaboración antes de registrar Hallazgos."
|
||||
return
|
||||
}
|
||||
launchBusy {
|
||||
launchBusy(mutation = true) {
|
||||
selectedAct = actsRepository.ensureAsset(draft.id, assetId)
|
||||
loadActsInternal(visitId, selectDraft = false)
|
||||
loadFindingOptionsInternal(visitId, assetId, draft.id)
|
||||
@@ -379,7 +374,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
error = "La gravedad debe estar entre 1 y 10."
|
||||
return
|
||||
}
|
||||
launchBusy {
|
||||
launchBusy(mutation = true) {
|
||||
selectedAct = actsRepository.ensureAsset(actId, assetId)
|
||||
val response = findingsRepository.create(
|
||||
visitId,
|
||||
@@ -410,7 +405,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
title: String? = null,
|
||||
description: String? = null,
|
||||
) {
|
||||
launchBusy {
|
||||
launchBusy(mutation = true) {
|
||||
findingsRepository.uploadObservationPhoto(
|
||||
findingId = findingId,
|
||||
file = file,
|
||||
@@ -442,7 +437,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
error = "Completá nombre, documento y cargo del responsable de la empresa."
|
||||
return
|
||||
}
|
||||
launchBusy {
|
||||
launchBusy(mutation = true) {
|
||||
actClosure = actsRepository.setResponsible(
|
||||
actId,
|
||||
MobileResponsibleRequest(
|
||||
@@ -465,7 +460,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
error = "Indicá un motivo de ausencia de al menos 10 caracteres."
|
||||
return
|
||||
}
|
||||
launchBusy {
|
||||
launchBusy(mutation = true) {
|
||||
actClosure = actsRepository.setResponsible(
|
||||
actId,
|
||||
MobileResponsibleRequest(
|
||||
@@ -477,12 +472,17 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
}
|
||||
|
||||
fun prepareSelectedAct() {
|
||||
fun prepareSelectedAct(urgency: String) {
|
||||
val actId = selectedAct?.id ?: return
|
||||
launchBusy {
|
||||
actClosure = actsRepository.lock(actId)
|
||||
if (urgency !in setOf("URGENT", "NON_URGENT")) {
|
||||
error = "Definí la urgencia antes de cerrar el Acta."
|
||||
return
|
||||
}
|
||||
launchBusy(mutation = true) {
|
||||
actClosure = actsRepository.lock(actId, urgency)
|
||||
refreshSelectedActInternal(actId)
|
||||
notice = "Acta cerrada y pendiente de firma. Su contenido quedó inmutable; las firmas y manifestaciones pueden completarse a continuación."
|
||||
val urgencyLabel = if (urgency == "URGENT") "urgente" else "no urgente"
|
||||
notice = "Acta cerrada como $urgencyLabel y pendiente de firma. Su contenido quedó inmutable."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -497,7 +497,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
accuracyM: Double?,
|
||||
) {
|
||||
val actId = selectedAct?.id ?: return
|
||||
launchBusy {
|
||||
launchBusy(mutation = true) {
|
||||
actClosure = actsRepository.signInspector(actId, png, latitude, longitude, accuracyM)
|
||||
notice = "Firma del inspector incorporada al Acta."
|
||||
}
|
||||
@@ -512,7 +512,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
statement: String?,
|
||||
) {
|
||||
val actId = selectedAct?.id ?: return
|
||||
launchBusy {
|
||||
launchBusy(mutation = true) {
|
||||
actClosure = actsRepository.signCompany(
|
||||
actId, png, latitude, longitude, accuracyM, manifestation, statement,
|
||||
)
|
||||
@@ -534,7 +534,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
error = "Indicá un motivo de al menos 10 caracteres."
|
||||
return
|
||||
}
|
||||
launchBusy {
|
||||
launchBusy(mutation = true) {
|
||||
actClosure = actsRepository.companyOutcome(actId, status, reason)
|
||||
notice = "Negativa a firmar asentada."
|
||||
}
|
||||
@@ -543,7 +543,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
fun closeSelectedAct() {
|
||||
val currentVisit = visit ?: return
|
||||
val actId = selectedAct?.id ?: return
|
||||
launchBusy {
|
||||
launchBusy(mutation = true) {
|
||||
actClosure = actsRepository.seal(actId)
|
||||
refreshSelectedActInternal(actId)
|
||||
loadActsInternal(currentVisit.id, selectDraft = false)
|
||||
@@ -554,7 +554,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
|
||||
fun closeInspection() {
|
||||
val visitId = visit?.id ?: return
|
||||
launchBusy {
|
||||
launchBusy(mutation = true) {
|
||||
visit = actsRepository.closeVisit(visitId)
|
||||
loadVisitsInternal()
|
||||
notice = "Inspección cerrada. Todas sus Actas quedaron firmadas y disponibles para el circuito de oficina."
|
||||
@@ -637,17 +637,21 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
fieldFindingEvidence = emptyMap()
|
||||
}
|
||||
|
||||
private fun launchBusy(block: suspend () -> Unit) {
|
||||
private fun launchBusy(mutation: Boolean = false, block: suspend () -> Unit) {
|
||||
if (!operations.begin(mutation)) return
|
||||
busy = operations.busy
|
||||
viewModelScope.launch {
|
||||
busy = true
|
||||
error = null
|
||||
try {
|
||||
block()
|
||||
} catch (cancelled: CancellationException) {
|
||||
throw cancelled
|
||||
} catch (throwable: Throwable) {
|
||||
error = DhRepository.humanError(throwable)
|
||||
if (repository.currentSession() == null) session = null
|
||||
} finally {
|
||||
busy = false
|
||||
operations.end()
|
||||
busy = operations.busy
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.korexlabs.dhinspeccion
|
||||
|
||||
/** Main-thread gate: reads may overlap; a second write is never queued by a double tap. */
|
||||
internal class OperationTracker {
|
||||
private var pending = 0
|
||||
val busy: Boolean get() = pending > 0
|
||||
fun begin(mutation: Boolean): Boolean {
|
||||
if (mutation && busy) return false
|
||||
pending += 1
|
||||
return true
|
||||
}
|
||||
fun end() {
|
||||
check(pending > 0)
|
||||
pending -= 1
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,6 @@ import android.util.Base64
|
||||
import com.korexlabs.dhinspeccion.BuildConfig
|
||||
import com.squareup.moshi.Moshi
|
||||
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.OkHttpClient
|
||||
@@ -451,7 +449,6 @@ class SecureSessionStore(context: Context) {
|
||||
|
||||
class DhRepository(context: Context) {
|
||||
private val store = SecureSessionStore(context.applicationContext)
|
||||
private val refreshMutex = Mutex()
|
||||
private val moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()
|
||||
private val api: DhApi = Retrofit.Builder()
|
||||
.baseUrl(BuildConfig.API_BASE_URL)
|
||||
@@ -530,13 +527,13 @@ class DhRepository(context: Context) {
|
||||
visitId = visitId,
|
||||
assetId = assetId,
|
||||
file = part,
|
||||
latitude = latitude.toString().toRequestBody(text),
|
||||
longitude = longitude.toString().toRequestBody(text),
|
||||
accuracy = accuracyM?.toString()?.toRequestBody(text),
|
||||
latitude = FieldCoordinates.latitude(latitude).toString().toRequestBody(text),
|
||||
longitude = FieldCoordinates.longitude(longitude).toString().toRequestBody(text),
|
||||
accuracy = accuracyM?.let(FieldCoordinates::accuracy)?.toString()?.toRequestBody(text),
|
||||
capturedAt = capturedAt.toRequestBody(text),
|
||||
deviceLabel = "DH Android".toRequestBody(text),
|
||||
exifLatitude = latitude.toString().toRequestBody(text),
|
||||
exifLongitude = longitude.toString().toRequestBody(text),
|
||||
exifLatitude = FieldCoordinates.latitude(latitude).toString().toRequestBody(text),
|
||||
exifLongitude = FieldCoordinates.longitude(longitude).toString().toRequestBody(text),
|
||||
exifCapturedAt = capturedAt.toRequestBody(text),
|
||||
)
|
||||
}
|
||||
@@ -548,23 +545,19 @@ class DhRepository(context: Context) {
|
||||
} catch (error: HttpException) {
|
||||
if (error.code() != 401) throw error
|
||||
}
|
||||
session = refresh(session.refreshToken)
|
||||
session = refresh(session)
|
||||
return block(session)
|
||||
}
|
||||
|
||||
private suspend fun refresh(previousRefreshToken: String): StoredSession = refreshMutex.withLock {
|
||||
val latest = store.load() ?: throw IllegalStateException("Sesión no iniciada")
|
||||
if (latest.refreshToken != previousRefreshToken) return@withLock latest
|
||||
try {
|
||||
store.save(api.refresh(RefreshRequest(previousRefreshToken)))
|
||||
} catch (error: Throwable) {
|
||||
store.clear()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
private suspend fun refresh(previous: StoredSession): StoredSession =
|
||||
MobileSessionCoordinator.refresh(previous, store::load, store::save, store::clear, api::refresh)
|
||||
|
||||
|
||||
companion object {
|
||||
fun humanError(error: Throwable): String {
|
||||
if (error is java.io.IOException) {
|
||||
return "No se pudo conectar. Revisá la señal. Si estabas guardando, comprobá el registro antes de reintentar."
|
||||
}
|
||||
if (error is HttpException) {
|
||||
val body = runCatching { error.response()?.errorBody()?.string() }.getOrNull()
|
||||
val message = runCatching { JSONObject(body.orEmpty()).optString("message") }.getOrNull()
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.korexlabs.dhinspeccion.data
|
||||
|
||||
import java.math.BigDecimal
|
||||
import java.math.RoundingMode
|
||||
|
||||
internal object FieldCoordinates {
|
||||
private fun normalized(value: Double, scale: Int, min: Double, max: Double): Double {
|
||||
require(value.isFinite() && value in min..max) { "La ubicación GPS recibida no es válida." }
|
||||
return BigDecimal.valueOf(value).setScale(scale, RoundingMode.HALF_UP).toDouble()
|
||||
}
|
||||
fun latitude(value: Double) = normalized(value, 6, -90.0, 90.0)
|
||||
fun longitude(value: Double) = normalized(value, 6, -180.0, 180.0)
|
||||
fun accuracy(value: Double) = normalized(value, 3, 0.0, 100000.0)
|
||||
}
|
||||
+7
-17
@@ -4,8 +4,6 @@ import android.content.Context
|
||||
import com.korexlabs.dhinspeccion.BuildConfig
|
||||
import com.squareup.moshi.Moshi
|
||||
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.OkHttpClient
|
||||
@@ -176,7 +174,6 @@ private interface FieldFindingsApi {
|
||||
*/
|
||||
class FieldFindingsRepository(context: Context) {
|
||||
private val store = SecureSessionStore(context.applicationContext)
|
||||
private val refreshMutex = Mutex()
|
||||
private val moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()
|
||||
private val api: FieldFindingsApi = Retrofit.Builder()
|
||||
.baseUrl(BuildConfig.API_BASE_URL)
|
||||
@@ -227,9 +224,9 @@ class FieldFindingsRepository(context: Context) {
|
||||
title = title?.trim()?.takeIf { it.isNotBlank() }?.toRequestBody(text),
|
||||
description = description?.trim()?.takeIf { it.isNotBlank() }?.toRequestBody(text),
|
||||
capturedAt = capturedAt.toRequestBody(text),
|
||||
latitude = latitude.toString().toRequestBody(text),
|
||||
longitude = longitude.toString().toRequestBody(text),
|
||||
accuracyM = accuracyM?.toString()?.toRequestBody(text),
|
||||
latitude = FieldCoordinates.latitude(latitude).toString().toRequestBody(text),
|
||||
longitude = FieldCoordinates.longitude(longitude).toString().toRequestBody(text),
|
||||
accuracyM = accuracyM?.let(FieldCoordinates::accuracy)?.toString()?.toRequestBody(text),
|
||||
deviceLabel = "DH Android".toRequestBody(text),
|
||||
)
|
||||
}
|
||||
@@ -241,18 +238,11 @@ class FieldFindingsRepository(context: Context) {
|
||||
} catch (error: HttpException) {
|
||||
if (error.code() != 401) throw error
|
||||
}
|
||||
session = refresh(session.refreshToken)
|
||||
session = refresh(session)
|
||||
return block(session)
|
||||
}
|
||||
|
||||
private suspend fun refresh(previousRefreshToken: String): StoredSession = refreshMutex.withLock {
|
||||
val latest = store.load() ?: throw IllegalStateException("Sesión no iniciada")
|
||||
if (latest.refreshToken != previousRefreshToken) return@withLock latest
|
||||
try {
|
||||
store.save(api.refresh(RefreshRequest(previousRefreshToken)))
|
||||
} catch (error: Throwable) {
|
||||
store.clear()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
private suspend fun refresh(previous: StoredSession): StoredSession =
|
||||
MobileSessionCoordinator.refresh(previous, store::load, store::save, store::clear, api::refresh)
|
||||
|
||||
}
|
||||
|
||||
@@ -4,8 +4,6 @@ import android.content.Context
|
||||
import com.korexlabs.dhinspeccion.BuildConfig
|
||||
import com.squareup.moshi.Moshi
|
||||
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.OkHttpClient
|
||||
@@ -37,7 +35,7 @@ data class MobileActSummary(
|
||||
val title: String,
|
||||
val summary: String,
|
||||
val observations: String? = null,
|
||||
val urgency: String = "NON_URGENT",
|
||||
val urgency: String? = null,
|
||||
val deadlineDays: Int? = null,
|
||||
val deadlineDayType: String? = null,
|
||||
val deadlineBasis: String? = null,
|
||||
@@ -62,7 +60,7 @@ data class MobileActDetail(
|
||||
val title: String,
|
||||
val summary: String,
|
||||
val observations: String? = null,
|
||||
val urgency: String = "NON_URGENT",
|
||||
val urgency: String? = null,
|
||||
val deadlineDays: Int? = null,
|
||||
val deadlineDayType: String? = null,
|
||||
val deadlineBasis: String? = null,
|
||||
@@ -93,13 +91,16 @@ data class MobileActListResponse(
|
||||
|
||||
data class CreateMobileActRequest(
|
||||
val occurredAt: String,
|
||||
val urgency: String,
|
||||
val title: String,
|
||||
val summary: String,
|
||||
val observations: String? = null,
|
||||
val assetIds: List<String>,
|
||||
)
|
||||
|
||||
data class PrepareMobileActRequest(
|
||||
val urgency: String,
|
||||
)
|
||||
|
||||
data class UpdateMobileActRequest(
|
||||
val assetIds: List<String>,
|
||||
)
|
||||
@@ -132,7 +133,7 @@ data class MobileActClosureHeader(
|
||||
val code: String,
|
||||
val status: String,
|
||||
val visitId: String,
|
||||
val urgency: String = "NON_URGENT",
|
||||
val urgency: String? = null,
|
||||
val deadlineDays: Int? = null,
|
||||
val deadlineDayType: String? = null,
|
||||
val deadlineBasis: String? = null,
|
||||
@@ -251,6 +252,7 @@ private interface MobileActsApi {
|
||||
suspend fun lock(
|
||||
@Header("Authorization") authorization: String,
|
||||
@Path("actId") actId: String,
|
||||
@Body request: PrepareMobileActRequest,
|
||||
): MobileActClosure
|
||||
|
||||
@Multipart
|
||||
@@ -310,7 +312,6 @@ private interface MobileActsApi {
|
||||
|
||||
class MobileActsRepository(context: Context) {
|
||||
private val store = SecureSessionStore(context.applicationContext)
|
||||
private val refreshMutex = Mutex()
|
||||
private val moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()
|
||||
private val api: MobileActsApi = Retrofit.Builder()
|
||||
.baseUrl(BuildConfig.API_BASE_URL)
|
||||
@@ -329,19 +330,16 @@ class MobileActsRepository(context: Context) {
|
||||
|
||||
suspend fun create(
|
||||
visitId: String,
|
||||
assetId: String? = null,
|
||||
visitCode: String,
|
||||
urgency: String = "NON_URGENT",
|
||||
): MobileActDetail = authorized { session ->
|
||||
api.createAct(
|
||||
"Bearer ${session.accessToken}",
|
||||
visitId,
|
||||
CreateMobileActRequest(
|
||||
occurredAt = Instant.now().toString(),
|
||||
urgency = urgency,
|
||||
title = "Acta de inspección $visitCode",
|
||||
summary = "Acta de inspección en curso. Los Hallazgos y observaciones se incorporan de forma trazable durante la inspección.",
|
||||
assetIds = listOfNotNull(assetId),
|
||||
assetIds = emptyList(),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -363,8 +361,8 @@ class MobileActsRepository(context: Context) {
|
||||
api.responsible("Bearer ${session.accessToken}", actId, request)
|
||||
}
|
||||
|
||||
suspend fun lock(actId: String): MobileActClosure = authorized { session ->
|
||||
api.lock("Bearer ${session.accessToken}", actId)
|
||||
suspend fun lock(actId: String, urgency: String): MobileActClosure = authorized { session ->
|
||||
api.lock("Bearer ${session.accessToken}", actId, PrepareMobileActRequest(urgency))
|
||||
}
|
||||
|
||||
suspend fun signInspector(
|
||||
@@ -429,9 +427,9 @@ class MobileActsRepository(context: Context) {
|
||||
val consent = "true".toRequestBody(text)
|
||||
val signedAt = Instant.now().toString().toRequestBody(text)
|
||||
val device = "DH Android".toRequestBody(text)
|
||||
val lat = latitude?.toString()?.toRequestBody(text)
|
||||
val lon = longitude?.toString()?.toRequestBody(text)
|
||||
val accuracy = accuracyM?.toString()?.toRequestBody(text)
|
||||
val lat = latitude?.let(FieldCoordinates::latitude)?.toString()?.toRequestBody(text)
|
||||
val lon = longitude?.let(FieldCoordinates::longitude)?.toString()?.toRequestBody(text)
|
||||
val accuracy = accuracyM?.let(FieldCoordinates::accuracy)?.toString()?.toRequestBody(text)
|
||||
if (company) {
|
||||
api.signCompany(
|
||||
"Bearer ${session.accessToken}", actId, file, consent, signedAt,
|
||||
@@ -454,18 +452,11 @@ class MobileActsRepository(context: Context) {
|
||||
} catch (error: HttpException) {
|
||||
if (error.code() != 401) throw error
|
||||
}
|
||||
session = refresh(session.refreshToken)
|
||||
session = refresh(session)
|
||||
return block(session)
|
||||
}
|
||||
|
||||
private suspend fun refresh(previousRefreshToken: String): StoredSession = refreshMutex.withLock {
|
||||
val latest = store.load() ?: throw IllegalStateException("Sesión no iniciada")
|
||||
if (latest.refreshToken != previousRefreshToken) return@withLock latest
|
||||
try {
|
||||
store.save(api.refresh(RefreshRequest(previousRefreshToken)))
|
||||
} catch (error: Throwable) {
|
||||
store.clear()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
private suspend fun refresh(previous: StoredSession): StoredSession =
|
||||
MobileSessionCoordinator.refresh(previous, store::load, store::save, store::clear, api::refresh)
|
||||
|
||||
}
|
||||
|
||||
+4
-14
@@ -4,8 +4,6 @@ import android.content.Context
|
||||
import com.korexlabs.dhinspeccion.BuildConfig
|
||||
import com.squareup.moshi.Moshi
|
||||
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import okhttp3.OkHttpClient
|
||||
import retrofit2.HttpException
|
||||
import retrofit2.Retrofit
|
||||
@@ -55,7 +53,6 @@ private interface MobileInspectionOpenApi {
|
||||
|
||||
class MobileInspectionOpenRepository(context: Context) {
|
||||
private val store = SecureSessionStore(context.applicationContext)
|
||||
private val refreshMutex = Mutex()
|
||||
private val moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()
|
||||
private val api: MobileInspectionOpenApi = Retrofit.Builder()
|
||||
.baseUrl(BuildConfig.API_BASE_URL)
|
||||
@@ -86,18 +83,11 @@ class MobileInspectionOpenRepository(context: Context) {
|
||||
} catch (error: HttpException) {
|
||||
if (error.code() != 401) throw error
|
||||
}
|
||||
session = refresh(session.refreshToken)
|
||||
session = refresh(session)
|
||||
return block(session)
|
||||
}
|
||||
|
||||
private suspend fun refresh(previousRefreshToken: String): StoredSession = refreshMutex.withLock {
|
||||
val latest = store.load() ?: throw IllegalStateException("Sesión no iniciada")
|
||||
if (latest.refreshToken != previousRefreshToken) return@withLock latest
|
||||
try {
|
||||
store.save(api.refresh(RefreshRequest(previousRefreshToken)))
|
||||
} catch (error: Throwable) {
|
||||
store.clear()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
private suspend fun refresh(previous: StoredSession): StoredSession =
|
||||
MobileSessionCoordinator.refresh(previous, store::load, store::save, store::clear, api::refresh)
|
||||
|
||||
}
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.korexlabs.dhinspeccion.data
|
||||
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import retrofit2.HttpException
|
||||
|
||||
/** One refresh lock for every API client sharing the encrypted session. */
|
||||
internal object MobileSessionCoordinator {
|
||||
private val mutex = Mutex()
|
||||
|
||||
suspend fun refresh(
|
||||
previous: StoredSession,
|
||||
load: () -> StoredSession?,
|
||||
save: (MobileSessionResponse) -> StoredSession,
|
||||
clear: () -> Unit,
|
||||
request: suspend (RefreshRequest) -> MobileSessionResponse,
|
||||
): StoredSession = mutex.withLock {
|
||||
val latest = load() ?: throw IllegalStateException("Sesión no iniciada")
|
||||
check(latest.userId == previous.userId) { "La sesión cambió. Volvé a abrir la operación." }
|
||||
if (latest.refreshToken != previous.refreshToken) return@withLock latest
|
||||
val response = try {
|
||||
request(RefreshRequest(previous.refreshToken))
|
||||
} catch (error: HttpException) {
|
||||
// Network failures and server outages must not discard the saved login.
|
||||
if (error.code() == 401 && load()?.refreshToken == previous.refreshToken) clear()
|
||||
throw error
|
||||
}
|
||||
// A logout or another login during the request must never be undone.
|
||||
check(load()?.refreshToken == previous.refreshToken) { "La sesión cambió. Volvé a ingresar." }
|
||||
save(response)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.korexlabs.dhinspeccion.data
|
||||
|
||||
import android.content.Context
|
||||
import com.korexlabs.dhinspeccion.BuildConfig
|
||||
import com.squareup.moshi.Moshi
|
||||
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||
import retrofit2.HttpException
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.converter.moshi.MoshiConverterFactory
|
||||
import retrofit2.http.*
|
||||
import java.time.LocalDate
|
||||
import java.time.OffsetDateTime
|
||||
|
||||
internal data class TechnicalDefinition(
|
||||
val id: String, val code: String, val name: String, val dataType: String,
|
||||
val isRequired: Boolean = false, val isActive: Boolean = true,
|
||||
val unit: String? = null, val options: List<String>? = null,
|
||||
)
|
||||
internal data class TechnicalValues(
|
||||
val assetId: String, val family: FieldInventoryFamily,
|
||||
val definitions: List<TechnicalDefinition>, val values: Map<String, Any?>,
|
||||
)
|
||||
internal data class TechnicalValuesRequest(val values: Map<String, Any?>)
|
||||
private interface TechnicalApi {
|
||||
@GET("assets/{id}/technical-values")
|
||||
suspend fun get(@Header("Authorization") auth: String, @Path("id") id: String): TechnicalValues
|
||||
@PUT("assets/{id}/technical-values")
|
||||
suspend fun put(@Header("Authorization") auth: String, @Path("id") id: String, @Body body: TechnicalValuesRequest): TechnicalValues
|
||||
@POST("auth/mobile/refresh")
|
||||
suspend fun refresh(@Body request: RefreshRequest): MobileSessionResponse
|
||||
}
|
||||
internal class TechnicalRepository(context: Context) {
|
||||
private val store = SecureSessionStore(context.applicationContext)
|
||||
private val api = Retrofit.Builder().baseUrl(BuildConfig.API_BASE_URL)
|
||||
.addConverterFactory(MoshiConverterFactory.create(Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()))
|
||||
.build().create(TechnicalApi::class.java)
|
||||
suspend fun get(id: String) = authorized { api.get("Bearer ${it.accessToken}", id) }
|
||||
suspend fun save(id: String, values: Map<String, Any?>) = authorized {
|
||||
api.put("Bearer ${it.accessToken}", id, TechnicalValuesRequest(values))
|
||||
}
|
||||
private suspend fun <T> authorized(block: suspend (StoredSession) -> T): T {
|
||||
val previous = store.load() ?: error("Sesión no iniciada")
|
||||
try { return block(previous) }
|
||||
catch (error: HttpException) { if (error.code() != 401) throw error }
|
||||
val current = MobileSessionCoordinator.refresh(previous, store::load, store::save, store::clear, api::refresh)
|
||||
return block(current)
|
||||
}
|
||||
}
|
||||
|
||||
/** Keeps IDs and typed JSON values identical to the Dashboard contract. */
|
||||
internal fun technicalInputValue(definition: TechnicalDefinition, text: String): Any? {
|
||||
val value = text.trim()
|
||||
require(value.isNotBlank() || !definition.isRequired) { "Completá ${definition.name}." }
|
||||
if (value.isBlank()) return null
|
||||
fun invalid(): Nothing = throw IllegalArgumentException("Revisá el valor de ${definition.name}.")
|
||||
return when (definition.dataType) {
|
||||
"NUMBER" -> value.replace(',', '.').toDoubleOrNull()?.takeIf { it.isFinite() } ?: invalid()
|
||||
"BOOLEAN" -> when (value) { "true" -> true; "false" -> false; else -> invalid() }
|
||||
"DATE" -> runCatching { LocalDate.parse(value).toString() }.getOrElse { invalid() }
|
||||
"DATETIME" -> runCatching { OffsetDateTime.parse(value).toInstant().toString() }.getOrElse { invalid() }
|
||||
"SELECT" -> value.takeIf { it in definition.options.orEmpty() } ?: invalid()
|
||||
else -> value.takeIf { it.length <= 4000 } ?: invalid()
|
||||
}
|
||||
}
|
||||
@@ -75,6 +75,7 @@ fun FieldFindingScreen(model: MainViewModel) {
|
||||
var severityText by rememberSaveable(asset.id) { mutableStateOf("") }
|
||||
var correctionDueOn by rememberSaveable(asset.id) { mutableStateOf("") }
|
||||
|
||||
var localError by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var requestedFindingId by remember { mutableStateOf<String?>(null) }
|
||||
var pendingPhotoFile by remember { mutableStateOf<File?>(null) }
|
||||
var pendingPhotoGeo by remember { mutableStateOf<FindingGeoSnapshot?>(null) }
|
||||
@@ -110,6 +111,7 @@ fun FieldFindingScreen(model: MainViewModel) {
|
||||
pendingPhotoFindingId = findingId
|
||||
takePicture.launch(uri)
|
||||
}
|
||||
.onFailure { localError = it.message ?: "No se pudo capturar la ubicación GPS." }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,6 +124,7 @@ fun FieldFindingScreen(model: MainViewModel) {
|
||||
val findingId = requestedFindingId
|
||||
requestedFindingId = null
|
||||
if (camera && location && findingId != null) beginPhoto(findingId)
|
||||
else localError = "Permití cámara y ubicación para adjuntar una foto con GPS."
|
||||
}
|
||||
|
||||
fun requestPhoto(findingId: String) {
|
||||
@@ -192,6 +195,7 @@ fun FieldFindingScreen(model: MainViewModel) {
|
||||
}
|
||||
}
|
||||
|
||||
localError?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||
model.error?.let {
|
||||
Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer)) {
|
||||
Text(it, Modifier.padding(12.dp))
|
||||
|
||||
@@ -11,6 +11,10 @@ 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.safeDrawingPadding
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Visibility
|
||||
import androidx.compose.material.icons.filled.VisibilityOff
|
||||
@@ -80,7 +84,7 @@ fun DhRoot(model: MainViewModel, activity: FragmentActivity) {
|
||||
}
|
||||
|
||||
DhTheme {
|
||||
Surface(Modifier.fillMaxSize()) {
|
||||
Surface(Modifier.fillMaxSize().safeDrawingPadding().imePadding()) {
|
||||
when {
|
||||
model.session == null -> EnhancedLoginScreen(model) {
|
||||
passwordLoginInFlight = true
|
||||
@@ -106,10 +110,10 @@ fun DhRoot(model: MainViewModel, activity: FragmentActivity) {
|
||||
@Composable
|
||||
private fun EnhancedLoginScreen(model: MainViewModel, onPasswordLogin: () -> Unit) {
|
||||
var identifier by rememberSaveable { mutableStateOf("") }
|
||||
var password by rememberSaveable { mutableStateOf("") }
|
||||
var password by remember { mutableStateOf("") }
|
||||
var passwordVisible by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) {
|
||||
Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(24.dp), contentAlignment = Alignment.Center) {
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(14.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.ic_mendoza_launcher_exact),
|
||||
@@ -203,7 +207,7 @@ private fun BiometricUnlockScreen(
|
||||
|
||||
LaunchedEffect(Unit) { authenticate() }
|
||||
|
||||
Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) {
|
||||
Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(24.dp), contentAlignment = Alignment.Center) {
|
||||
Column(
|
||||
Modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
|
||||
@@ -60,7 +60,7 @@ fun MobileActsScreen(
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
var newActUrgency by rememberSaveable(visit.id) { mutableStateOf("NON_URGENT") }
|
||||
var closingUrgency by rememberSaveable(selected?.id) { mutableStateOf("") }
|
||||
var attendance by rememberSaveable(selected?.id) {
|
||||
mutableStateOf(closure?.responsible?.attendanceStatus ?: "PRESENT")
|
||||
}
|
||||
@@ -137,7 +137,11 @@ fun MobileActsScreen(
|
||||
}
|
||||
model.acts.forEach { act ->
|
||||
val active = selected?.id == act.id
|
||||
val urgency = if (act.urgency == "URGENT") "URGENTE" else "No urgente"
|
||||
val urgency = when (act.urgency) {
|
||||
"URGENT" -> "URGENTE"
|
||||
"NON_URGENT" -> "No urgente"
|
||||
else -> "Urgencia pendiente"
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = { model.selectAct(act.id) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
@@ -165,23 +169,8 @@ fun MobileActsScreen(
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
Text("Urgencia", fontWeight = FontWeight.Bold)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
AssistChip(
|
||||
onClick = { newActUrgency = "NON_URGENT" },
|
||||
label = { Text(if (newActUrgency == "NON_URGENT") "✓ No urgente" else "No urgente") },
|
||||
)
|
||||
AssistChip(
|
||||
onClick = { newActUrgency = "URGENT" },
|
||||
label = { Text(if (newActUrgency == "URGENT") "✓ Urgente" else "Urgente") },
|
||||
)
|
||||
}
|
||||
Text(
|
||||
if (newActUrgency == "URGENT") {
|
||||
"El plazo urgente se computará desde el Acta según la política institucional vigente al bloquearla."
|
||||
} else {
|
||||
"El plazo no urgente se computará desde la oficialización GEDO según la política institucional vigente al bloquearla."
|
||||
},
|
||||
"La urgencia se define al cerrar el Acta, después de completar los Hallazgos.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Text(
|
||||
@@ -189,7 +178,7 @@ fun MobileActsScreen(
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Button(
|
||||
onClick = { model.createAct(newActUrgency) },
|
||||
onClick = { model.createAct() },
|
||||
enabled = !model.busy,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Crear nueva Acta") }
|
||||
@@ -203,7 +192,13 @@ fun MobileActsScreen(
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||
Text(selected.code, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(actStatusLabel(selected.status))
|
||||
Text(if (selected.urgency == "URGENT") "Urgente" else "No urgente")
|
||||
Text(
|
||||
when (selected.urgency) {
|
||||
"URGENT" -> "Urgencia: Urgente"
|
||||
"NON_URGENT" -> "Urgencia: No urgente"
|
||||
else -> "Urgencia: se define al cerrar el Acta"
|
||||
},
|
||||
)
|
||||
Text("${selected.findingCount} Hallazgo${if (selected.findingCount == 1) "" else "s"} · ${selected.assetCount} elemento${if (selected.assetCount == 1) "" else "s"} de Inventario")
|
||||
selected.deadlineAt?.let { Text("Vencimiento calculado: $it", style = MaterialTheme.typography.bodySmall) }
|
||||
if (selected.deadlineAt == null && selected.deadlineBasis == "GEDO_DATE") {
|
||||
@@ -270,10 +265,20 @@ fun MobileActsScreen(
|
||||
|
||||
HorizontalDivider()
|
||||
Text("Finalizar contenido", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text("Al BLOQUEAR el Acta, el contenido y los Hallazgos quedan inmutables. Esta acción no se puede deshacer.")
|
||||
Text("Al cerrar el Acta, el contenido y los Hallazgos quedan inmutables. Definí ahora la urgencia según lo constatado.")
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
AssistChip(
|
||||
onClick = { closingUrgency = "NON_URGENT" },
|
||||
label = { Text(if (closingUrgency == "NON_URGENT") "✓ No urgente" else "No urgente") },
|
||||
)
|
||||
AssistChip(
|
||||
onClick = { closingUrgency = "URGENT" },
|
||||
label = { Text(if (closingUrgency == "URGENT") "✓ Urgente" else "Urgente") },
|
||||
)
|
||||
}
|
||||
Button(
|
||||
onClick = { model.prepareSelectedAct() },
|
||||
enabled = !model.busy && closure?.responsible != null,
|
||||
onClick = { model.prepareSelectedAct(closingUrgency) },
|
||||
enabled = !model.busy && closure?.responsible != null && closingUrgency.isNotBlank(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Finalizar y BLOQUEAR Acta") }
|
||||
}
|
||||
|
||||
+41
-35
@@ -75,7 +75,7 @@ fun ModernMobileActsScreen(
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
var newActUrgency by rememberSaveable(visit.id) { mutableStateOf("NON_URGENT") }
|
||||
var closingUrgency by rememberSaveable(selected?.id) { mutableStateOf("") }
|
||||
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") }
|
||||
@@ -195,7 +195,7 @@ fun ModernMobileActsScreen(
|
||||
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"}",
|
||||
"${modernActStatusLabel(act.status)} · ${when (act.urgency) { "URGENT" -> "Urgente"; "NON_URGENT" -> "No urgente"; else -> "Urgencia pendiente" }}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
@@ -225,36 +225,13 @@ fun ModernMobileActsScreen(
|
||||
}
|
||||
}
|
||||
|
||||
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 cerrar su contenido."
|
||||
} else {
|
||||
"El plazo no urgente comienza con la oficialización GEDO, no al crear el Acta."
|
||||
},
|
||||
Modifier.padding(12.dp),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
"La urgencia se define recién al cerrar el Acta, cuando ya se conoce el resultado de la inspección.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Button(
|
||||
onClick = { model.createAct(newActUrgency) },
|
||||
onClick = { model.createAct() },
|
||||
enabled = !model.busy,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
@@ -278,7 +255,14 @@ fun ModernMobileActsScreen(
|
||||
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(
|
||||
when (selected.urgency) {
|
||||
"URGENT" -> "Urgencia · Urgente"
|
||||
"NON_URGENT" -> "Urgencia · No urgente"
|
||||
else -> "Urgencia · Se define al cerrar el Acta"
|
||||
},
|
||||
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") {
|
||||
@@ -356,12 +340,34 @@ fun ModernMobileActsScreen(
|
||||
Text("Cerrar Acta", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
Text(
|
||||
"Al cerrar el contenido, el Acta queda inmutable y pasa a Pendiente de firma. Podés firmarla ahora o continuar con otra Acta.",
|
||||
"Al cerrar el contenido, el Acta queda inmutable y pasa a Pendiente de firma. En este momento definí la urgencia según lo constatado en campo.",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text("Urgencia del Acta", fontWeight = FontWeight.SemiBold)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
FilterChip(
|
||||
selected = closingUrgency == "NON_URGENT",
|
||||
onClick = { closingUrgency = "NON_URGENT" },
|
||||
label = { Text("No urgente") },
|
||||
)
|
||||
FilterChip(
|
||||
selected = closingUrgency == "URGENT",
|
||||
onClick = { closingUrgency = "URGENT" },
|
||||
label = { Text("Urgente") },
|
||||
)
|
||||
}
|
||||
Text(
|
||||
when (closingUrgency) {
|
||||
"URGENT" -> "El plazo urgente se computará desde el Acta según la política vigente."
|
||||
"NON_URGENT" -> "El plazo no urgente comenzará con la oficialización GEDO."
|
||||
else -> "Elegí una opción para habilitar el cierre."
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Button(
|
||||
onClick = { model.prepareSelectedAct() },
|
||||
enabled = !model.busy && closure?.responsible != null,
|
||||
onClick = { model.prepareSelectedAct(closingUrgency) },
|
||||
enabled = !model.busy && closure?.responsible != null && closingUrgency.isNotBlank(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Cerrar Acta y dejar pendiente de firma") }
|
||||
}
|
||||
|
||||
@@ -106,7 +106,6 @@ fun ModernVisitRoot(model: MainViewModel) {
|
||||
ModernVisitScreen.OVERVIEW -> ModernVisitOverview(
|
||||
model = model,
|
||||
onActs = { screenName = ModernVisitScreen.ACTS.name },
|
||||
onInventory = { screenName = ModernVisitScreen.INVENTORY.name },
|
||||
)
|
||||
ModernVisitScreen.ACTS -> ModernMobileActsScreen(
|
||||
model = model,
|
||||
@@ -124,7 +123,6 @@ fun ModernVisitRoot(model: MainViewModel) {
|
||||
private fun ModernVisitOverview(
|
||||
model: MainViewModel,
|
||||
onActs: () -> Unit,
|
||||
onInventory: () -> Unit,
|
||||
) {
|
||||
val visit = model.visit ?: return
|
||||
Column(
|
||||
@@ -183,7 +181,7 @@ private fun ModernVisitOverview(
|
||||
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text("Listo para iniciar", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"Al iniciar se habilitan Actas, Hallazgos y el Inventario de campo.",
|
||||
"Al iniciar se habilitan Actas y Hallazgos.",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Button(
|
||||
@@ -217,25 +215,6 @@ private fun ModernVisitOverview(
|
||||
}
|
||||
}
|
||||
}
|
||||
ElevatedCard(onClick = onInventory, modifier = Modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
Modifier.padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
Surface(shape = MaterialTheme.shapes.medium, color = MaterialTheme.colorScheme.secondaryContainer) {
|
||||
Icon(Icons.Filled.Factory, null, Modifier.padding(11.dp), tint = MaterialTheme.colorScheme.secondary)
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text("Inventario de campo", fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"Buscar existente o cargar Instalación / Subinstalación",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (visit.status == "CLOSED") {
|
||||
OutlinedButton(onClick = onActs, modifier = Modifier.fillMaxWidth()) { Text("Ver Actas") }
|
||||
}
|
||||
@@ -329,13 +308,13 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
||||
model.loadFieldTypes(null)
|
||||
}
|
||||
|
||||
fun startInstallation() {
|
||||
fun startInstallation(parent: FieldInventoryItem? = null) {
|
||||
model.clearSelectedFieldAsset()
|
||||
modeName = ModernInventoryMode.CREATE_INSTALLATION.name
|
||||
parentId = null
|
||||
parentLabel = visit.scopeAsset?.name ?: "Yacimiento de la inspección"
|
||||
parentId = parent?.id
|
||||
parentLabel = parent?.name ?: visit.scopeAsset?.name ?: "Yacimiento de la inspección"
|
||||
resetForm()
|
||||
model.loadFieldTypes(null)
|
||||
model.loadFieldTypes(parent?.id)
|
||||
}
|
||||
|
||||
fun startSubinstallation() {
|
||||
@@ -349,6 +328,10 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
||||
}
|
||||
|
||||
fun chooseParent(item: FieldInventoryItem) {
|
||||
if (modernItemTypeCode(item) == "yacimiento") {
|
||||
startInstallation(item)
|
||||
return
|
||||
}
|
||||
keyboard?.hide()
|
||||
focusManager.clearFocus()
|
||||
parentId = item.id
|
||||
@@ -385,8 +368,8 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
||||
ModernInventoryMode.CREATE_SUBINSTALLATION -> normalized.contains("subinstalacion")
|
||||
else -> false
|
||||
}
|
||||
} ?: model.fieldTypes.firstOrNull()
|
||||
if (model.fieldTypes.none { it.id == selectedTypeId }) {
|
||||
}
|
||||
if (selectedTypeId != preferred?.id) {
|
||||
selectedTypeId = preferred?.id
|
||||
selectedFamilyId = null
|
||||
familySearch = ""
|
||||
@@ -435,7 +418,7 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
||||
|
||||
fun createWithLocation() {
|
||||
val type = selectedType ?: return
|
||||
val effectiveParent = if (mode == ModernInventoryMode.CREATE_SUBINSTALLATION) parentId else null
|
||||
val effectiveParent = parentId
|
||||
scope.launch {
|
||||
runCatching { currentModernGeo(context) }
|
||||
.onSuccess { geo ->
|
||||
@@ -529,7 +512,7 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
||||
ModernInventoryMode.PICK_PARENT -> "Elegir Instalación"
|
||||
ModernInventoryMode.CREATE_INSTALLATION -> "Nueva Instalación"
|
||||
ModernInventoryMode.CREATE_SUBINSTALLATION -> "Nueva Subinstalación"
|
||||
ModernInventoryMode.BROWSE -> "Inventario de campo"
|
||||
ModernInventoryMode.BROWSE -> "Ubicación del Hallazgo"
|
||||
},
|
||||
subtitle = visit.scopeAsset?.name ?: visit.code,
|
||||
onBack = { if (mode == ModernInventoryMode.BROWSE) onBack() else backToBrowse() },
|
||||
@@ -544,6 +527,9 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
||||
}
|
||||
|
||||
if (selectedCapture != null) {
|
||||
if (modernItemTypeCode(selectedCapture.asset) in setOf("instalacion", "subinstalacion")) {
|
||||
TechnicalFieldsButton(selectedCapture.asset.id, enabled = !model.busy)
|
||||
}
|
||||
ModernCaptureCard(
|
||||
item = selectedCapture.asset,
|
||||
gps = selectedCapture.capture.creationGpsCaptured,
|
||||
@@ -735,8 +721,9 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
||||
}
|
||||
}
|
||||
|
||||
if (model.fieldTypes.isEmpty() && !model.busy) {
|
||||
ModernLocalError("No hay un tipo habilitado para esta ubicación.") {}
|
||||
if (selectedType == null && !model.busy) {
|
||||
ModernLocalError("Elegí un Yacimiento en Inventario y tocá Agregar Instalación. No se puede crear una Instalación directamente dentro de un Área.") {}
|
||||
OutlinedButton(onClick = { backToBrowse() }) { Text("Elegir Yacimiento") }
|
||||
}
|
||||
|
||||
if (model.fieldTypes.size > 1) {
|
||||
@@ -886,7 +873,7 @@ private fun ModernInventoryBrowse(
|
||||
) {
|
||||
val focusManager = LocalFocusManager.current
|
||||
val keyboard = LocalSoftwareKeyboardController.current
|
||||
val rows = model.inventory.filter { modernItemTypeCode(it) in setOf("instalacion", "subinstalacion") }
|
||||
val rows = model.inventory.filter { modernItemTypeCode(it) in setOf("yacimiento", "instalacion", "subinstalacion") }
|
||||
Column(Modifier.fillMaxSize().padding(horizontal = 18.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Button(onClick = onStartSubinstallation, modifier = Modifier.weight(1f)) {
|
||||
@@ -904,7 +891,7 @@ private fun ModernInventoryBrowse(
|
||||
OutlinedTextField(
|
||||
value = search,
|
||||
onValueChange = onSearchChange,
|
||||
label = { Text("Buscar Inventario") },
|
||||
label = { Text("Buscar Instalación o Subinstalación") },
|
||||
placeholder = { Text("Nombre, código o dato técnico") },
|
||||
leadingIcon = { Icon(Icons.Filled.Search, null) },
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
|
||||
@@ -934,7 +921,7 @@ private fun ModernInventoryCard(item: FieldInventoryItem, onInspect: () -> Unit,
|
||||
Text(item.name, fontWeight = FontWeight.Bold)
|
||||
Text(item.code, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
StatusPill(if (typeCode == "subinstalacion") "Subinstalación" else "Instalación")
|
||||
StatusPill(when (typeCode) { "subinstalacion" -> "Subinstalación"; "yacimiento" -> "Yacimiento"; else -> "Instalación" })
|
||||
}
|
||||
item.commonName?.takeIf { it.isNotBlank() }?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
Text(
|
||||
@@ -946,11 +933,11 @@ private fun ModernInventoryCard(item: FieldInventoryItem, onInspect: () -> Unit,
|
||||
Button(onClick = onInspect, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(if (item.selectedInInspection) "Abrir para Hallazgo" else "Seleccionar para Hallazgo")
|
||||
}
|
||||
if (typeCode == "instalacion") {
|
||||
if (typeCode in setOf("yacimiento", "instalacion")) {
|
||||
OutlinedButton(onClick = onAddChild, modifier = Modifier.fillMaxWidth()) {
|
||||
Icon(Icons.Filled.Add, null)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("Agregar Subinstalación")
|
||||
Text(if (typeCode == "yacimiento") "Agregar Instalación" else "Agregar Subinstalación")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.korexlabs.dhinspeccion.ui
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.korexlabs.dhinspeccion.data.*
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@Composable
|
||||
internal fun TechnicalFieldsButton(assetId: String, enabled: Boolean) {
|
||||
val context = LocalContext.current
|
||||
val repository = remember { TechnicalRepository(context) }
|
||||
val scope = rememberCoroutineScope()
|
||||
var open by rememberSaveable(assetId) { mutableStateOf(false) }
|
||||
var busy by remember(assetId) { mutableStateOf(false) }
|
||||
var snapshot by remember(assetId) { mutableStateOf<TechnicalValues?>(null) }
|
||||
var error by remember(assetId) { mutableStateOf<String?>(null) }
|
||||
var saved by remember(assetId) { mutableStateOf(false) }
|
||||
val values = remember(assetId) { mutableStateMapOf<String, String>() }
|
||||
|
||||
OutlinedButton(onClick = { open = true }, enabled = enabled,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 18.dp)) {
|
||||
Text(if (saved) "Datos técnicos guardados · Revisar" else "Completar datos técnicos")
|
||||
}
|
||||
if (!open) return
|
||||
LaunchedEffect(assetId, open) {
|
||||
busy = true; error = null; snapshot = null
|
||||
try {
|
||||
val loaded = repository.get(assetId)
|
||||
snapshot = loaded
|
||||
values.clear()
|
||||
loaded.values.forEach { (id, value) -> values[id] = value?.toString().orEmpty() }
|
||||
} catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (failure: Exception) { error = DhRepository.humanError(failure) }
|
||||
finally { busy = false }
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = { if (!busy) open = false },
|
||||
title = { Text(snapshot?.family?.name ?: "Datos técnicos") },
|
||||
text = {
|
||||
Column(Modifier.fillMaxWidth().heightIn(max = 460.dp).verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text("Son los mismos campos de la clasificación administrada en oficina. Los marcados con * son obligatorios.")
|
||||
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||
snapshot?.definitions?.filter { it.isActive }?.forEach { definition ->
|
||||
val label = definition.name + (if (definition.isRequired) " *" else "") + (definition.unit?.let { " ($it)" } ?: "")
|
||||
val current = values[definition.id].orEmpty()
|
||||
if (definition.dataType in setOf("BOOLEAN", "SELECT")) {
|
||||
Text(label)
|
||||
val options = if (definition.dataType == "BOOLEAN") listOf("true", "false") else definition.options.orEmpty()
|
||||
options.forEach { option ->
|
||||
FilterChip(selected = current == option, enabled = !busy,
|
||||
onClick = { values[definition.id] = option },
|
||||
label = { Text(if (definition.dataType == "BOOLEAN") if (option == "true") "Sí" else "No" else option) })
|
||||
}
|
||||
if (!definition.isRequired) TextButton(enabled = !busy, onClick = { values[definition.id] = "" }) { Text("Sin dato") }
|
||||
} else {
|
||||
OutlinedTextField(value = current, onValueChange = { values[definition.id] = it },
|
||||
label = { Text(label) }, enabled = !busy, modifier = Modifier.fillMaxWidth(),
|
||||
supportingText = {
|
||||
when (definition.dataType) {
|
||||
"DATE" -> Text("AAAA-MM-DD")
|
||||
"DATETIME" -> Text("AAAA-MM-DDTHH:MM:SS-03:00")
|
||||
else -> Unit
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
if (snapshot?.definitions?.none { it.isActive } == true) Text("Esta clasificación no tiene campos técnicos activos.")
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(enabled = !busy && snapshot != null, onClick = {
|
||||
val current = snapshot ?: return@TextButton
|
||||
busy = true; error = null
|
||||
scope.launch {
|
||||
try {
|
||||
val payload = current.definitions.filter { it.isActive }.mapNotNull { definition ->
|
||||
technicalInputValue(definition, values[definition.id].orEmpty())?.let { definition.id to it }
|
||||
}.toMap()
|
||||
snapshot = repository.save(assetId, payload)
|
||||
saved = true; open = false
|
||||
} catch (cancelled: CancellationException) { throw cancelled }
|
||||
catch (failure: Exception) { error = DhRepository.humanError(failure) }
|
||||
finally { busy = false }
|
||||
}
|
||||
}) { Text("Guardar datos") }
|
||||
},
|
||||
dismissButton = { TextButton(enabled = !busy, onClick = { open = false }) { Text("Cerrar") } },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.korexlabs.dhinspeccion
|
||||
import com.korexlabs.dhinspeccion.data.FieldCoordinates
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
class FieldCoordinatesTest {
|
||||
@Test fun realGpsIsRoundedToApiPrecision() {
|
||||
assertEquals(-32.889459, FieldCoordinates.latitude(-32.889458762), 0.0)
|
||||
assertEquals(-68.845839, FieldCoordinates.longitude(-68.845838912), 0.0)
|
||||
assertEquals(4.123, FieldCoordinates.accuracy(4.123456789), 0.0)
|
||||
}
|
||||
@Test fun boundsAndZeroRemainValid() {
|
||||
assertEquals(90.0, FieldCoordinates.latitude(90.0), 0.0)
|
||||
assertEquals(-180.0, FieldCoordinates.longitude(-180.0), 0.0)
|
||||
assertEquals(0.0, FieldCoordinates.accuracy(0.0), 0.0)
|
||||
}
|
||||
@Test fun invalidCoordinatesAreRejected() {
|
||||
for (value in listOf(Double.NaN, Double.POSITIVE_INFINITY, 90.1, -90.1)) {
|
||||
try { FieldCoordinates.latitude(value); fail("Invalid latitude accepted") }
|
||||
catch (_: IllegalArgumentException) { }
|
||||
}
|
||||
try { FieldCoordinates.accuracy(-1.0); fail("Negative accuracy accepted") }
|
||||
catch (_: IllegalArgumentException) { }
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -38,7 +38,7 @@ class FinalFieldFlowContractTest {
|
||||
@Test
|
||||
fun structuralSelectionUsesTheServerTypeCode() {
|
||||
assertTrue(visit.contains("type.code.ifBlank { type.typeName ?: type.name }"))
|
||||
assertTrue(visit.contains("modernItemTypeCode(it) in setOf(\"instalacion\", \"subinstalacion\")"))
|
||||
assertTrue(visit.contains("modernItemTypeCode(it) in setOf(\"yacimiento\", \"instalacion\", \"subinstalacion\")"))
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package com.korexlabs.dhinspeccion
|
||||
|
||||
import com.korexlabs.dhinspeccion.data.*
|
||||
import java.io.IOException
|
||||
import kotlinx.coroutines.*
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import retrofit2.HttpException
|
||||
import retrofit2.Response
|
||||
|
||||
class MobileSessionCoordinatorTest {
|
||||
private fun old() = StoredSession("u1", "inspector", "Inspector", "a1", "r1")
|
||||
private fun response() = MobileSessionResponse(MobileUser("u1", "inspector"), "a2", "r2", 900)
|
||||
private fun http(code: Int) = HttpException(Response.error<Unit>(code, "error".toResponseBody()))
|
||||
|
||||
private class Store(var value: StoredSession?) {
|
||||
var clears = 0
|
||||
fun load() = value
|
||||
fun clear() { clears++; value = null }
|
||||
fun save(r: MobileSessionResponse): StoredSession =
|
||||
StoredSession(r.user.id, r.user.username, r.user.username, r.accessToken, r.refreshToken).also { value = it }
|
||||
}
|
||||
|
||||
@Test fun concurrentClientsRotateTheTokenOnlyOnce() = runBlocking {
|
||||
val previous = old(); val store = Store(previous); var calls = 0
|
||||
val results = coroutineScope {
|
||||
(1..4).map {
|
||||
async {
|
||||
MobileSessionCoordinator.refresh(previous, store::load, store::save, store::clear) {
|
||||
calls++; delay(20); response()
|
||||
}
|
||||
}
|
||||
}.awaitAll()
|
||||
}
|
||||
assertEquals(1, calls)
|
||||
assertTrue(results.all { it.refreshToken == "r2" })
|
||||
assertEquals(0, store.clears)
|
||||
}
|
||||
|
||||
@Test fun networkAndServerFailuresKeepSessionForRetry() = runBlocking {
|
||||
for (failure in listOf(IOException("offline"), http(500), http(429))) {
|
||||
val previous = old(); val store = Store(previous)
|
||||
try {
|
||||
MobileSessionCoordinator.refresh(previous, store::load, store::save, store::clear) { throw failure }
|
||||
fail("Expected request failure")
|
||||
} catch (caught: Exception) { assertSame(failure, caught) }
|
||||
assertEquals(previous, store.value)
|
||||
assertEquals(0, store.clears)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun invalidRefreshClearsOnlyTheExpiredSession() = runBlocking {
|
||||
val previous = old(); val store = Store(previous)
|
||||
try {
|
||||
MobileSessionCoordinator.refresh(previous, store::load, store::save, store::clear) { throw http(401) }
|
||||
fail("Expected unauthorized")
|
||||
} catch (caught: HttpException) { assertEquals(401, caught.code()) }
|
||||
assertNull(store.value)
|
||||
assertEquals(1, store.clears)
|
||||
}
|
||||
|
||||
@Test fun cancelledRefreshKeepsSession() = runBlocking {
|
||||
val previous = old(); val store = Store(previous)
|
||||
try {
|
||||
MobileSessionCoordinator.refresh(previous, store::load, store::save, store::clear) { throw CancellationException("cancel") }
|
||||
fail("Expected cancellation")
|
||||
} catch (_: CancellationException) { }
|
||||
assertEquals(previous, store.value)
|
||||
}
|
||||
|
||||
@Test fun logoutDuringRefreshCannotBeUndone() = runBlocking {
|
||||
val previous = old(); val store = Store(previous)
|
||||
try {
|
||||
MobileSessionCoordinator.refresh(previous, store::load, store::save, store::clear) {
|
||||
store.clear(); response()
|
||||
}
|
||||
fail("Must reject a refresh after logout")
|
||||
} catch (_: IllegalStateException) { }
|
||||
assertNull(store.value)
|
||||
}
|
||||
|
||||
@Test fun staleRequestCannotUseAnotherInspectorsSession() = runBlocking {
|
||||
val previous = old(); val store = Store(previous.copy(userId = "u2", refreshToken = "other"))
|
||||
try {
|
||||
MobileSessionCoordinator.refresh(previous, store::load, store::save, store::clear) {
|
||||
fail("No refresh allowed for another inspector"); response()
|
||||
}
|
||||
fail("Must reject account switch")
|
||||
} catch (_: IllegalStateException) { }
|
||||
assertEquals("u2", store.value?.userId)
|
||||
}
|
||||
|
||||
@Test fun lateUnauthorizedDoesNotClearANewLogin() = runBlocking {
|
||||
val previous = old(); val store = Store(previous)
|
||||
try {
|
||||
MobileSessionCoordinator.refresh(previous, store::load, store::save, store::clear) {
|
||||
store.value = previous.copy(refreshToken = "new-login")
|
||||
throw http(401)
|
||||
}
|
||||
} catch (_: HttpException) { }
|
||||
assertEquals("new-login", store.value?.refreshToken)
|
||||
assertEquals(0, store.clears)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.korexlabs.dhinspeccion
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class OperationTrackerTest {
|
||||
@Test fun doubleTapCannotQueueASecondWrite() {
|
||||
val tracker = OperationTracker()
|
||||
assertTrue(tracker.begin(mutation = true))
|
||||
assertFalse(tracker.begin(mutation = true))
|
||||
tracker.end()
|
||||
assertFalse(tracker.busy)
|
||||
assertTrue(tracker.begin(mutation = true))
|
||||
}
|
||||
@Test fun BusyRemainsUntilEveryReadCompletes() {
|
||||
val tracker = OperationTracker()
|
||||
assertTrue(tracker.begin(false)); assertTrue(tracker.begin(false))
|
||||
tracker.end(); assertTrue(tracker.busy)
|
||||
assertFalse(tracker.begin(true))
|
||||
tracker.end(); assertFalse(tracker.busy)
|
||||
}
|
||||
@Test fun readDuringWriteDoesNotReleaseItsGuardEarly() {
|
||||
val tracker = OperationTracker()
|
||||
assertTrue(tracker.begin(true)); assertTrue(tracker.begin(false))
|
||||
tracker.end(); assertFalse(tracker.begin(true))
|
||||
tracker.end(); assertTrue(tracker.begin(true))
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,8 @@ class ReleaseMetadataTest {
|
||||
@Test
|
||||
fun debugBuildKeepsSeparateApplicationIdentity() {
|
||||
assertEquals("com.korexlabs.dhinspeccion.debug", BuildConfig.APPLICATION_ID)
|
||||
assertEquals(28, BuildConfig.VERSION_CODE)
|
||||
assertEquals("0.19.0-debug", BuildConfig.VERSION_NAME)
|
||||
assertEquals(30, BuildConfig.VERSION_CODE)
|
||||
assertEquals("0.19.2-debug", BuildConfig.VERSION_NAME)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.korexlabs.dhinspeccion
|
||||
import com.korexlabs.dhinspeccion.data.*
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
class TechnicalValuesTest {
|
||||
private fun field(type: String, required: Boolean = false) = TechnicalDefinition("id", "code", "Campo", type, required, options = listOf("A", "B"))
|
||||
@Test fun decimalCommaAndBooleanFalseKeepTheirTypes() {
|
||||
assertEquals(12.5, technicalInputValue(field("NUMBER"), "12,5"))
|
||||
assertEquals(false, technicalInputValue(field("BOOLEAN", true), "false"))
|
||||
assertEquals(0.0, technicalInputValue(field("NUMBER", true), "0"))
|
||||
}
|
||||
@Test fun optionalBlankIsOmittedButRequiredBlankFails() {
|
||||
assertNull(technicalInputValue(field("TEXT"), " "))
|
||||
try { technicalInputValue(field("TEXT", true), ""); fail("Required missing") }
|
||||
catch (_: IllegalArgumentException) { }
|
||||
}
|
||||
@Test fun invalidNumbersDatesAndOptionsFailBeforeSave() {
|
||||
for ((type, value) in listOf("NUMBER" to "NaN", "DATE" to "2026-02-30", "SELECT" to "C", "BOOLEAN" to "quizás")) {
|
||||
try { technicalInputValue(field(type), value); fail("Invalid value accepted") }
|
||||
catch (_: IllegalArgumentException) { }
|
||||
}
|
||||
}
|
||||
@Test fun validDatesAndSelectRemainCanonical() {
|
||||
assertEquals("2026-09-14", technicalInputValue(field("DATE"), "2026-09-14"))
|
||||
assertEquals("A", technicalInputValue(field("SELECT"), "A"))
|
||||
assertEquals("2026-09-14T13:00:00Z", technicalInputValue(field("DATETIME"), "2026-09-14T10:00:00-03:00"))
|
||||
}
|
||||
}
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "dhv2-api",
|
||||
"version": "0.29.0-1",
|
||||
"version": "0.29.0-2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "dhv2-api",
|
||||
"version": "0.29.0-1",
|
||||
"version": "0.29.0-2",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^11.0.0",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dhv2-api",
|
||||
"version": "0.29.0-1",
|
||||
"version": "0.29.0-2",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
|
||||
@@ -71,8 +71,8 @@ export class InspectionAct extends TimestampedEntity {
|
||||
@Column({ type: 'text', nullable: true })
|
||||
observations!: string | null;
|
||||
|
||||
@Column({ name: 'urgency', type: 'varchar', length: 24, default: InspectionActUrgency.NON_URGENT })
|
||||
urgency!: InspectionActUrgency;
|
||||
@Column({ name: 'urgency', type: 'varchar', length: 24, nullable: true })
|
||||
urgency!: InspectionActUrgency | null;
|
||||
|
||||
@Column({ name: 'deadline_days', type: 'integer', nullable: true })
|
||||
deadlineDays!: number | null;
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
export class F61ActUrgencyAtLock1790113800000 implements MigrationInterface {
|
||||
name = 'F61ActUrgencyAtLock1790113800000';
|
||||
|
||||
public async up(q: QueryRunner): Promise<void> {
|
||||
await q.query(`ALTER TABLE inspection_acts ALTER COLUMN urgency DROP DEFAULT`);
|
||||
await q.query(`ALTER TABLE inspection_acts ALTER COLUMN urgency DROP NOT NULL`);
|
||||
await q.query(`UPDATE inspection_acts SET urgency=NULL WHERE status='DRAFT'`);
|
||||
}
|
||||
|
||||
public async down(q: QueryRunner): Promise<void> {
|
||||
await q.query(`UPDATE inspection_acts SET urgency='NON_URGENT' WHERE urgency IS NULL`);
|
||||
await q.query(`ALTER TABLE inspection_acts ALTER COLUMN urgency SET NOT NULL`);
|
||||
await q.query(`ALTER TABLE inspection_acts ALTER COLUMN urgency SET DEFAULT 'NON_URGENT'`);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
ArrayMaxSize,
|
||||
ArrayUnique,
|
||||
IsArray,
|
||||
IsEnum,
|
||||
IsISO8601,
|
||||
IsOptional,
|
||||
IsString,
|
||||
@@ -11,15 +10,11 @@ import {
|
||||
MaxLength,
|
||||
MinLength,
|
||||
} from 'class-validator';
|
||||
import { InspectionActUrgency } from '../../database/entities';
|
||||
|
||||
export class CreateInspectionActDto {
|
||||
@IsISO8601({ strict: true })
|
||||
occurredAt!: string;
|
||||
|
||||
@IsEnum(InspectionActUrgency)
|
||||
urgency!: InspectionActUrgency;
|
||||
|
||||
@Transform(({ value }) => (typeof value === 'string' ? value.trim() : value))
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
ArrayMinSize,
|
||||
ArrayUnique,
|
||||
IsArray,
|
||||
IsEnum,
|
||||
IsISO8601,
|
||||
IsOptional,
|
||||
IsString,
|
||||
@@ -12,17 +11,12 @@ import {
|
||||
MaxLength,
|
||||
MinLength,
|
||||
} from 'class-validator';
|
||||
import { InspectionActUrgency } from '../../database/entities';
|
||||
|
||||
export class UpdateInspectionActDto {
|
||||
@IsOptional()
|
||||
@IsISO8601({ strict: true })
|
||||
occurredAt?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(InspectionActUrgency)
|
||||
urgency?: InspectionActUrgency;
|
||||
|
||||
@IsOptional()
|
||||
@Transform(({ value }) => (typeof value === 'string' ? value.trim() : value))
|
||||
@IsString()
|
||||
|
||||
@@ -74,7 +74,7 @@ export interface InspectionActListItem {
|
||||
title: string;
|
||||
summary: string;
|
||||
observations: string | null;
|
||||
urgency: InspectionActUrgency;
|
||||
urgency: InspectionActUrgency | null;
|
||||
deadlineDays: number | null;
|
||||
deadlineDayType: InspectionDeadlineDayType | null;
|
||||
deadlineBasis: InspectionDeadlineBasis | null;
|
||||
@@ -314,7 +314,7 @@ export class InspectionActsService {
|
||||
title: dto.title,
|
||||
summary: dto.summary,
|
||||
observations: dto.observations ?? null,
|
||||
urgency: dto.urgency,
|
||||
urgency: null,
|
||||
deadlineDays: null,
|
||||
deadlineDayType: null,
|
||||
deadlineBasis: null,
|
||||
@@ -379,7 +379,6 @@ export class InspectionActsService {
|
||||
await this.assertVisitAssets(manager, visit.id, nextAssetIds);
|
||||
const before = await this.loadView(manager, id);
|
||||
if (dto.occurredAt !== undefined) act.occurredAt = nextOccurredAt;
|
||||
if (dto.urgency !== undefined) act.urgency = dto.urgency;
|
||||
if (dto.title !== undefined) act.title = dto.title;
|
||||
if (dto.summary !== undefined) act.summary = dto.summary;
|
||||
if (dto.observations !== undefined) act.observations = dto.observations;
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { IsEnum } from 'class-validator';
|
||||
import { InspectionActUrgency } from '../../database/entities';
|
||||
|
||||
export class PrepareInspectionActDto {
|
||||
@IsEnum(InspectionActUrgency)
|
||||
urgency!: InspectionActUrgency;
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import { CurrentAuth } from '../auth/decorators/current-auth.decorator';
|
||||
import { RequirePermissions } from '../authorization/decorators/require-permissions.decorator';
|
||||
import type { AuthPrincipal, RequestWithContext } from '../common/http/request-context';
|
||||
import { CloseInspectionActDto } from './dto/close-inspection-act.dto';
|
||||
import { PrepareInspectionActDto } from './dto/prepare-inspection-act.dto';
|
||||
import { CreateCompanyOutcomeDto } from './dto/create-company-outcome.dto';
|
||||
import { CreateInspectionSignatureDto } from './dto/create-inspection-signature.dto';
|
||||
import { CreateCompanySignatureDto } from './dto/create-company-signature.dto';
|
||||
@@ -52,10 +53,11 @@ export class InspectionClosingController {
|
||||
@RequirePermissions('inspection_closure.prepare')
|
||||
lock(
|
||||
@Param('actId', new ParseUUIDPipe({ version: '4' })) actId: string,
|
||||
@Body() dto: PrepareInspectionActDto,
|
||||
@CurrentAuth() principal: AuthPrincipal,
|
||||
@Req() request: RequestWithContext,
|
||||
) {
|
||||
return this.closing.prepare(actId, principal, request);
|
||||
return this.closing.prepare(actId, dto, principal, request);
|
||||
}
|
||||
|
||||
@Post('signatures/inspector')
|
||||
|
||||
@@ -35,6 +35,7 @@ import { assertMobileInspector } from '../inspection-operations/mobile-inspector
|
||||
import { InspectionReportsService } from '../inspection-reports/inspection-reports.service';
|
||||
import { sha256CanonicalJson } from './canonical-json';
|
||||
import type { CloseInspectionActDto } from './dto/close-inspection-act.dto';
|
||||
import type { PrepareInspectionActDto } from './dto/prepare-inspection-act.dto';
|
||||
import type { CreateCompanyOutcomeDto } from './dto/create-company-outcome.dto';
|
||||
import type { CreateCompanySignatureDto } from './dto/create-company-signature.dto';
|
||||
import type { CreateInspectionSignatureDto } from './dto/create-inspection-signature.dto';
|
||||
@@ -130,7 +131,7 @@ export interface InspectionClosureView {
|
||||
code: string;
|
||||
status: InspectionActStatus;
|
||||
visitId: string;
|
||||
urgency: InspectionActUrgency;
|
||||
urgency: InspectionActUrgency | null;
|
||||
deadlineDays: number | null;
|
||||
deadlineDayType: InspectionDeadlineDayType | null;
|
||||
deadlineBasis: InspectionDeadlineBasis | null;
|
||||
@@ -268,6 +269,7 @@ export class InspectionClosingService {
|
||||
/** Finaliza el contenido: desde este punto el Acta queda inmutable. */
|
||||
async prepare(
|
||||
actId: string,
|
||||
dto: PrepareInspectionActDto,
|
||||
principal: AuthPrincipal,
|
||||
request: RequestWithContext,
|
||||
): Promise<InspectionClosureView> {
|
||||
@@ -285,16 +287,16 @@ export class InspectionClosingService {
|
||||
}
|
||||
|
||||
const policy = await this.deadlinePolicy(manager);
|
||||
const deadlineDays = act.urgency === InspectionActUrgency.URGENT
|
||||
const deadlineDays = dto.urgency === InspectionActUrgency.URGENT
|
||||
? policy.urgentDays
|
||||
: policy.nonUrgentDays;
|
||||
const deadlineDayType = act.urgency === InspectionActUrgency.URGENT
|
||||
const deadlineDayType = dto.urgency === InspectionActUrgency.URGENT
|
||||
? policy.urgentDayType
|
||||
: policy.nonUrgentDayType;
|
||||
const deadlineBasis = act.urgency === InspectionActUrgency.URGENT
|
||||
const deadlineBasis = dto.urgency === InspectionActUrgency.URGENT
|
||||
? InspectionDeadlineBasis.ACT_DATE
|
||||
: InspectionDeadlineBasis.GEDO_DATE;
|
||||
const deadlineBaseAt = act.urgency === InspectionActUrgency.URGENT
|
||||
const deadlineBaseAt = dto.urgency === InspectionActUrgency.URGENT
|
||||
? act.occurredAt
|
||||
: null;
|
||||
const deadlineAt = deadlineBaseAt
|
||||
@@ -305,20 +307,22 @@ export class InspectionClosingService {
|
||||
const [updated] = (await manager.query(`
|
||||
UPDATE inspection_acts
|
||||
SET status='LOCKED',
|
||||
deadline_days=$2,
|
||||
deadline_day_type=$3,
|
||||
deadline_basis=$4,
|
||||
deadline_base_at=$5,
|
||||
deadline_at=$6,
|
||||
locked_at=$7,
|
||||
locked_by=$8,
|
||||
urgency=$2,
|
||||
deadline_days=$3,
|
||||
deadline_day_type=$4,
|
||||
deadline_basis=$5,
|
||||
deadline_base_at=$6,
|
||||
deadline_at=$7,
|
||||
locked_at=$8,
|
||||
locked_by=$9,
|
||||
current_version=current_version+1,
|
||||
updated_by=$8,
|
||||
updated_at=$7
|
||||
updated_by=$9,
|
||||
updated_at=$8
|
||||
WHERE id=$1
|
||||
RETURNING current_version AS "versionNumber"
|
||||
`, [
|
||||
actId,
|
||||
dto.urgency,
|
||||
deadlineDays,
|
||||
deadlineDayType,
|
||||
deadlineBasis,
|
||||
@@ -1009,7 +1013,7 @@ export class InspectionClosingService {
|
||||
WHERE act.id=$1
|
||||
`, [actId]) as Array<{
|
||||
id: string; code: string; status: InspectionActStatus; visitId: string;
|
||||
urgency: InspectionActUrgency; deadlineDays: number | null;
|
||||
urgency: InspectionActUrgency | null; deadlineDays: number | null;
|
||||
deadlineDayType: InspectionDeadlineDayType | null; deadlineBasis: InspectionDeadlineBasis | null;
|
||||
deadlineBaseAt: Date | null; deadlineAt: Date | null; lockedAt: Date | null;
|
||||
lockedSha256: string | null; sealedAt: Date | null; currentVersion: number;
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export const API_VERSION = '0.29.0-1';
|
||||
export const API_VERSION = '0.29.0-2';
|
||||
export const API_PHASE = 'F6.1';
|
||||
@@ -20,7 +20,7 @@ test('F4 WEB has an explicit LOCKED and SEALED act contract', () => {
|
||||
assert.match(f4Api, /lockedAt: string \| null/);
|
||||
assert.match(f4Api, /lockedSha256: string \| null/);
|
||||
assert.match(f4Api, /sealedAt: string \| null/);
|
||||
assert.match(f4Api, /urgency: InspectionActUrgencyF4/);
|
||||
assert.match(f4Api, /urgency: InspectionActUrgencyF4 \| null/);
|
||||
assert.match(f4Api, /deadlineAt: string \| null/);
|
||||
});
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ test('F4 Android uses only lock and seal endpoints for the active Act lifecycle'
|
||||
});
|
||||
|
||||
test('F4 Android ViewModel calls lock and seal directly', () => {
|
||||
assert.match(viewModel, /actsRepository\.lock\(actId\)/);
|
||||
assert.match(viewModel, /actsRepository\.lock\(actId, urgency\)/);
|
||||
assert.match(viewModel, /actsRepository\.seal\(actId\)/);
|
||||
assert.doesNotMatch(viewModel, /actsRepository\.prepare\(/);
|
||||
assert.doesNotMatch(viewModel, /actsRepository\.reopen\(/);
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { API_PHASE, API_VERSION } from '../../src/version';
|
||||
|
||||
test('health metadata reports the current F6.1 release', () => {
|
||||
assert.equal(API_PHASE, 'F6.1');
|
||||
assert.equal(API_VERSION, '0.29.0-1');
|
||||
const pkg = JSON.parse(readFileSync(resolve(process.cwd(), 'package.json'), 'utf8')) as { version: string };
|
||||
assert.equal(API_VERSION, pkg.version);
|
||||
assert.equal(API_VERSION, '0.29.0-2');
|
||||
});
|
||||
@@ -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 = 28/);
|
||||
assert.match(gradle, /versionName = "0\.19\.0"/);
|
||||
assert.match(gradle, /versionCode = 30/);
|
||||
assert.match(gradle, /versionName = "0\.19\.2"/);
|
||||
assert.match(gradle, /https:\/\/dhv2\.korexlabs\.com\/api\/v3\//);
|
||||
assert.match(gradle, /applicationIdSuffix = "\.debug"/);
|
||||
});
|
||||
|
||||
@@ -20,7 +20,7 @@ test('F6.3 an Acta can start empty and receive Inventory when Hallazgos are adde
|
||||
|
||||
assert.doesNotMatch(dto, /ArrayMinSize\(1\)/);
|
||||
assert.match(service, /if \(assetIds\.length === 0\) return/);
|
||||
assert.match(mobile, /assetIds = listOfNotNull\(assetId\)/);
|
||||
assert.match(mobile, /assetIds = emptyList\(\)/);
|
||||
});
|
||||
|
||||
test('F6.3 every Installation and Subinstallation receives the common field card', () => {
|
||||
@@ -35,15 +35,31 @@ test('F6.3 every Installation and Subinstallation receives the common field card
|
||||
});
|
||||
|
||||
test('F6.3 Android follows Inspección → Acta → Hallazgo → Inventario', () => {
|
||||
const root = source('../android-app/app/src/main/java/com/korexlabs/dhinspeccion/ui/F3VisitRoot.kt');
|
||||
const acts = source('../android-app/app/src/main/java/com/korexlabs/dhinspeccion/ui/MobileActsScreen.kt');
|
||||
const root = source('../android-app/app/src/main/java/com/korexlabs/dhinspeccion/ui/ModernVisitRoot.kt');
|
||||
const acts = source('../android-app/app/src/main/java/com/korexlabs/dhinspeccion/ui/ModernMobileActsScreen.kt');
|
||||
const vm = source('../android-app/app/src/main/java/com/korexlabs/dhinspeccion/MainViewModel.kt');
|
||||
|
||||
assert.match(root, /model\.startVisit\(\); onActs\(\)/);
|
||||
assert.match(root, /Text\("Nuevo Hallazgo"/);
|
||||
assert.match(root, /Buscar instalación o subinstalación/);
|
||||
assert.match(acts, /Text\("\+ Agregar Hallazgo"\)/);
|
||||
assert.match(acts, /model\.createAct\(newActUrgency\)/);
|
||||
assert.match(vm, /fun createAct\(urgency: String = "NON_URGENT"\)/);
|
||||
assert.doesNotMatch(root, /Text\("Inventario de campo"/);
|
||||
assert.match(acts, /Text\("Agregar Hallazgo"\)/);
|
||||
assert.match(acts, /model\.createAct\(\)/);
|
||||
assert.match(acts, /model\.prepareSelectedAct\(closingUrgency\)/);
|
||||
assert.match(vm, /fun createAct\(\)/);
|
||||
assert.match(vm, /fun prepareSelectedAct\(urgency: String\)/);
|
||||
assert.match(vm, /repository\.fieldInventory\(currentVisit\.id, search, parentId\)/);
|
||||
});
|
||||
|
||||
test('F6.1 Acta urgency is null while drafting and is persisted atomically at lock', () => {
|
||||
const createDto = source('src/inspection-acts/dto/create-inspection-act.dto.ts');
|
||||
const prepareDto = source('src/inspection-closing/dto/prepare-inspection-act.dto.ts');
|
||||
const actsService = source('src/inspection-acts/inspection-acts.service.ts');
|
||||
const closingService = source('src/inspection-closing/inspection-closing.service.ts');
|
||||
const migration = source('src/database/migrations/1790113800000-f6-1-act-urgency-at-lock.ts');
|
||||
|
||||
assert.doesNotMatch(createDto, /urgency/);
|
||||
assert.match(prepareDto, /urgency!: InspectionActUrgency/);
|
||||
assert.match(actsService, /urgency: null/);
|
||||
assert.match(closingService, /urgency=\$2/);
|
||||
assert.match(migration, /ALTER COLUMN urgency DROP NOT NULL/);
|
||||
assert.match(migration, /SET urgency=NULL WHERE status='DRAFT'/);
|
||||
});
|
||||
|
||||
@@ -5,21 +5,18 @@ import { plainToInstance } from 'class-transformer';
|
||||
import { validate } from 'class-validator';
|
||||
import { CancelInspectionActDto } from '../../src/inspection-acts/dto/cancel-inspection-act.dto';
|
||||
import { CreateInspectionActDto } from '../../src/inspection-acts/dto/create-inspection-act.dto';
|
||||
import { InspectionActUrgency } from '../../src/database/entities';
|
||||
|
||||
const ASSET_ID = '16e54e65-60cf-4739-b0d1-ccdd904fbfd5';
|
||||
|
||||
test('inspection act DTO accepts urgency, content and selected visit assets', async () => {
|
||||
test('inspection act DTO accepts content and selected visit assets without deciding urgency', async () => {
|
||||
const dto = plainToInstance(CreateInspectionActDto, {
|
||||
occurredAt: '2026-08-14T15:30:00.000Z',
|
||||
urgency: InspectionActUrgency.NON_URGENT,
|
||||
title: ' Verificación de instalación ',
|
||||
summary: ' Se inspeccionó el activo seleccionado. ',
|
||||
observations: ' Sin novedades. ',
|
||||
assetIds: [ASSET_ID],
|
||||
});
|
||||
assert.deepEqual(await validate(dto), []);
|
||||
assert.equal(dto.urgency, InspectionActUrgency.NON_URGENT);
|
||||
assert.equal(dto.title, 'Verificación de instalación');
|
||||
assert.equal(dto.summary, 'Se inspeccionó el activo seleccionado.');
|
||||
assert.equal(dto.observations, 'Sin novedades.');
|
||||
@@ -28,7 +25,6 @@ test('inspection act DTO accepts urgency, content and selected visit assets', as
|
||||
test('inspection act DTO rejects duplicate assets', async () => {
|
||||
const dto = plainToInstance(CreateInspectionActDto, {
|
||||
occurredAt: '2026-08-14T15:30:00.000Z',
|
||||
urgency: InspectionActUrgency.NON_URGENT,
|
||||
title: 'Acta',
|
||||
summary: 'Contenido',
|
||||
assetIds: [ASSET_ID, ASSET_ID],
|
||||
|
||||
@@ -5,6 +5,8 @@ import { plainToInstance } from 'class-transformer';
|
||||
import { validate } from 'class-validator';
|
||||
import { CreateCompanyOutcomeDto } from '../../src/inspection-closing/dto/create-company-outcome.dto';
|
||||
import { CreateInspectionSignatureDto } from '../../src/inspection-closing/dto/create-inspection-signature.dto';
|
||||
import { PrepareInspectionActDto } from '../../src/inspection-closing/dto/prepare-inspection-act.dto';
|
||||
import { InspectionActUrgency } from '../../src/database/entities';
|
||||
import { UpsertInspectionResponsibleDto } from '../../src/inspection-closing/dto/upsert-inspection-responsible.dto';
|
||||
|
||||
test('D5 present responsible requires identity and position', async () => {
|
||||
@@ -54,3 +56,13 @@ test('D5 signature DTO transforms multipart consent and coordinates', async () =
|
||||
assert.equal(dto.consentAccepted, true);
|
||||
assert.equal(dto.latitude, -32.889458);
|
||||
});
|
||||
|
||||
|
||||
test('F6.1 urgency is selected when the Acta is closed, not when it is created', async () => {
|
||||
const urgent = plainToInstance(PrepareInspectionActDto, { urgency: InspectionActUrgency.URGENT });
|
||||
const nonUrgent = plainToInstance(PrepareInspectionActDto, { urgency: InspectionActUrgency.NON_URGENT });
|
||||
const invalid = plainToInstance(PrepareInspectionActDto, { urgency: 'UNKNOWN' });
|
||||
assert.deepEqual(await validate(urgent), []);
|
||||
assert.deepEqual(await validate(nonUrgent), []);
|
||||
assert.equal((await validate(invalid)).some((error) => error.property === 'urgency'), true);
|
||||
});
|
||||
|
||||
@@ -126,11 +126,20 @@ INSERT INTO auth_sessions(
|
||||
SQL
|
||||
|
||||
docker compose --env-file .env.example up -d api
|
||||
|
||||
# Gitea Actions runs Docker through DinD: the job container's 127.0.0.1 is
|
||||
# not the Docker daemon host. Probe the API from inside its own container,
|
||||
# matching the main CI contract instead of relying on the published host port.
|
||||
api_health() {
|
||||
docker compose --env-file .env.example exec -T api \
|
||||
node -e 'fetch(`http://127.0.0.1:${process.env.API_PORT}/api/v3/health`).then(async r => { const t = await r.text(); if (!r.ok) { console.error(t); process.exit(1); } }).catch(() => process.exit(1))'
|
||||
}
|
||||
|
||||
for _ in $(seq 1 30); do
|
||||
curl -fsS http://127.0.0.1:3101/api/v3/health >/dev/null 2>&1 && break
|
||||
if api_health >/dev/null 2>&1; then break; fi
|
||||
sleep 2
|
||||
done
|
||||
curl -fsS http://127.0.0.1:3101/api/v3/health >/dev/null
|
||||
api_health >/dev/null
|
||||
|
||||
TOKEN="$(docker compose --env-file .env.example exec -T api node - <<'NODE'
|
||||
const jwt = require('jsonwebtoken');
|
||||
@@ -164,28 +173,29 @@ CONTEXT="$(docker compose --env-file .env.example exec -T db \
|
||||
IFS='|' read -r DEPARTMENT_ID AREA_ID YACIMIENTO_ID COMPANY_ID <<< "$CONTEXT"
|
||||
test -n "$DEPARTMENT_ID" && test -n "$AREA_ID" && test -n "$YACIMIENTO_ID" && test -n "$COMPANY_ID"
|
||||
|
||||
curl -fsS -H "Authorization: Bearer $TOKEN" \
|
||||
http://127.0.0.1:3101/api/v3/inspection-visits/planning-context/departments \
|
||||
>/tmp/dhv2-departments.json
|
||||
api_get() {
|
||||
local request_path="$1"
|
||||
docker compose --env-file .env.example exec -T \
|
||||
-e REQUEST_TOKEN="$TOKEN" -e REQUEST_PATH="$request_path" api \
|
||||
node -e 'fetch(`http://127.0.0.1:${process.env.API_PORT}${process.env.REQUEST_PATH}`, {headers:{Authorization:`Bearer ${process.env.REQUEST_TOKEN}`}}).then(async r => { const t=await r.text(); process.stdout.write(t); if (!r.ok) process.exit(1); }).catch(e => { console.error(e); process.exit(1); })'
|
||||
}
|
||||
|
||||
api_get '/api/v3/inspection-visits/planning-context/departments' >/tmp/dhv2-departments.json
|
||||
grep -Fq "$DEPARTMENT_ID" /tmp/dhv2-departments.json
|
||||
|
||||
curl -fsS -H "Authorization: Bearer $TOKEN" \
|
||||
"http://127.0.0.1:3101/api/v3/inspection-visits/planning-context/departments/$DEPARTMENT_ID/areas" \
|
||||
>/tmp/dhv2-areas.json
|
||||
api_get "/api/v3/inspection-visits/planning-context/departments/$DEPARTMENT_ID/areas" >/tmp/dhv2-areas.json
|
||||
grep -Fq "$AREA_ID" /tmp/dhv2-areas.json
|
||||
|
||||
curl -fsS -H "Authorization: Bearer $TOKEN" \
|
||||
"http://127.0.0.1:3101/api/v3/inspection-visits/planning-context/areas/$AREA_ID/yacimientos" \
|
||||
>/tmp/dhv2-yacimientos.json
|
||||
api_get "/api/v3/inspection-visits/planning-context/areas/$AREA_ID/yacimientos" >/tmp/dhv2-yacimientos.json
|
||||
grep -Fq "$YACIMIENTO_ID" /tmp/dhv2-yacimientos.json
|
||||
|
||||
START_AT="$(date -u -d '+1 day' +'%Y-%m-%dT%H:%M:%S.000Z')"
|
||||
HTTP_CODE="$(curl -sS -o /tmp/dhv2-created.json -w '%{http_code}' \
|
||||
-X POST \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "{\"operationalAreaId\":\"$AREA_ID\",\"scopeAssetId\":\"$YACIMIENTO_ID\",\"operatorCompanyId\":\"$COMPANY_ID\",\"plannedStartAt\":\"$START_AT\",\"leadInspectorUserId\":\"22222222-2222-4222-8222-222222222222\"}" \
|
||||
http://127.0.0.1:3101/api/v3/inspection-visits)"
|
||||
REQUEST_BODY="{\"operationalAreaId\":\"$AREA_ID\",\"scopeAssetId\":\"$YACIMIENTO_ID\",\"operatorCompanyId\":\"$COMPANY_ID\",\"plannedStartAt\":\"$START_AT\",\"leadInspectorUserId\":\"22222222-2222-4222-8222-222222222222\"}"
|
||||
POST_RESULT="$(docker compose --env-file .env.example exec -T \
|
||||
-e REQUEST_TOKEN="$TOKEN" -e REQUEST_BODY="$REQUEST_BODY" api \
|
||||
node -e 'fetch(`http://127.0.0.1:${process.env.API_PORT}/api/v3/inspection-visits`, {method:"POST",headers:{Authorization:`Bearer ${process.env.REQUEST_TOKEN}`,"Content-Type":"application/json"},body:process.env.REQUEST_BODY}).then(async r => process.stdout.write(JSON.stringify({status:r.status,body:await r.text()}))).catch(e => { console.error(e); process.exit(1); })')"
|
||||
HTTP_CODE="$(printf '%s' "$POST_RESULT" | python -c 'import json,sys; print(json.load(sys.stdin)["status"])')"
|
||||
printf '%s' "$POST_RESULT" | python -c 'import json,sys; sys.stdout.write(json.load(sys.stdin)["body"])' >/tmp/dhv2-created.json
|
||||
if [ "$HTTP_CODE" != 201 ]; then
|
||||
echo "ERROR: real inspection create returned HTTP $HTTP_CODE" >&2
|
||||
cat /tmp/dhv2-created.json >&2
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "dhv2-web",
|
||||
"version": "0.23.0-1",
|
||||
"version": "0.23.0-2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "dhv2-web",
|
||||
"version": "0.23.0-1",
|
||||
"version": "0.23.0-2",
|
||||
"dependencies": {
|
||||
"maplibre-gl": "6.4.1",
|
||||
"react": "^19.0.0",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dhv2-web",
|
||||
"version": "0.23.0-1",
|
||||
"version": "0.23.0-2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export const APP_VERSION = '0.23.0-1';
|
||||
export const APP_VERSION = '0.23.0-2';
|
||||
export const APP_PHASE = 'F6.1 · Contexto operativo Área–Operadora consolidado';
|
||||
|
||||
@@ -90,7 +90,7 @@ export function InspectionClosurePanel({ act }: { act: InspectionActF4 }) {
|
||||
</div>
|
||||
|
||||
<div className="responsible-summary">
|
||||
<div><small>Urgencia</small><strong>{closure.act.urgency === 'URGENT' ? 'Urgente' : 'No urgente'}</strong></div>
|
||||
<div><small>Urgencia</small><strong>{closure.act.urgency === 'URGENT' ? 'Urgente' : closure.act.urgency === 'NON_URGENT' ? 'No urgente' : 'Pendiente de cierre'}</strong></div>
|
||||
<div><small>Plazo configurado</small><strong>{closure.act.deadlineDays ? `${closure.act.deadlineDays} días ${closure.act.deadlineDayType === 'BUSINESS' ? 'hábiles' : 'corridos'}` : 'Pendiente'}</strong></div>
|
||||
<div><small>Inicio del plazo</small><strong>{closure.act.deadlineBaseAt ? formatDate(closure.act.deadlineBaseAt) : 'Pendiente de evento válido'}</strong></div>
|
||||
<div><small>Vencimiento</small><strong>{closure.act.deadlineAt ? formatDate(closure.act.deadlineAt) : 'Todavía no iniciado'}</strong></div>
|
||||
|
||||
@@ -53,7 +53,7 @@ export interface InspectionActListItemF4 {
|
||||
title: string;
|
||||
summary: string;
|
||||
observations: string | null;
|
||||
urgency: InspectionActUrgencyF4;
|
||||
urgency: InspectionActUrgencyF4 | null;
|
||||
deadlineDays: number | null;
|
||||
deadlineDayType: InspectionDeadlineDayTypeF4 | null;
|
||||
deadlineBasis: InspectionDeadlineBasisF4 | null;
|
||||
@@ -107,7 +107,7 @@ export interface InspectionClosureF4 {
|
||||
code: string;
|
||||
status: InspectionActStatusF4;
|
||||
visitId: string;
|
||||
urgency: InspectionActUrgencyF4;
|
||||
urgency: InspectionActUrgencyF4 | null;
|
||||
deadlineDays: number | null;
|
||||
deadlineDayType: InspectionDeadlineDayTypeF4 | null;
|
||||
deadlineBasis: InspectionDeadlineBasisF4 | null;
|
||||
|
||||
@@ -63,7 +63,7 @@ export function InspectionActEditorPage() {
|
||||
<div className="responsible-summary">
|
||||
<div><small>Fecha y hora</small><strong>{formatDate(act.occurredAt)}</strong></div>
|
||||
<div><small>Título</small><strong>{act.title}</strong></div>
|
||||
<div><small>Urgencia</small><strong>{act.urgency === 'URGENT' ? 'Urgente' : 'No urgente'}</strong></div>
|
||||
<div><small>Urgencia</small><strong>{act.urgency === 'URGENT' ? 'Urgente' : act.urgency === 'NON_URGENT' ? 'No urgente' : 'Pendiente de cierre'}</strong></div>
|
||||
<div><small>Hallazgos</small><strong>{act.findingCount}</strong></div>
|
||||
</div>
|
||||
<div className="closure-section"><span className="eyebrow">DESCRIPCIÓN DE LO ACTUADO</span><p>{act.summary}</p>{act.observations && <><span className="eyebrow">OBSERVACIONES</span><p>{act.observations}</p></>}</div>
|
||||
|
||||
Reference in New Issue
Block a user