Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b151fe964 | ||
|
|
c748aba650 | ||
|
|
b8b578a3f0 | ||
|
|
2455a89c3e | ||
|
|
2a99183d31 | ||
|
|
675d01bea7 | ||
|
|
26d79f1e4d | ||
|
|
496bb785c1 | ||
|
|
f513817388 | ||
|
|
92a21d8f15 | ||
|
|
753fa9915f | ||
|
|
ec0ef732f7 | ||
|
|
87adf71114 | ||
|
|
0a856a1857 | ||
|
|
247c652d40 | ||
|
|
b5ee17ce95 | ||
|
|
cca2d38b98 | ||
|
|
ebce2bb957 | ||
|
|
963485618b | ||
|
|
8f051158c1 | ||
|
|
2d8425dec5 | ||
|
|
cfae2bb9ac | ||
|
|
5d8949d7d2 | ||
|
|
304adcd9b0 | ||
|
|
20dd110928 | ||
|
|
80ffb35065 | ||
|
|
6f79abbcff | ||
|
|
d18375b85b | ||
|
|
85a84e0f63 | ||
|
|
03f42209b9 | ||
|
|
74ff64182c | ||
|
|
a9e300d6a4 | ||
|
|
143db53552 | ||
|
|
d9fbd95da3 | ||
|
|
b744a77f49 | ||
|
|
082354320b | ||
|
|
71dda05c20 | ||
|
|
b88855860d | ||
|
|
ec84f42a74 | ||
|
|
b859278ad0 | ||
|
|
32fc5bc60d |
@@ -0,0 +1,15 @@
|
|||||||
|
# Checklist final Android 0.19.0
|
||||||
|
|
||||||
|
La candidata sólo se promueve si el mismo SHA cumple:
|
||||||
|
|
||||||
|
- iniciar Inspección;
|
||||||
|
- crear/abrir Acta;
|
||||||
|
- 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**;
|
||||||
|
- 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 exponer estados internos en inglés en la interfaz de campo;
|
||||||
|
- Android CI / RC, DH V2 CI y auditoría de dependencias en verde.
|
||||||
+57
-26
@@ -1,40 +1,71 @@
|
|||||||
# DH Inspección Android · release Campo Moderno 0.18.0
|
# DH Inspección Android · release final de campo 0.19.0
|
||||||
|
|
||||||
## Candidata vigente
|
## Candidata vigente
|
||||||
|
|
||||||
- Fase funcional: **Campo Moderno / UX dinámica de Inventario y Actas**.
|
- Fase funcional: **Flujo final de campo · Inspección → Acta → Hallazgos → Firma**.
|
||||||
- `versionName`: **0.18.0**.
|
- `versionName`: **0.19.0**.
|
||||||
- `versionCode`: **27**.
|
- `versionCode`: **28**.
|
||||||
- Application ID release: `com.korexlabs.dhinspeccion`.
|
- Application ID release: `com.korexlabs.dhinspeccion`.
|
||||||
- Application ID debug/QA: `com.korexlabs.dhinspeccion.debug`.
|
- Application ID debug/QA: `com.korexlabs.dhinspeccion.debug`.
|
||||||
- API: `https://dhv2.korexlabs.com/api/v3/`.
|
- API: `https://dhv2.korexlabs.com/api/v3/`.
|
||||||
|
|
||||||
La variante debug es independiente de la app productiva y puede instalarse para QA/presentación sin sobrescribir una instalación release histórica.
|
La variante debug es independiente de la app productiva y puede instalarse para QA/presentación sin sobrescribir una instalación release histórica.
|
||||||
|
|
||||||
## Novedades de campo 0.18.0
|
## Procedimiento operativo validado
|
||||||
|
|
||||||
La APK adopta una capa visual Material 3 propia de DH: superficies más limpias, jerarquía visual más clara, botones y estados más legibles, tarjetas con menor ruido y una navegación consistente entre Inspección, Actas e Inventario.
|
La APK 0.19.0 fija como recorrido principal de campo:
|
||||||
|
|
||||||
La carga de una Subinstalación mantiene la integridad del modelo físico pero reduce pasos:
|
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.
|
||||||
|
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**.
|
||||||
|
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.
|
||||||
|
|
||||||
1. el buscador de **Instalaciones padre** ahora consulta mientras el inspector escribe;
|
La nomenclatura técnica interna de API (`DRAFT`, `LOCKED`, `SEALED`, etc.) no se muestra al inspector: la interfaz usa textos operativos en castellano.
|
||||||
2. cada coincidencia aparece como tarjeta seleccionable y tocarla avanza directamente a la identificación de la Subinstalación;
|
|
||||||
3. la clasificación técnica continúa filtrada por compatibilidad con la Instalación elegida;
|
|
||||||
4. **Guardar y tomar foto** captura GPS y abre la cámara automáticamente.
|
|
||||||
|
|
||||||
Se conserva la regla de que un elemento nacido en campo no puede recibir Hallazgos hasta contar con GPS y fotografía.
|
## Alta de Instalaciones y Subinstalaciones
|
||||||
|
|
||||||
## Actas en Android
|
El alta móvil queda alineada con el Dashboard y con las validaciones del servidor.
|
||||||
|
|
||||||
El espacio de Actas fue rediseñado para mostrar con claridad:
|
### Instalación
|
||||||
|
|
||||||
- contexto de la Inspección y Yacimiento;
|
- contexto territorial: Yacimiento/Área de la Inspección;
|
||||||
- estado de cada Acta y cantidad de Hallazgos;
|
- clasificación técnica compatible;
|
||||||
- urgencia mediante selección explícita;
|
- **Nombre técnico** obligatorio;
|
||||||
- responsable de empresa, bloqueo, firmas, manifestación y sellado;
|
- Nombre habitual opcional;
|
||||||
- condición necesaria para cerrar la Inspección.
|
- Descripción opcional;
|
||||||
|
- atributos técnicos definidos por el tipo; sólo los marcados como obligatorios bloquean el guardado;
|
||||||
|
- código DH generado por el sistema cuando corresponde;
|
||||||
|
- GPS de la tablet;
|
||||||
|
- fotografía obligatoria antes de crear Hallazgos.
|
||||||
|
|
||||||
El listado que consume Android usa un read-model móvil liviano (`/inspection-visits/:visitId/acts/mobile`). Esta lectura no depende del módulo documental de oficina ni de `inspection_reports`, de modo que entrar a una Inspección en campo no queda acoplado a la proyección de Informes/GEDO.
|
### Subinstalación
|
||||||
|
|
||||||
|
Además de lo anterior requiere elegir primero la **Instalación padre**. El buscador consulta mientras se escribe y cada resultado es seleccionable tocando la tarjeta.
|
||||||
|
|
||||||
|
La clasificación y los atributos se obtienen dinámicamente desde el mismo catálogo administrado por el Dashboard; la APK no mantiene listas técnicas paralelas.
|
||||||
|
|
||||||
|
## Actas y firma
|
||||||
|
|
||||||
|
La terminología visible se simplifica:
|
||||||
|
|
||||||
|
- `DRAFT` → **En elaboración**;
|
||||||
|
- `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.
|
||||||
|
|
||||||
|
Después de la firma/cierre definitivo se mantiene el circuito documental existente: PDF del Acta e informe INF editable (DOCX) para oficina.
|
||||||
|
|
||||||
|
## Castellano e identidad visual
|
||||||
|
|
||||||
|
Se revisaron las pantallas activas de campo para evitar exponer estados y opciones internas en inglés. Entre otros cambios: Pasaporte/Otro en documentos, estados de Inspección/Acta/Hallazgo en castellano, Correo electrónico, Huella de integridad y terminología de cierre orientada al usuario.
|
||||||
|
|
||||||
|
La pantalla de ingreso y el desbloqueo biométrico utilizan la identidad visual de Mendoza ya incorporada al proyecto.
|
||||||
|
|
||||||
## Barrera obligatoria
|
## Barrera obligatoria
|
||||||
|
|
||||||
@@ -42,16 +73,16 @@ Todo cambio Android o de API que pueda afectar al cliente móvil debe pasar `And
|
|||||||
|
|
||||||
1. validación de identidad, HTTPS y políticas básicas del manifest;
|
1. validación de identidad, HTTPS y políticas básicas del manifest;
|
||||||
2. Android lint;
|
2. Android lint;
|
||||||
3. unit tests Android reales, con verificación de que exista al menos una prueba ejecutada;
|
3. pruebas unitarias Android reales, con verificación de que exista al menos una prueba ejecutada;
|
||||||
4. `assembleDebug`;
|
4. `assembleDebug`;
|
||||||
5. `assembleRelease` para comprobar que la variante productiva compile;
|
5. `assembleRelease` para comprobar que la variante productiva compile;
|
||||||
6. empaquetado del APK debug con SHA-256 y metadata de commit/versionado.
|
6. empaquetado del APK debug con SHA-256 y metadata de commit/versionado.
|
||||||
|
|
||||||
Además, `DH V2 CI` debe mantener verdes API, WEB y contrato Docker/migraciones antes de promover el cambio.
|
Además, `DH V2 CI` debe mantener verdes API, WEB y contrato Docker/migraciones antes de promover cambios que afecten al servidor.
|
||||||
|
|
||||||
## Firma release
|
## Firma release
|
||||||
|
|
||||||
La clave histórica de firma **no se versiona ni se reemplaza**. La CI compila la variante release para detectar roturas, pero la APK productiva final debe firmarse con la clave histórica antes de instalarse como actualización de `com.korexlabs.dhinspeccion`.
|
La clave histórica de firma **no se versiona ni se reemplaza**. La CI compila la variante release para detectar roturas, pero una APK productiva que deba actualizar `com.korexlabs.dhinspeccion` tiene que firmarse con la clave histórica.
|
||||||
|
|
||||||
No se debe crear una clave nueva para resolver una falta de acceso: eso rompería la continuidad de actualización de tablets que ya tengan una versión firmada con la clave anterior.
|
No se debe crear una clave nueva para resolver una falta de acceso: eso rompería la continuidad de actualización de tablets que ya tengan una versión firmada con la clave anterior.
|
||||||
|
|
||||||
@@ -60,7 +91,7 @@ No se debe crear una clave nueva para resolver una falta de acceso: eso romperí
|
|||||||
Antes de distribuir una APK productiva:
|
Antes de distribuir una APK productiva:
|
||||||
|
|
||||||
- todas las barreras de CI del SHA exacto deben estar verdes;
|
- todas las barreras de CI del SHA exacto deben estar verdes;
|
||||||
- comprobar certificado/huella de firma contra la versión histórica;
|
- comprobar certificado/huella de firma contra la versión histórica si se distribuirá como actualización productiva;
|
||||||
- realizar actualización sobre al menos una tablet con la versión productiva anterior;
|
- realizar actualización sobre al menos una tablet con la versión productiva anterior cuando corresponda;
|
||||||
- ejecutar smoke funcional contra el entorno objetivo: login, abrir Inspección, abrir Actas sin error, crear Acta, búsqueda dinámica de Instalación, selección de padre, alta de Subinstalación, GPS/foto, Hallazgo y cierre;
|
- 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.
|
- registrar el SHA Git y SHA-256 de la APK distribuida.
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ android {
|
|||||||
applicationId = "com.korexlabs.dhinspeccion"
|
applicationId = "com.korexlabs.dhinspeccion"
|
||||||
minSdk = 26
|
minSdk = 26
|
||||||
targetSdk = 36
|
targetSdk = 36
|
||||||
versionCode = 27
|
versionCode = 28
|
||||||
versionName = "0.18.0"
|
versionName = "0.19.0"
|
||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
vectorDrawables.useSupportLibrary = true
|
vectorDrawables.useSupportLibrary = true
|
||||||
|
|||||||
@@ -169,7 +169,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (acts.any { it.status == "DRAFT" }) {
|
if (acts.any { it.status == "DRAFT" }) {
|
||||||
error = "Ya existe un Acta en borrador. Bloqueala o cancelala antes de crear la siguiente."
|
error = "Ya existe un Acta en elaboración. Cerrala o cancelala antes de crear la siguiente."
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
launchBusy {
|
launchBusy {
|
||||||
@@ -241,6 +241,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
latitude: Double,
|
latitude: Double,
|
||||||
longitude: Double,
|
longitude: Double,
|
||||||
accuracyM: Double?,
|
accuracyM: Double?,
|
||||||
|
description: String? = null,
|
||||||
) {
|
) {
|
||||||
val visitId = visit?.id ?: return
|
val visitId = visit?.id ?: return
|
||||||
if (visit?.status != "IN_PROGRESS") {
|
if (visit?.status != "IN_PROGRESS") {
|
||||||
@@ -258,6 +259,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
familyId = familyId,
|
familyId = familyId,
|
||||||
name = name.trim(),
|
name = name.trim(),
|
||||||
commonName = commonName?.trim()?.takeIf { it.isNotBlank() },
|
commonName = commonName?.trim()?.takeIf { it.isNotBlank() },
|
||||||
|
description = description?.trim()?.takeIf { it.isNotBlank() },
|
||||||
attributes = attributes,
|
attributes = attributes,
|
||||||
deviceLatitude = latitude,
|
deviceLatitude = latitude,
|
||||||
deviceLongitude = longitude,
|
deviceLongitude = longitude,
|
||||||
@@ -340,7 +342,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
val assetId = selectedFieldAsset?.asset?.id ?: return
|
val assetId = selectedFieldAsset?.asset?.id ?: return
|
||||||
val draft = selectedDraftAct()
|
val draft = selectedDraftAct()
|
||||||
if (draft == null) {
|
if (draft == null) {
|
||||||
error = "Creá o seleccioná el Acta en borrador antes de registrar Hallazgos."
|
error = "Creá o seleccioná el Acta en elaboración antes de registrar Hallazgos."
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
launchBusy {
|
launchBusy {
|
||||||
@@ -362,7 +364,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
val assetId = selectedFieldAsset?.asset?.id ?: return
|
val assetId = selectedFieldAsset?.asset?.id ?: return
|
||||||
val actId = selectedDraftAct()?.id
|
val actId = selectedDraftAct()?.id
|
||||||
if (actId == null) {
|
if (actId == null) {
|
||||||
error = "No hay un Acta en borrador seleccionada."
|
error = "No hay un Acta en elaboración seleccionada."
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (description.isBlank()) {
|
if (description.isBlank()) {
|
||||||
@@ -471,7 +473,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
absenceReason = reason.trim(),
|
absenceReason = reason.trim(),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
notice = "Ausencia del responsable registrada. La manifestación de empresa quedará pendiente y deberá resolverse antes de sellar el Acta."
|
notice = "Ausencia del responsable registrada. La manifestación de empresa quedará pendiente y deberá resolverse antes de firmar y cerrar el Acta."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -480,12 +482,12 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
launchBusy {
|
launchBusy {
|
||||||
actClosure = actsRepository.lock(actId)
|
actClosure = actsRepository.lock(actId)
|
||||||
refreshSelectedActInternal(actId)
|
refreshSelectedActInternal(actId)
|
||||||
notice = "Acta bloqueada. Su contenido quedó inmutable; ahora deben resolverse las firmas y manifestaciones."
|
notice = "Acta cerrada y pendiente de firma. Su contenido quedó inmutable; las firmas y manifestaciones pueden completarse a continuación."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun reopenSelectedAct() {
|
fun reopenSelectedAct() {
|
||||||
error = "Un Acta bloqueada es inmutable y no puede volver a borrador."
|
error = "Un Acta pendiente de firma es inmutable y no puede volver a edición."
|
||||||
}
|
}
|
||||||
|
|
||||||
fun signSelectedActAsInspector(
|
fun signSelectedActAsInspector(
|
||||||
@@ -546,7 +548,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
refreshSelectedActInternal(actId)
|
refreshSelectedActInternal(actId)
|
||||||
loadActsInternal(currentVisit.id, selectDraft = false)
|
loadActsInternal(currentVisit.id, selectDraft = false)
|
||||||
clearFindingState()
|
clearFindingState()
|
||||||
notice = "${selectedAct?.code ?: "Acta"} SELLADA e inmutable. Podés crear otra Acta o continuar hacia el cierre de la Inspección."
|
notice = "${selectedAct?.code ?: "Acta"} firmada y cerrada. Podés crear otra Acta o continuar hacia el cierre de la Inspección."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -555,7 +557,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
launchBusy {
|
launchBusy {
|
||||||
visit = actsRepository.closeVisit(visitId)
|
visit = actsRepository.closeVisit(visitId)
|
||||||
loadVisitsInternal()
|
loadVisitsInternal()
|
||||||
notice = "Inspección cerrada. Todas sus Actas quedaron SELLADAS y disponibles para el circuito de oficina."
|
notice = "Inspección cerrada. Todas sus Actas quedaron firmadas y disponibles para el circuito de oficina."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -185,7 +185,7 @@ fun FieldFindingScreen(model: MainViewModel) {
|
|||||||
Text(asset.name, fontWeight = FontWeight.Bold)
|
Text(asset.name, fontWeight = FontWeight.Bold)
|
||||||
Text("${asset.code} · Acta ${options.act.code}", style = MaterialTheme.typography.bodySmall)
|
Text("${asset.code} · Acta ${options.act.code}", style = MaterialTheme.typography.bodySmall)
|
||||||
Text(
|
Text(
|
||||||
"GPS + foto del Inventario: ${if (options.capture.readyForFinding) "OK" else "pendiente"}",
|
"GPS + foto del Inventario: ${if (options.capture.readyForFinding) "completo" else "pendiente"}",
|
||||||
color = if (options.capture.readyForFinding) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error,
|
color = if (options.capture.readyForFinding) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error,
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
)
|
)
|
||||||
@@ -210,7 +210,7 @@ fun FieldFindingScreen(model: MainViewModel) {
|
|||||||
Card(Modifier.fillMaxWidth()) {
|
Card(Modifier.fillMaxWidth()) {
|
||||||
Column(Modifier.padding(10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
Column(Modifier.padding(10.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||||
Text("${finding.code} · ${finding.title}", fontWeight = FontWeight.SemiBold)
|
Text("${finding.code} · ${finding.title}", fontWeight = FontWeight.SemiBold)
|
||||||
Text("Gravedad: ${finding.severity ?: "s/d"} · ${finding.status}", style = MaterialTheme.typography.bodySmall)
|
Text("Gravedad: ${finding.severity ?: "s/d"} · ${findingStatusLabelEs(finding.status)}", style = MaterialTheme.typography.bodySmall)
|
||||||
Text(
|
Text(
|
||||||
"Evidencias: ${evidence.size} · Fotos: ${evidence.count { it.kind == "PHOTO" }}",
|
"Evidencias: ${evidence.size} · Fotos: ${evidence.count { it.kind == "PHOTO" }}",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
|||||||
@@ -3,11 +3,13 @@ package com.korexlabs.dhinspeccion.ui
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import androidx.biometric.BiometricManager
|
import androidx.biometric.BiometricManager
|
||||||
import androidx.biometric.BiometricPrompt
|
import androidx.biometric.BiometricPrompt
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Visibility
|
import androidx.compose.material.icons.filled.Visibility
|
||||||
@@ -29,7 +31,9 @@ import androidx.compose.runtime.saveable.rememberSaveable
|
|||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.layout.ContentScale
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.painterResource
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
import androidx.compose.ui.text.input.VisualTransformation
|
import androidx.compose.ui.text.input.VisualTransformation
|
||||||
@@ -37,6 +41,7 @@ import androidx.compose.ui.unit.dp
|
|||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
import androidx.fragment.app.FragmentActivity
|
import androidx.fragment.app.FragmentActivity
|
||||||
import com.korexlabs.dhinspeccion.MainViewModel
|
import com.korexlabs.dhinspeccion.MainViewModel
|
||||||
|
import com.korexlabs.dhinspeccion.R
|
||||||
|
|
||||||
private const val BIOMETRIC_PREFS = "dh_v2_biometric"
|
private const val BIOMETRIC_PREFS = "dh_v2_biometric"
|
||||||
private const val BIOMETRIC_ENABLED = "enabled"
|
private const val BIOMETRIC_ENABLED = "enabled"
|
||||||
@@ -105,7 +110,13 @@ private fun EnhancedLoginScreen(model: MainViewModel, onPasswordLogin: () -> Uni
|
|||||||
var passwordVisible by rememberSaveable { mutableStateOf(false) }
|
var passwordVisible by rememberSaveable { mutableStateOf(false) }
|
||||||
|
|
||||||
Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) {
|
Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) {
|
||||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(14.dp)) {
|
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(14.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||||
|
Image(
|
||||||
|
painter = painterResource(R.drawable.ic_mendoza_launcher_exact),
|
||||||
|
contentDescription = "Gobierno de Mendoza",
|
||||||
|
modifier = Modifier.fillMaxWidth().height(170.dp),
|
||||||
|
contentScale = ContentScale.Fit,
|
||||||
|
)
|
||||||
Text("DH Inspección", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
|
Text("DH Inspección", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
|
||||||
Text("Aplicación de campo · Dirección de Hidrocarburos")
|
Text("Aplicación de campo · Dirección de Hidrocarburos")
|
||||||
model.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
model.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||||
@@ -113,7 +124,7 @@ private fun EnhancedLoginScreen(model: MainViewModel, onPasswordLogin: () -> Uni
|
|||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = identifier,
|
value = identifier,
|
||||||
onValueChange = { identifier = it },
|
onValueChange = { identifier = it },
|
||||||
label = { Text("Usuario o email") },
|
label = { Text("Usuario o correo electrónico") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
)
|
)
|
||||||
@@ -198,6 +209,12 @@ private fun BiometricUnlockScreen(
|
|||||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
) {
|
) {
|
||||||
|
Image(
|
||||||
|
painter = painterResource(R.drawable.ic_mendoza_launcher_exact),
|
||||||
|
contentDescription = "Gobierno de Mendoza",
|
||||||
|
modifier = Modifier.fillMaxWidth().height(140.dp),
|
||||||
|
contentScale = ContentScale.Fit,
|
||||||
|
)
|
||||||
Text("DH Inspección", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
|
Text("DH Inspección", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
|
||||||
Text("Ingresá con tu huella")
|
Text("Ingresá con tu huella")
|
||||||
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||||
|
|||||||
@@ -215,7 +215,7 @@ private fun MobileVisitCard(visit: VisitSummary, onOpen: () -> Unit) {
|
|||||||
Column(Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
Column(Modifier.padding(14.dp), verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||||
Text(visit.code, fontWeight = FontWeight.Bold)
|
Text(visit.code, fontWeight = FontWeight.Bold)
|
||||||
Text(visit.status)
|
Text(visitStatusLabelEs(visit.status))
|
||||||
}
|
}
|
||||||
Text(visit.operatorCompany?.name ?: "Operadora sin definir")
|
Text(visit.operatorCompany?.name ?: "Operadora sin definir")
|
||||||
Text(visit.operationalArea?.name ?: "Área sin definir", style = MaterialTheme.typography.bodySmall)
|
Text(visit.operationalArea?.name ?: "Área sin definir", style = MaterialTheme.typography.bodySmall)
|
||||||
|
|||||||
+17
-23
@@ -245,7 +245,7 @@ fun ModernMobileActsScreen(
|
|||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
if (newActUrgency == "URGENT") {
|
if (newActUrgency == "URGENT") {
|
||||||
"El plazo urgente se computará desde el Acta conforme a la política institucional vigente al bloquearla."
|
"El plazo urgente se computará desde el Acta conforme a la política institucional vigente al cerrar su contenido."
|
||||||
} else {
|
} else {
|
||||||
"El plazo no urgente comienza con la oficialización GEDO, no al crear el Acta."
|
"El plazo no urgente comienza con la oficialización GEDO, no al crear el Acta."
|
||||||
},
|
},
|
||||||
@@ -319,12 +319,12 @@ fun ModernMobileActsScreen(
|
|||||||
OutlinedTextField(fullName, { fullName = it }, label = { Text("Nombre y apellido *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
OutlinedTextField(fullName, { fullName = it }, label = { Text("Nombre y apellido *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||||
listOf("DNI", "CUIL", "PASSPORT", "OTHER").forEach { kind ->
|
listOf("DNI", "CUIL", "PASSPORT", "OTHER").forEach { kind ->
|
||||||
FilterChip(selected = documentType == kind, onClick = { documentType = kind }, label = { Text(kind) })
|
FilterChip(selected = documentType == kind, onClick = { documentType = kind }, label = { Text(documentTypeLabelEs(kind)) })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
OutlinedTextField(documentNumber, { documentNumber = it }, label = { Text("Documento *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
OutlinedTextField(documentNumber, { documentNumber = it }, label = { Text("Documento *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||||
OutlinedTextField(position, { position = it }, label = { Text("Cargo *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
OutlinedTextField(position, { position = it }, label = { Text("Cargo *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||||
OutlinedTextField(email, { email = it }, label = { Text("Email") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
OutlinedTextField(email, { email = it }, label = { Text("Correo electrónico") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||||
OutlinedTextField(phone, { phone = it }, label = { Text("Teléfono") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
OutlinedTextField(phone, { phone = it }, label = { Text("Teléfono") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||||
Button(
|
Button(
|
||||||
onClick = { model.setCompanyResponsiblePresent(fullName, documentType, documentNumber, position, email, phone) },
|
onClick = { model.setCompanyResponsiblePresent(fullName, documentType, documentNumber, position, email, phone) },
|
||||||
@@ -353,17 +353,17 @@ fun ModernMobileActsScreen(
|
|||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
Icon(Icons.Filled.Lock, null, tint = MaterialTheme.colorScheme.error)
|
Icon(Icons.Filled.Lock, null, tint = MaterialTheme.colorScheme.error)
|
||||||
Spacer(Modifier.width(8.dp))
|
Spacer(Modifier.width(8.dp))
|
||||||
Text("Finalizar contenido", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
Text("Cerrar Acta", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||||
}
|
}
|
||||||
Text(
|
Text(
|
||||||
"Al bloquear el Acta, su contenido y sus Hallazgos quedan inmutables.",
|
"Al cerrar el contenido, el Acta queda inmutable y pasa a Pendiente de firma. Podés firmarla ahora o continuar con otra Acta.",
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
Button(
|
Button(
|
||||||
onClick = { model.prepareSelectedAct() },
|
onClick = { model.prepareSelectedAct() },
|
||||||
enabled = !model.busy && closure?.responsible != null,
|
enabled = !model.busy && closure?.responsible != null,
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
) { Text("Finalizar y BLOQUEAR Acta") }
|
) { Text("Cerrar Acta y dejar pendiente de firma") }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -379,10 +379,10 @@ fun ModernMobileActsScreen(
|
|||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
Icon(Icons.Filled.Lock, null, tint = MaterialTheme.colorScheme.secondary)
|
Icon(Icons.Filled.Lock, null, tint = MaterialTheme.colorScheme.secondary)
|
||||||
Spacer(Modifier.width(8.dp))
|
Spacer(Modifier.width(8.dp))
|
||||||
Text("Acta BLOQUEADA", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
Text("Acta pendiente de firma", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||||
}
|
}
|
||||||
Text("El contenido ya es inmutable. Restan firmas y manifestaciones para poder sellarla.")
|
Text("El contenido ya está cerrado e inmutable. Completá la firma del inspector y la manifestación de la empresa cuando corresponda.")
|
||||||
closure?.closure?.preparedSha256?.let { Text("Hash · $it", style = MaterialTheme.typography.bodySmall) }
|
closure?.closure?.preparedSha256?.let { Text("Huella de integridad · $it", style = MaterialTheme.typography.bodySmall) }
|
||||||
|
|
||||||
HorizontalDivider()
|
HorizontalDivider()
|
||||||
Text("Firma del inspector", fontWeight = FontWeight.Bold)
|
Text("Firma del inspector", fontWeight = FontWeight.Bold)
|
||||||
@@ -403,7 +403,7 @@ fun ModernMobileActsScreen(
|
|||||||
val detail = when (companyOutcome.status) {
|
val detail = when (companyOutcome.status) {
|
||||||
"SIGNED" -> if (companyOutcome.companyManifestation == "DISSENT") "Firma en disidencia" else "Firma en conformidad"
|
"SIGNED" -> if (companyOutcome.companyManifestation == "DISSENT") "Firma en disidencia" else "Firma en conformidad"
|
||||||
"REFUSED" -> "Negativa a firmar"
|
"REFUSED" -> "Negativa a firmar"
|
||||||
else -> companyOutcome.status
|
else -> humanBackendLabelEs(companyOutcome.status)
|
||||||
}
|
}
|
||||||
SuccessLine(detail)
|
SuccessLine(detail)
|
||||||
companyOutcome.reason?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
companyOutcome.reason?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||||
@@ -413,7 +413,7 @@ fun ModernMobileActsScreen(
|
|||||||
Row(Modifier.padding(12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
Row(Modifier.padding(12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
Icon(Icons.Filled.ErrorOutline, null, tint = MaterialTheme.colorScheme.error)
|
Icon(Icons.Filled.ErrorOutline, null, tint = MaterialTheme.colorScheme.error)
|
||||||
Text(
|
Text(
|
||||||
"La ausencia no resuelve la manifestación. Debe registrarse firma o negativa antes de sellar.",
|
"La ausencia no resuelve la manifestación. Debe registrarse firma o negativa antes de firmar y cerrar el Acta.",
|
||||||
Modifier.weight(1f),
|
Modifier.weight(1f),
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
)
|
)
|
||||||
@@ -462,7 +462,7 @@ fun ModernMobileActsScreen(
|
|||||||
) {
|
) {
|
||||||
Icon(Icons.Filled.CheckCircle, null)
|
Icon(Icons.Filled.CheckCircle, null)
|
||||||
Spacer(Modifier.width(6.dp))
|
Spacer(Modifier.width(6.dp))
|
||||||
Text("SELLAR Acta definitivamente")
|
Text("Firmar y cerrar Acta")
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Text(
|
Text(
|
||||||
@@ -480,8 +480,8 @@ fun ModernMobileActsScreen(
|
|||||||
Row(Modifier.padding(18.dp), horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.Top) {
|
Row(Modifier.padding(18.dp), horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.Top) {
|
||||||
Icon(Icons.Filled.CheckCircle, null, tint = MaterialTheme.colorScheme.primary)
|
Icon(Icons.Filled.CheckCircle, null, tint = MaterialTheme.colorScheme.primary)
|
||||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||||
Text("Acta SELLADA e inmutable", fontWeight = FontWeight.Bold)
|
Text("Acta firmada y cerrada", fontWeight = FontWeight.Bold)
|
||||||
Text("Desde este sellado se genera el PDF del Acta y el INF Word editable para el Inspector.")
|
Text("Desde este cierre se genera el PDF del Acta y el informe INF editable (DOCX) para el Inspector.")
|
||||||
closure?.closure?.finalSha256?.let { Text("SHA-256 · $it", style = MaterialTheme.typography.bodySmall) }
|
closure?.closure?.finalSha256?.let { Text("SHA-256 · $it", style = MaterialTheme.typography.bodySmall) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -503,10 +503,10 @@ fun ModernMobileActsScreen(
|
|||||||
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(9.dp)) {
|
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(9.dp)) {
|
||||||
Text("Finalizar Inspección", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
Text("Finalizar Inspección", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||||
if (pendingActs.isEmpty()) {
|
if (pendingActs.isEmpty()) {
|
||||||
SuccessLine("Todas las Actas están SELLADAS")
|
SuccessLine("Todas las Actas están firmadas y cerradas")
|
||||||
} else {
|
} else {
|
||||||
Text(
|
Text(
|
||||||
"Falta SELLAR: ${pendingActs.joinToString { it.code }}",
|
"Falta firmar y cerrar: ${pendingActs.joinToString { it.code }}",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.error,
|
color = MaterialTheme.colorScheme.error,
|
||||||
)
|
)
|
||||||
@@ -531,13 +531,7 @@ private fun SuccessLine(text: String) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun modernActStatusLabel(status: String): String = when (status) {
|
private fun modernActStatusLabel(status: String): String = actStatusLabelEs(status)
|
||||||
"DRAFT" -> "Borrador"
|
|
||||||
"LOCKED" -> "Bloqueada"
|
|
||||||
"SEALED" -> "Sellada"
|
|
||||||
"CANCELLED" -> "Cancelada"
|
|
||||||
else -> status
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun hasModernActLocation(context: Context): Boolean =
|
private fun hasModernActLocation(context: Context): Boolean =
|
||||||
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
|
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
|
||||||
|
|||||||
@@ -274,7 +274,7 @@ private fun ModernChecklistCard(visit: VisitDetail) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (checklist.stale) {
|
if (checklist.stale) {
|
||||||
Text("El checklist requiere actualización.", color = MaterialTheme.colorScheme.error)
|
Text("La lista de control requiere actualización.", color = MaterialTheme.colorScheme.error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -296,6 +296,7 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
|||||||
var parentLabel by rememberSaveable(visit.id) { mutableStateOf("") }
|
var parentLabel by rememberSaveable(visit.id) { mutableStateOf("") }
|
||||||
var name by rememberSaveable(visit.id) { mutableStateOf("") }
|
var name by rememberSaveable(visit.id) { mutableStateOf("") }
|
||||||
var commonName by rememberSaveable(visit.id) { mutableStateOf("") }
|
var commonName by rememberSaveable(visit.id) { mutableStateOf("") }
|
||||||
|
var description by rememberSaveable(visit.id) { mutableStateOf("") }
|
||||||
var selectedTypeId by rememberSaveable(visit.id) { mutableStateOf<String?>(null) }
|
var selectedTypeId by rememberSaveable(visit.id) { mutableStateOf<String?>(null) }
|
||||||
var selectedFamilyId by rememberSaveable(visit.id) { mutableStateOf<String?>(null) }
|
var selectedFamilyId by rememberSaveable(visit.id) { mutableStateOf<String?>(null) }
|
||||||
var familySearch by rememberSaveable(visit.id) { mutableStateOf("") }
|
var familySearch by rememberSaveable(visit.id) { mutableStateOf("") }
|
||||||
@@ -311,6 +312,7 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
|||||||
fun resetForm() {
|
fun resetForm() {
|
||||||
name = ""
|
name = ""
|
||||||
commonName = ""
|
commonName = ""
|
||||||
|
description = ""
|
||||||
selectedTypeId = null
|
selectedTypeId = null
|
||||||
selectedFamilyId = null
|
selectedFamilyId = null
|
||||||
familySearch = ""
|
familySearch = ""
|
||||||
@@ -444,6 +446,7 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
|||||||
familyId = selectedFamilyId,
|
familyId = selectedFamilyId,
|
||||||
name = name,
|
name = name,
|
||||||
commonName = commonName,
|
commonName = commonName,
|
||||||
|
description = description,
|
||||||
attributes = buildModernAttributes(type, attributeValues),
|
attributes = buildModernAttributes(type, attributeValues),
|
||||||
latitude = geo.latitude,
|
latitude = geo.latitude,
|
||||||
longitude = geo.longitude,
|
longitude = geo.longitude,
|
||||||
@@ -800,18 +803,26 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
|||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = name,
|
value = name,
|
||||||
onValueChange = { name = it },
|
onValueChange = { name = it },
|
||||||
label = { Text("Nombre o código visible *") },
|
label = { Text("Nombre técnico *") },
|
||||||
supportingText = { Text("Usá lo que figura en placa o identifica el elemento en campo.") },
|
supportingText = { Text("Usá la denominación técnica del elemento. El código DH se genera automáticamente.") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
)
|
)
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = commonName,
|
value = commonName,
|
||||||
onValueChange = { commonName = it },
|
onValueChange = { commonName = it },
|
||||||
label = { Text("Nombre habitual") },
|
label = { Text("Nombre habitual (opcional)") },
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
singleLine = true,
|
singleLine = true,
|
||||||
)
|
)
|
||||||
|
OutlinedTextField(
|
||||||
|
value = description,
|
||||||
|
onValueChange = { description = it },
|
||||||
|
label = { Text("Descripción (opcional)") },
|
||||||
|
supportingText = { Text("Dato equivalente al alta desde el panel web.") },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
minLines = 2,
|
||||||
|
)
|
||||||
|
|
||||||
selectedType?.attributes?.forEach { definition ->
|
selectedType?.attributes?.forEach { definition ->
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
@@ -1066,20 +1077,14 @@ private fun ModernStepHeader(step: Int, title: String) {
|
|||||||
|
|
||||||
private fun modernItemTypeCode(item: FieldInventoryItem): String {
|
private fun modernItemTypeCode(item: FieldInventoryItem): String {
|
||||||
val type = item.type ?: return ""
|
val type = item.type ?: return ""
|
||||||
return modernNormalize(type.typeName ?: type.name)
|
return modernNormalize(type.code.ifBlank { type.typeName ?: type.name })
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun modernNormalize(value: String): String = value.trim().lowercase()
|
private fun modernNormalize(value: String): String = value.trim().lowercase()
|
||||||
.replace('ó', 'o').replace('í', 'i').replace('á', 'a').replace('é', 'e').replace('ú', 'u')
|
.replace('ó', 'o').replace('í', 'i').replace('á', 'a').replace('é', 'e').replace('ú', 'u')
|
||||||
.replace("_", "").replace("-", "").replace(" ", "")
|
.replace("_", "").replace("-", "").replace(" ", "")
|
||||||
|
|
||||||
private fun modernStatusLabel(status: String): String = when (status) {
|
private fun modernStatusLabel(status: String): String = visitStatusLabelEs(status)
|
||||||
"PLANNED" -> "Planificada"
|
|
||||||
"IN_PROGRESS" -> "En curso"
|
|
||||||
"CLOSED" -> "Cerrada"
|
|
||||||
"CANCELLED" -> "Cancelada"
|
|
||||||
else -> status
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun buildModernAttributes(type: FieldType, values: Map<String, String>): Map<String, Any?> =
|
private fun buildModernAttributes(type: FieldType, values: Map<String, String>): Map<String, Any?> =
|
||||||
type.attributes.mapNotNull { definition ->
|
type.attributes.mapNotNull { definition ->
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ fun SignaturePad(
|
|||||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
Text(label, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold)
|
Text(label, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold)
|
||||||
Text(
|
Text(
|
||||||
"Firmá dentro del recuadro. La imagen se guarda como PNG y se incorpora al hash del Acta.",
|
"Firmá dentro del recuadro. La imagen se guarda como PNG y se incorpora a la huella de integridad del Acta.",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
)
|
)
|
||||||
Canvas(
|
Canvas(
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package com.korexlabs.dhinspeccion.ui
|
||||||
|
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
internal fun visitStatusLabelEs(status: String?): String = when (status?.uppercase(Locale.ROOT)) {
|
||||||
|
"PLANNED" -> "Planificada"
|
||||||
|
"IN_PROGRESS" -> "En curso"
|
||||||
|
"CLOSED" -> "Cerrada"
|
||||||
|
"CANCELLED" -> "Cancelada"
|
||||||
|
null, "" -> "Sin estado"
|
||||||
|
else -> humanBackendLabelEs(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun actStatusLabelEs(status: String?): String = when (status?.uppercase(Locale.ROOT)) {
|
||||||
|
"DRAFT" -> "En elaboración"
|
||||||
|
"LOCKED" -> "Pendiente de firma"
|
||||||
|
"SEALED" -> "Firmada y cerrada"
|
||||||
|
"CLOSED" -> "Cerrada"
|
||||||
|
"RECTIFIED" -> "Rectificada"
|
||||||
|
"CANCELLED" -> "Cancelada"
|
||||||
|
null, "" -> "Sin estado"
|
||||||
|
else -> humanBackendLabelEs(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun findingStatusLabelEs(status: String?): String = when (status?.uppercase(Locale.ROOT)) {
|
||||||
|
"OPEN" -> "Abierto"
|
||||||
|
"PENDING" -> "Pendiente"
|
||||||
|
"COMPANY_RESPONSE_PENDING" -> "Pendiente de respuesta de la empresa"
|
||||||
|
"COMPANY_RESPONDED" -> "Respondido por la empresa"
|
||||||
|
"VERIFICATION_PENDING" -> "Pendiente de verificación"
|
||||||
|
"VERIFICATION_SCHEDULED" -> "Verificación programada"
|
||||||
|
"READY_TO_CLOSE" -> "Listo para cierre"
|
||||||
|
"CLOSED" -> "Cerrado"
|
||||||
|
"CANCELLED" -> "Cancelado"
|
||||||
|
null, "" -> "Sin estado"
|
||||||
|
else -> humanBackendLabelEs(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun documentTypeLabelEs(type: String): String = when (type.uppercase(Locale.ROOT)) {
|
||||||
|
"DNI" -> "DNI"
|
||||||
|
"CUIL" -> "CUIL"
|
||||||
|
"PASSPORT" -> "Pasaporte"
|
||||||
|
"OTHER" -> "Otro"
|
||||||
|
else -> humanBackendLabelEs(type)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun humanBackendLabelEs(value: String): String {
|
||||||
|
val clean = value.trim().replace('_', ' ').replace('-', ' ').lowercase(Locale("es", "AR"))
|
||||||
|
return clean.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale("es", "AR")) else it.toString() }
|
||||||
|
}
|
||||||
+57
@@ -0,0 +1,57 @@
|
|||||||
|
package com.korexlabs.dhinspeccion
|
||||||
|
|
||||||
|
import java.io.File
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class FinalFieldFlowContractTest {
|
||||||
|
private val visit = File("src/main/java/com/korexlabs/dhinspeccion/ui/ModernVisitRoot.kt").readText()
|
||||||
|
private val acts = File("src/main/java/com/korexlabs/dhinspeccion/ui/ModernMobileActsScreen.kt").readText()
|
||||||
|
private val findings = File("src/main/java/com/korexlabs/dhinspeccion/ui/FieldFindingScreen.kt").readText()
|
||||||
|
private val home = File("src/main/java/com/korexlabs/dhinspeccion/ui/MobileHomeScreen.kt").readText()
|
||||||
|
private val labels = File("src/main/java/com/korexlabs/dhinspeccion/ui/UiSpanishLabels.kt").readText()
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun inspectionActFindingFlowMatchesFieldProcedure() {
|
||||||
|
assertTrue(visit.contains("Iniciar inspección"))
|
||||||
|
assertTrue(acts.contains("Crear nueva Acta"))
|
||||||
|
assertTrue(acts.contains("Agregar Hallazgo"))
|
||||||
|
assertTrue(visit.contains("Instalación"))
|
||||||
|
assertTrue(visit.contains("Subinstalación"))
|
||||||
|
assertTrue(visit.contains("Guardar y tomar foto"))
|
||||||
|
assertTrue(acts.contains("Cerrar Acta y dejar pendiente de firma"))
|
||||||
|
assertTrue(labels.contains("\"LOCKED\" -> \"Pendiente de firma\""))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun fieldCreateKeepsDashboardEquivalentMinimumAndCaptureBarrier() {
|
||||||
|
assertTrue(visit.contains("Nombre técnico *"))
|
||||||
|
assertTrue(visit.contains("Nombre habitual (opcional)"))
|
||||||
|
assertTrue(visit.contains("Descripción (opcional)"))
|
||||||
|
assertTrue(visit.contains("familyReady"))
|
||||||
|
assertTrue(visit.contains("attributesReady"))
|
||||||
|
assertTrue(visit.contains("GPS + foto"))
|
||||||
|
assertTrue(visit.contains("La foto es obligatoria antes de registrar Hallazgos"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun structuralSelectionUsesTheServerTypeCode() {
|
||||||
|
assertTrue(visit.contains("type.code.ifBlank { type.typeName ?: type.name }"))
|
||||||
|
assertTrue(visit.contains("modernItemTypeCode(it) in setOf(\"instalacion\", \"subinstalacion\")"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun currentFieldUiDoesNotExposeBackendEnglishStates() {
|
||||||
|
assertTrue(home.contains("visitStatusLabelEs(visit.status)"))
|
||||||
|
assertTrue(findings.contains("findingStatusLabelEs(finding.status)"))
|
||||||
|
assertTrue(acts.contains("documentTypeLabelEs(kind)"))
|
||||||
|
assertTrue(labels.contains("\"PASSPORT\" -> \"Pasaporte\""))
|
||||||
|
assertTrue(labels.contains("\"OTHER\" -> \"Otro\""))
|
||||||
|
assertFalse(acts.contains("Finalizar y BLOQUEAR Acta"))
|
||||||
|
assertFalse(acts.contains("Acta BLOQUEADA"))
|
||||||
|
assertFalse(acts.contains("SELLAR Acta"))
|
||||||
|
assertFalse(acts.contains("Acta SELLADA"))
|
||||||
|
assertFalse(acts.contains("Text(\"Email\")"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,8 +8,8 @@ class ReleaseMetadataTest {
|
|||||||
@Test
|
@Test
|
||||||
fun debugBuildKeepsSeparateApplicationIdentity() {
|
fun debugBuildKeepsSeparateApplicationIdentity() {
|
||||||
assertEquals("com.korexlabs.dhinspeccion.debug", BuildConfig.APPLICATION_ID)
|
assertEquals("com.korexlabs.dhinspeccion.debug", BuildConfig.APPLICATION_ID)
|
||||||
assertEquals(27, BuildConfig.VERSION_CODE)
|
assertEquals(28, BuildConfig.VERSION_CODE)
|
||||||
assertEquals("0.18.0-debug", BuildConfig.VERSION_NAME)
|
assertEquals("0.19.0-debug", BuildConfig.VERSION_NAME)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -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', () => {
|
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');
|
const gradle = mountedRepoFile('android-app/app/build.gradle.kts');
|
||||||
|
|
||||||
assert.match(gradle, /versionCode = 27/);
|
assert.match(gradle, /versionCode = 28/);
|
||||||
assert.match(gradle, /versionName = "0\.18\.0"/);
|
assert.match(gradle, /versionName = "0\.19\.0"/);
|
||||||
assert.match(gradle, /https:\/\/dhv2\.korexlabs\.com\/api\/v3\//);
|
assert.match(gradle, /https:\/\/dhv2\.korexlabs\.com\/api\/v3\//);
|
||||||
assert.match(gradle, /applicationIdSuffix = "\.debug"/);
|
assert.match(gradle, /applicationIdSuffix = "\.debug"/);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import { AccessDeniedPage, NotFoundPage } from '../pages/SystemPages';
|
|||||||
import { UserDetailPage } from '../pages/UserDetailPage';
|
import { UserDetailPage } from '../pages/UserDetailPage';
|
||||||
import { UsersPage } from '../pages/UsersPage';
|
import { UsersPage } from '../pages/UsersPage';
|
||||||
import { AssetsPage } from '../pages/AssetsPage';
|
import { AssetsPage } from '../pages/AssetsPage';
|
||||||
import { AssetEditorPage } from '../pages/AssetEditorPage';
|
import { InventoryDetailPage } from '../pages/InventoryDetailPage';
|
||||||
import { InventoryCreatePage } from '../pages/InventoryCreatePage';
|
import { InventoryCreatePage } from '../pages/InventoryCreatePage';
|
||||||
import { FieldDiscoveriesPage } from '../pages/FieldDiscoveriesPage';
|
import { FieldDiscoveriesPage } from '../pages/FieldDiscoveriesPage';
|
||||||
import { AuthoritativeInventoryConfigPage } from '../pages/AuthoritativeInventoryConfigPage';
|
import { AuthoritativeInventoryConfigPage } from '../pages/AuthoritativeInventoryConfigPage';
|
||||||
@@ -49,9 +49,9 @@ export function App() {
|
|||||||
<Route element={<PermissionRoute permission="assets.read" />}><Route path="/mapa" element={<MapPage />} /></Route>
|
<Route element={<PermissionRoute permission="assets.read" />}><Route path="/mapa" element={<MapPage />} /></Route>
|
||||||
<Route element={<PermissionRoute permission="assets.read" />}>
|
<Route element={<PermissionRoute permission="assets.read" />}>
|
||||||
<Route path="/inventarios" element={<AssetsPage />} />
|
<Route path="/inventarios" element={<AssetsPage />} />
|
||||||
<Route path="/inventarios/:id" element={<AssetEditorPage />} />
|
<Route path="/inventarios/:id" element={<InventoryDetailPage />} />
|
||||||
<Route path="/activos" element={<Navigate to="/inventarios" replace />} />
|
<Route path="/activos" element={<Navigate to="/inventarios" replace />} />
|
||||||
<Route path="/activos/:id" element={<AssetEditorPage />} />
|
<Route path="/activos/:id" element={<InventoryDetailPage />} />
|
||||||
</Route>
|
</Route>
|
||||||
<Route element={<PermissionRoute permission="assets.change_status" />}><Route path="/inventarios/revision-campo" element={<FieldDiscoveriesPage />} /></Route>
|
<Route element={<PermissionRoute permission="assets.change_status" />}><Route path="/inventarios/revision-campo" element={<FieldDiscoveriesPage />} /></Route>
|
||||||
<Route element={<PermissionRoute permission="assets.create" />}><Route path="/inventarios/nuevo" element={<InventoryCreatePage />} /><Route path="/activos/nuevo" element={<Navigate to="/inventarios/nuevo" replace />} /></Route>
|
<Route element={<PermissionRoute permission="assets.create" />}><Route path="/inventarios/nuevo" element={<InventoryCreatePage />} /><Route path="/activos/nuevo" element={<Navigate to="/inventarios/nuevo" replace />} /></Route>
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import type { AuthUser } from '../lib/api';
|
||||||
|
|
||||||
|
function normalizeRole(value: string) {
|
||||||
|
return value
|
||||||
|
.normalize('NFD')
|
||||||
|
.replace(/[\u0300-\u036f]/g, '')
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, ' ')
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
const ADMIN_ROLES = new Set([
|
||||||
|
'admin',
|
||||||
|
'administrator',
|
||||||
|
'administrador',
|
||||||
|
'superadmin',
|
||||||
|
'super admin',
|
||||||
|
'superadministrator',
|
||||||
|
'super administrator',
|
||||||
|
'superadministrador',
|
||||||
|
'super administrador',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export function hasAdministratorRole(user: AuthUser | null) {
|
||||||
|
return Boolean(user?.roles.some((role) => ADMIN_ROLES.has(normalizeRole(role))));
|
||||||
|
}
|
||||||
@@ -34,10 +34,10 @@ function supportsFunctionChange(code: string, name: string): boolean {
|
|||||||
|
|
||||||
export function AssetHistoryPanel({
|
export function AssetHistoryPanel({
|
||||||
assetId,
|
assetId,
|
||||||
refreshKey,
|
refreshKey = 0,
|
||||||
}: {
|
}: {
|
||||||
assetId: string;
|
assetId: string;
|
||||||
refreshKey: number;
|
refreshKey?: number;
|
||||||
}) {
|
}) {
|
||||||
const [versions, setVersions] = useState<AssetVersionSummary[]>([]);
|
const [versions, setVersions] = useState<AssetVersionSummary[]>([]);
|
||||||
const [total, setTotal] = useState(0);
|
const [total, setTotal] = useState(0);
|
||||||
|
|||||||
@@ -52,12 +52,12 @@ export function AssetMediaPanel({
|
|||||||
assetId,
|
assetId,
|
||||||
assetName,
|
assetName,
|
||||||
canManage,
|
canManage,
|
||||||
onChanged,
|
onChanged = () => undefined,
|
||||||
}: {
|
}: {
|
||||||
assetId: string;
|
assetId: string;
|
||||||
assetName: string;
|
assetName: string;
|
||||||
canManage: boolean;
|
canManage: boolean;
|
||||||
onChanged: () => void;
|
onChanged?: () => void;
|
||||||
}) {
|
}) {
|
||||||
const fileRef = useRef<HTMLInputElement | null>(null);
|
const fileRef = useRef<HTMLInputElement | null>(null);
|
||||||
const [items, setItems] = useState<AssetMedia[]>([]);
|
const [items, setItems] = useState<AssetMedia[]>([]);
|
||||||
|
|||||||
@@ -0,0 +1,215 @@
|
|||||||
|
.asset-compact-form {
|
||||||
|
gap: 0;
|
||||||
|
padding: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-section {
|
||||||
|
display: grid;
|
||||||
|
gap: 14px;
|
||||||
|
padding: 20px 22px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-section-heading {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-section-heading h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 17px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-primary-grid {
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-meta {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-meta > span {
|
||||||
|
min-width: 0;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 7px;
|
||||||
|
padding: 7px 10px;
|
||||||
|
border: 1px solid #e0e5ed;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #f8fafc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-meta small {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 9px;
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: .05em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-meta strong {
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
color: var(--ink);
|
||||||
|
font-size: 11px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-context-button {
|
||||||
|
min-height: 34px;
|
||||||
|
padding: 7px 11px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-context-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-context-item {
|
||||||
|
min-width: 0;
|
||||||
|
display: grid;
|
||||||
|
gap: 3px;
|
||||||
|
padding: 12px 13px;
|
||||||
|
border: 1px solid #e1e6ee;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: #f8fafc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-context-item small {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 9px;
|
||||||
|
font-weight: 750;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: .05em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-context-item strong {
|
||||||
|
overflow: hidden;
|
||||||
|
color: var(--ink);
|
||||||
|
font-size: 12px;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-context-item span {
|
||||||
|
overflow: hidden;
|
||||||
|
color: var(--muted);
|
||||||
|
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||||
|
font-size: 9px;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-details {
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-details > summary {
|
||||||
|
min-height: 54px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 14px;
|
||||||
|
padding: 13px 22px;
|
||||||
|
cursor: pointer;
|
||||||
|
list-style: none;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-details > summary::-webkit-details-marker {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-details > summary:hover {
|
||||||
|
background: #f8fafc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-details > summary > span:first-child {
|
||||||
|
min-width: 0;
|
||||||
|
display: grid;
|
||||||
|
gap: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-details > summary strong {
|
||||||
|
color: var(--ink);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-details > summary small {
|
||||||
|
overflow: hidden;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 10px;
|
||||||
|
font-weight: 500;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-details > summary > span:last-child {
|
||||||
|
color: #7b8496;
|
||||||
|
font-size: 16px;
|
||||||
|
transition: transform .18s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-details[open] > summary > span:last-child {
|
||||||
|
transform: rotate(180deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-details-body {
|
||||||
|
display: grid;
|
||||||
|
gap: 16px;
|
||||||
|
padding: 2px 22px 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-technical {
|
||||||
|
display: grid;
|
||||||
|
gap: 12px;
|
||||||
|
padding-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-technical h3 {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-form > .form-actions {
|
||||||
|
padding: 16px 22px 18px;
|
||||||
|
background: #fafbfc;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 720px) {
|
||||||
|
.asset-compact-section {
|
||||||
|
padding: 17px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-section-heading {
|
||||||
|
display: grid;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-context-button {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-context-grid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-details > summary {
|
||||||
|
padding: 13px 17px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-details-body {
|
||||||
|
padding: 2px 17px 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.asset-compact-form > .form-actions {
|
||||||
|
padding: 14px 17px 17px;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,18 @@
|
|||||||
|
import './AssetEditorPage.css';
|
||||||
import { SearchableSelect } from '../components/SearchableSelect';
|
import { SearchableSelect } from '../components/SearchableSelect';
|
||||||
import { lazy, Suspense, useEffect, useMemo, useState } from 'react';
|
import { lazy, Suspense, useEffect, useMemo, useState } from 'react';
|
||||||
import type { FormEvent } from 'react';
|
import type { FormEvent, ReactNode } from 'react';
|
||||||
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
|
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
|
||||||
import { useAuth } from '../auth/AuthContext';
|
import { useAuth } from '../auth/AuthContext';
|
||||||
import { Alert, LoadingBlock, errorMessage } from '../components/Feedback';
|
import { Alert, LoadingBlock, errorMessage } from '../components/Feedback';
|
||||||
import { Icon } from '../components/Icon';
|
import { Icon } from '../components/Icon';
|
||||||
import { ASSET_OPERATIONAL_STATUSES, ASSET_STATUSES, assetOperationalStatusLabel, assetStatusClass, assetStatusLabel } from '../features/assets/assetPresentation';
|
import {
|
||||||
|
ASSET_OPERATIONAL_STATUSES,
|
||||||
|
ASSET_STATUSES,
|
||||||
|
assetOperationalStatusLabel,
|
||||||
|
assetStatusClass,
|
||||||
|
assetStatusLabel,
|
||||||
|
} from '../features/assets/assetPresentation';
|
||||||
import { AssetHistoryPanel } from '../features/assets/AssetHistoryPanel';
|
import { AssetHistoryPanel } from '../features/assets/AssetHistoryPanel';
|
||||||
import { AssetDossierPanel } from '../features/assets/AssetDossierPanel';
|
import { AssetDossierPanel } from '../features/assets/AssetDossierPanel';
|
||||||
import { AssetMediaPanel } from '../features/assets/AssetMediaPanel';
|
import { AssetMediaPanel } from '../features/assets/AssetMediaPanel';
|
||||||
@@ -15,15 +22,31 @@ import { AssetRegistryPanel } from '../features/assets/AssetRegistryPanel';
|
|||||||
import { AssetContextHistoryPanel } from '../features/assets/AssetContextHistoryPanel';
|
import { AssetContextHistoryPanel } from '../features/assets/AssetContextHistoryPanel';
|
||||||
import { AssetFindingCatalogPanel } from '../features/assets/AssetFindingCatalogPanel';
|
import { AssetFindingCatalogPanel } from '../features/assets/AssetFindingCatalogPanel';
|
||||||
import {
|
import {
|
||||||
createAsset, getAsset, getAssetLineage, listAssetParentOptions, listAssetTypes, listCompaniesForArea,
|
createAsset,
|
||||||
listOperationalAreas, updateAsset, updateAssetInformationStatus, updateAssetOperationalStatus,
|
getAsset,
|
||||||
|
getAssetLineage,
|
||||||
|
listAssetParentOptions,
|
||||||
|
listAssetTypes,
|
||||||
|
listCompaniesForArea,
|
||||||
|
listOperationalAreas,
|
||||||
|
updateAsset,
|
||||||
|
updateAssetInformationStatus,
|
||||||
|
updateAssetOperationalStatus,
|
||||||
} from '../lib/api';
|
} from '../lib/api';
|
||||||
import type {
|
import type {
|
||||||
AssetAttributeDefinition, AssetDetail, AssetInformationStatus, AssetOperationalStatus,
|
AssetAttributeDefinition,
|
||||||
AssetLineageItem, AssetListItem, AssetType, OperationalAssetSummary,
|
AssetDetail,
|
||||||
|
AssetInformationStatus,
|
||||||
|
AssetOperationalStatus,
|
||||||
|
AssetLineageItem,
|
||||||
|
AssetListItem,
|
||||||
|
AssetType,
|
||||||
|
OperationalAssetSummary,
|
||||||
} from '../lib/api';
|
} from '../lib/api';
|
||||||
|
|
||||||
const AssetGeometryEditor = lazy(() => import('../features/map/AssetGeometryEditor').then((module) => ({ default: module.AssetGeometryEditor })));
|
const AssetGeometryEditor = lazy(() =>
|
||||||
|
import('../features/map/AssetGeometryEditor').then((module) => ({ default: module.AssetGeometryEditor })),
|
||||||
|
);
|
||||||
|
|
||||||
type DetailTab = 'summary' | 'dossier' | 'findings' | 'location' | 'registry' | 'files' | 'history';
|
type DetailTab = 'summary' | 'dossier' | 'findings' | 'location' | 'registry' | 'files' | 'history';
|
||||||
|
|
||||||
@@ -35,16 +58,26 @@ function localDateTime(value: unknown): string {
|
|||||||
return local.toISOString().slice(0, 16);
|
return local.toISOString().slice(0, 16);
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeAttributeValues(definitions: AssetAttributeDefinition[], values: Record<string, unknown>): Record<string, unknown> {
|
function normalizeAttributeValues(
|
||||||
|
definitions: AssetAttributeDefinition[],
|
||||||
|
values: Record<string, unknown>,
|
||||||
|
): Record<string, unknown> {
|
||||||
const result: Record<string, unknown> = {};
|
const result: Record<string, unknown> = {};
|
||||||
definitions.filter((item) => item.isActive).forEach((definition) => {
|
definitions.filter((item) => item.isActive).forEach((definition) => {
|
||||||
const raw = values[definition.id];
|
const raw = values[definition.id];
|
||||||
if (definition.dataType === 'BOOLEAN') result[definition.id] = Boolean(raw);
|
if (definition.dataType === 'BOOLEAN') result[definition.id] = Boolean(raw);
|
||||||
else if (raw !== undefined && raw !== null && raw !== '') result[definition.id] = definition.dataType === 'NUMBER' ? Number(raw) : raw;
|
else if (raw !== undefined && raw !== null && raw !== '') {
|
||||||
|
result[definition.id] = definition.dataType === 'NUMBER' ? Number(raw) : raw;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function hasAttributeValue(definition: AssetAttributeDefinition, value: unknown): boolean {
|
||||||
|
if (definition.dataType === 'BOOLEAN') return value === true;
|
||||||
|
return value !== undefined && value !== null && String(value).trim() !== '';
|
||||||
|
}
|
||||||
|
|
||||||
export function AssetEditorPage() {
|
export function AssetEditorPage() {
|
||||||
const { id } = useParams();
|
const { id } = useParams();
|
||||||
const editing = Boolean(id);
|
const editing = Boolean(id);
|
||||||
@@ -52,7 +85,11 @@ export function AssetEditorPage() {
|
|||||||
const [searchParams] = useSearchParams();
|
const [searchParams] = useSearchParams();
|
||||||
const contextParentId = !editing ? searchParams.get('parentId') : null;
|
const contextParentId = !editing ? searchParams.get('parentId') : null;
|
||||||
const requestedTab = searchParams.get('tab') as DetailTab | null;
|
const requestedTab = searchParams.get('tab') as DetailTab | null;
|
||||||
const tab: DetailTab = requestedTab && ['summary','dossier','findings','location','registry','files','history'].includes(requestedTab) ? requestedTab : 'summary';
|
const tab: DetailTab = requestedTab
|
||||||
|
&& ['summary', 'dossier', 'findings', 'location', 'registry', 'files', 'history'].includes(requestedTab)
|
||||||
|
? requestedTab
|
||||||
|
: 'summary';
|
||||||
|
|
||||||
const { hasPermission } = useAuth();
|
const { hasPermission } = useAuth();
|
||||||
const canEdit = editing ? hasPermission('assets.update') : hasPermission('assets.create');
|
const canEdit = editing ? hasPermission('assets.update') : hasPermission('assets.create');
|
||||||
const canCreate = hasPermission('assets.create');
|
const canCreate = hasPermission('assets.create');
|
||||||
@@ -104,10 +141,14 @@ export function AssetEditorPage() {
|
|||||||
const [success, setSuccess] = useState('');
|
const [success, setSuccess] = useState('');
|
||||||
const [historyRefreshKey, setHistoryRefreshKey] = useState(0);
|
const [historyRefreshKey, setHistoryRefreshKey] = useState(0);
|
||||||
|
|
||||||
const canDirectContextEdit = !editing || Boolean(asset?.dataOrigin === 'FIELD_SURVEY' && asset.informationStatus === 'DRAFT');
|
const canDirectContextEdit = !editing
|
||||||
|
|| Boolean(asset?.dataOrigin === 'FIELD_SURVEY' && asset.informationStatus === 'DRAFT');
|
||||||
|
|
||||||
const selectedType = types.find((type) => type.id === typeId) ?? null;
|
const selectedType = types.find((type) => type.id === typeId) ?? null;
|
||||||
const definitions = useMemo(() => selectedType?.attributes.filter((item) => item.isActive) ?? [], [selectedType]);
|
const definitions = useMemo(
|
||||||
|
() => selectedType?.attributes.filter((item) => item.isActive) ?? [],
|
||||||
|
[selectedType],
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
Promise.all([
|
Promise.all([
|
||||||
@@ -119,13 +160,26 @@ export function AssetEditorPage() {
|
|||||||
setTypes(loadedTypes);
|
setTypes(loadedTypes);
|
||||||
setLineage(loadedLineage);
|
setLineage(loadedLineage);
|
||||||
if (loadedAsset) {
|
if (loadedAsset) {
|
||||||
setAsset(loadedAsset); setCode(loadedAsset.code); setName(loadedAsset.name); setCommonName(loadedAsset.commonName ?? ''); setTypeId(loadedAsset.type.id);
|
setAsset(loadedAsset);
|
||||||
setParentId(loadedAsset.parent?.id ?? ''); setOperationalAreaId(loadedAsset.operationalArea?.id ?? '');
|
setCode(loadedAsset.code);
|
||||||
setOperatorCompanyId(loadedAsset.operatorCompany?.id ?? ''); setDescription(loadedAsset.description ?? '');
|
setName(loadedAsset.name);
|
||||||
setStatus(loadedAsset.informationStatus); setOperationalStatus(loadedAsset.operationalStatus);
|
setCommonName(loadedAsset.commonName ?? '');
|
||||||
setAttributeValues(Object.fromEntries(loadedAsset.attributes.map((attribute) => [attribute.definitionId, attribute.dataType === 'DATETIME' ? localDateTime(attribute.value) : attribute.value ?? ''])));
|
setTypeId(loadedAsset.type.id);
|
||||||
|
setParentId(loadedAsset.parent?.id ?? '');
|
||||||
|
setOperationalAreaId(loadedAsset.operationalArea?.id ?? '');
|
||||||
|
setOperatorCompanyId(loadedAsset.operatorCompany?.id ?? '');
|
||||||
|
setDescription(loadedAsset.description ?? '');
|
||||||
|
setStatus(loadedAsset.informationStatus);
|
||||||
|
setOperationalStatus(loadedAsset.operationalStatus);
|
||||||
|
setAttributeValues(Object.fromEntries(
|
||||||
|
loadedAsset.attributes.map((attribute) => [
|
||||||
|
attribute.definitionId,
|
||||||
|
attribute.dataType === 'DATETIME' ? localDateTime(attribute.value) : attribute.value ?? '',
|
||||||
|
]),
|
||||||
|
));
|
||||||
} else if (!contextParentId) {
|
} else if (!contextParentId) {
|
||||||
const first = loadedTypes.find((type) => type.isActive && type.canBeRoot) ?? loadedTypes.find((type) => type.isActive);
|
const first = loadedTypes.find((type) => type.isActive && type.canBeRoot)
|
||||||
|
?? loadedTypes.find((type) => type.isActive);
|
||||||
if (first) setTypeId(first.id);
|
if (first) setTypeId(first.id);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -135,38 +189,56 @@ export function AssetEditorPage() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (editing || !contextParentId || types.length === 0) return;
|
if (editing || !contextParentId || types.length === 0) return;
|
||||||
Promise.all([getAsset(contextParentId), getAssetLineage(contextParentId)]).then(([parent, parentLineage]) => {
|
Promise.all([getAsset(contextParentId), getAssetLineage(contextParentId)])
|
||||||
setContextParent(parent);
|
.then(([parent, parentLineage]) => {
|
||||||
setLineage(parentLineage);
|
setContextParent(parent);
|
||||||
const compatible = types.find((type) => type.isActive && type.allowedParentTypes.some((allowed) => allowed.id === parent.type.id));
|
setLineage(parentLineage);
|
||||||
if (compatible) {
|
const compatible = types.find(
|
||||||
setTypeId(compatible.id); setParentId(parent.id);
|
(type) => type.isActive && type.allowedParentTypes.some((allowed) => allowed.id === parent.type.id),
|
||||||
const parentType = types.find((type) => type.id === parent.type.id);
|
);
|
||||||
if (parentType?.operationalRole === 'AREA') setOperationalAreaId(parent.id);
|
if (compatible) {
|
||||||
else if (parent.operationalArea) setOperationalAreaId(parent.operationalArea.id);
|
setTypeId(compatible.id);
|
||||||
}
|
setParentId(parent.id);
|
||||||
}).catch((requestError) => setError(errorMessage(requestError)));
|
const parentType = types.find((type) => type.id === parent.type.id);
|
||||||
|
if (parentType?.operationalRole === 'AREA') setOperationalAreaId(parent.id);
|
||||||
|
else if (parent.operationalArea) setOperationalAreaId(parent.operationalArea.id);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((requestError) => setError(errorMessage(requestError)));
|
||||||
}, [editing, contextParentId, types]);
|
}, [editing, contextParentId, types]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!typeId) { setParents([]); return; }
|
if (!typeId) {
|
||||||
const timer = window.setTimeout(() => listAssetParentOptions(typeId, id, parentSearch).then(setParents).catch((requestError) => setError(errorMessage(requestError))), 220);
|
setParents([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const timer = window.setTimeout(
|
||||||
|
() => listAssetParentOptions(typeId, id, parentSearch)
|
||||||
|
.then(setParents)
|
||||||
|
.catch((requestError) => setError(errorMessage(requestError))),
|
||||||
|
220,
|
||||||
|
);
|
||||||
return () => window.clearTimeout(timer);
|
return () => window.clearTimeout(timer);
|
||||||
}, [typeId, id, parentSearch]);
|
}, [typeId, id, parentSearch]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!canReadRelations || selectedType?.operationalRole !== 'GENERIC' || !parentId) {
|
if (!canReadRelations || selectedType?.operationalRole !== 'GENERIC' || !parentId) {
|
||||||
setOperationalAreas([]);
|
setOperationalAreas([]);
|
||||||
if (!parentId) { setOperationalAreaId(''); if (!editing) setOperatorCompanyId(''); }
|
if (!parentId) {
|
||||||
return;
|
|
||||||
}
|
|
||||||
listOperationalAreas(parentId).then((loadedAreas) => {
|
|
||||||
setOperationalAreas(loadedAreas);
|
|
||||||
if (operationalAreaId && !loadedAreas.some((area) => area.id === operationalAreaId)) {
|
|
||||||
setOperationalAreaId('');
|
setOperationalAreaId('');
|
||||||
if (!editing) setOperatorCompanyId('');
|
if (!editing) setOperatorCompanyId('');
|
||||||
}
|
}
|
||||||
}).catch((requestError) => setError(errorMessage(requestError)));
|
return;
|
||||||
|
}
|
||||||
|
listOperationalAreas(parentId)
|
||||||
|
.then((loadedAreas) => {
|
||||||
|
setOperationalAreas(loadedAreas);
|
||||||
|
if (operationalAreaId && !loadedAreas.some((area) => area.id === operationalAreaId)) {
|
||||||
|
setOperationalAreaId('');
|
||||||
|
if (!editing) setOperatorCompanyId('');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((requestError) => setError(errorMessage(requestError)));
|
||||||
}, [canReadRelations, selectedType?.operationalRole, parentId, editing]);
|
}, [canReadRelations, selectedType?.operationalRole, parentId, editing]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -174,39 +246,85 @@ export function AssetEditorPage() {
|
|||||||
setOperationalCompanies([]);
|
setOperationalCompanies([]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
listCompaniesForArea(operationalAreaId).then((loadedCompanies) => {
|
listCompaniesForArea(operationalAreaId)
|
||||||
setOperationalCompanies(loadedCompanies);
|
.then((loadedCompanies) => {
|
||||||
setOperatorCompanyId((current) => loadedCompanies.some((company) => company.id === current)
|
setOperationalCompanies(loadedCompanies);
|
||||||
? current
|
setOperatorCompanyId((current) => loadedCompanies.some((company) => company.id === current)
|
||||||
: loadedCompanies.length === 1 ? (loadedCompanies[0]?.id ?? '') : '');
|
? current
|
||||||
}).catch((requestError) => {
|
: loadedCompanies.length === 1 ? (loadedCompanies[0]?.id ?? '') : '');
|
||||||
setOperationalCompanies([]);
|
})
|
||||||
setOperatorCompanyId('');
|
.catch((requestError) => {
|
||||||
setError(errorMessage(requestError));
|
setOperationalCompanies([]);
|
||||||
});
|
setOperatorCompanyId('');
|
||||||
|
setError(errorMessage(requestError));
|
||||||
|
});
|
||||||
}, [editing, canReadRelations, operationalAreaId, selectedType?.operationalRole]);
|
}, [editing, canReadRelations, operationalAreaId, selectedType?.operationalRole]);
|
||||||
|
|
||||||
const changeType = (nextTypeId: string) => { setTypeId(nextTypeId); setParentId(''); setOperationalAreaId(''); if (!editing) setOperatorCompanyId(''); setAttributeValues({}); setParentSearch(''); };
|
const changeType = (nextTypeId: string) => {
|
||||||
const setAttribute = (definitionId: string, value: unknown) => setAttributeValues((current) => ({ ...current, [definitionId]: value }));
|
setTypeId(nextTypeId);
|
||||||
|
setParentId('');
|
||||||
|
setOperationalAreaId('');
|
||||||
|
if (!editing) setOperatorCompanyId('');
|
||||||
|
setAttributeValues({});
|
||||||
|
setParentSearch('');
|
||||||
|
};
|
||||||
|
|
||||||
|
const setAttribute = (definitionId: string, value: unknown) =>
|
||||||
|
setAttributeValues((current) => ({ ...current, [definitionId]: value }));
|
||||||
|
|
||||||
const save = async (event: FormEvent) => {
|
const save = async (event: FormEvent) => {
|
||||||
event.preventDefault(); if (!selectedType) return;
|
event.preventDefault();
|
||||||
setSaving(true); setError(''); setSuccess('');
|
if (!selectedType) return;
|
||||||
|
setSaving(true);
|
||||||
|
setError('');
|
||||||
|
setSuccess('');
|
||||||
try {
|
try {
|
||||||
const attributes = normalizeAttributeValues(definitions, attributeValues);
|
const attributes = normalizeAttributeValues(definitions, attributeValues);
|
||||||
let saved: AssetDetail;
|
let saved: AssetDetail;
|
||||||
if (editing && id) {
|
if (editing && id) {
|
||||||
if (canEdit) saved = await updateAsset(id, { typeId: canDirectContextEdit ? typeId : undefined, code, name, commonName: commonName.trim() || null, parentId: canDirectContextEdit ? parentId || null : undefined, operationalAreaId: canDirectContextEdit ? operationalAreaId || null : undefined, description: description.trim() || null, attributes });
|
if (canEdit) {
|
||||||
else if (asset) saved = asset; else return;
|
saved = await updateAsset(id, {
|
||||||
if (canChangeStatus && saved.informationStatus !== status) saved = await updateAssetInformationStatus(id, status);
|
typeId: canDirectContextEdit ? typeId : undefined,
|
||||||
if (canChangeOperationalStatus && saved.operationalStatus !== operationalStatus) saved = await updateAssetOperationalStatus(id, operationalStatus);
|
code,
|
||||||
setAsset(saved); setSuccess('Registro actualizado correctamente'); setHistoryRefreshKey((current) => current + 1);
|
name,
|
||||||
|
commonName: commonName.trim() || null,
|
||||||
|
parentId: canDirectContextEdit ? parentId || null : undefined,
|
||||||
|
operationalAreaId: canDirectContextEdit ? operationalAreaId || null : undefined,
|
||||||
|
description: description.trim() || null,
|
||||||
|
attributes,
|
||||||
|
});
|
||||||
|
} else if (asset) saved = asset;
|
||||||
|
else return;
|
||||||
|
|
||||||
|
if (canChangeStatus && saved.informationStatus !== status) {
|
||||||
|
saved = await updateAssetInformationStatus(id, status);
|
||||||
|
}
|
||||||
|
if (canChangeOperationalStatus && saved.operationalStatus !== operationalStatus) {
|
||||||
|
saved = await updateAssetOperationalStatus(id, operationalStatus);
|
||||||
|
}
|
||||||
|
setAsset(saved);
|
||||||
|
setSuccess('Registro actualizado correctamente');
|
||||||
|
setHistoryRefreshKey((current) => current + 1);
|
||||||
} else {
|
} else {
|
||||||
saved = await createAsset({ code, name, commonName: commonName.trim() || null, typeId, parentId: parentId || null, operationalAreaId: operationalAreaId || null, operatorCompanyId: operatorCompanyId || null, description: description.trim() || null, informationStatus: canChangeStatus ? status : 'DRAFT', attributes });
|
saved = await createAsset({
|
||||||
|
code,
|
||||||
|
name,
|
||||||
|
commonName: commonName.trim() || null,
|
||||||
|
typeId,
|
||||||
|
parentId: parentId || null,
|
||||||
|
operationalAreaId: operationalAreaId || null,
|
||||||
|
operatorCompanyId: operatorCompanyId || null,
|
||||||
|
description: description.trim() || null,
|
||||||
|
informationStatus: canChangeStatus ? status : 'DRAFT',
|
||||||
|
attributes,
|
||||||
|
});
|
||||||
navigate(`/inventarios/${saved.id}`, { replace: true });
|
navigate(`/inventarios/${saved.id}`, { replace: true });
|
||||||
}
|
}
|
||||||
} catch (requestError) { setError(errorMessage(requestError)); }
|
} catch (requestError) {
|
||||||
finally { setSaving(false); }
|
setError(errorMessage(requestError));
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (loading) return <LoadingBlock label="Cargando registro…" />;
|
if (loading) return <LoadingBlock label="Cargando registro…" />;
|
||||||
@@ -221,44 +339,621 @@ export function AssetEditorPage() {
|
|||||||
{ key: 'history', label: 'Historial', show: editing && canReadHistory },
|
{ key: 'history', label: 'Historial', show: editing && canReadHistory },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
const breadcrumbSection = asset?.type.code === 'empresa' || contextParent?.type.code === 'empresa' ? 'companies' : 'territory';
|
const breadcrumbSection = asset?.type.code === 'empresa' || contextParent?.type.code === 'empresa'
|
||||||
|
? 'companies'
|
||||||
|
: 'territory';
|
||||||
|
|
||||||
|
const structuralTypeCode = selectedType?.code.trim().toLowerCase() ?? '';
|
||||||
|
const compactStructuralSummary = editing
|
||||||
|
&& (structuralTypeCode === 'instalacion' || structuralTypeCode === 'subinstalacion');
|
||||||
|
|
||||||
|
const technicalFilledCount = definitions.filter(
|
||||||
|
(definition) => hasAttributeValue(definition, attributeValues[definition.id]),
|
||||||
|
).length;
|
||||||
|
const missingRequiredTechnical = definitions.some(
|
||||||
|
(definition) => definition.isRequired && !hasAttributeValue(definition, attributeValues[definition.id]),
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleContextChanged = (saved: AssetDetail) => {
|
||||||
|
setAsset(saved);
|
||||||
|
setParentId(saved.parent?.id ?? '');
|
||||||
|
setOperationalAreaId(saved.operationalArea?.id ?? '');
|
||||||
|
setOperatorCompanyId(saved.operatorCompany?.id ?? '');
|
||||||
|
setLineage([]);
|
||||||
|
getAssetLineage(saved.id).then(setLineage).catch(() => undefined);
|
||||||
|
setHistoryRefreshKey((current) => current + 1);
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderAttributes = (): ReactNode => {
|
||||||
|
if (definitions.length === 0) {
|
||||||
|
return <div className="inline-empty">Este tipo no requiere datos técnicos adicionales.</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <div className="dynamic-attributes">
|
||||||
|
{definitions.map((definition) => {
|
||||||
|
const value = attributeValues[definition.id];
|
||||||
|
const label = <span>
|
||||||
|
{definition.name}{definition.unit ? ` (${definition.unit})` : ''}
|
||||||
|
{definition.isRequired ? <em>obligatorio</em> : <em>opcional</em>}
|
||||||
|
</span>;
|
||||||
|
|
||||||
|
if (definition.dataType === 'BOOLEAN') {
|
||||||
|
return <label className="check-row attribute-check" key={definition.id}>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={Boolean(value)}
|
||||||
|
onChange={(event) => setAttribute(definition.id, event.target.checked)}
|
||||||
|
disabled={!canEdit}
|
||||||
|
/>
|
||||||
|
<span><strong>{definition.name}</strong><small>{definition.code}</small></span>
|
||||||
|
</label>;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (definition.dataType === 'SELECT') {
|
||||||
|
return <label className="field" key={definition.id}>
|
||||||
|
{label}
|
||||||
|
<SearchableSelect
|
||||||
|
value={String(value ?? '')}
|
||||||
|
onChange={(event) => setAttribute(definition.id, event.target.value)}
|
||||||
|
disabled={!canEdit}
|
||||||
|
required={definition.isRequired}
|
||||||
|
>
|
||||||
|
<option value="">Seleccionar…</option>
|
||||||
|
{definition.options?.map((option) =>
|
||||||
|
<option key={option} value={option}>{option}</option>)}
|
||||||
|
</SearchableSelect>
|
||||||
|
</label>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const inputType = definition.dataType === 'NUMBER'
|
||||||
|
? 'number'
|
||||||
|
: definition.dataType === 'DATE'
|
||||||
|
? 'date'
|
||||||
|
: definition.dataType === 'DATETIME'
|
||||||
|
? 'datetime-local'
|
||||||
|
: 'text';
|
||||||
|
|
||||||
|
return <label className="field" key={definition.id}>
|
||||||
|
{label}
|
||||||
|
<input
|
||||||
|
type={inputType}
|
||||||
|
value={String(value ?? '')}
|
||||||
|
onChange={(event) => setAttribute(definition.id, event.target.value)}
|
||||||
|
disabled={!canEdit}
|
||||||
|
required={definition.isRequired}
|
||||||
|
step={definition.dataType === 'NUMBER' ? 'any' : undefined}
|
||||||
|
maxLength={definition.dataType === 'TEXT' ? 4000 : undefined}
|
||||||
|
/>
|
||||||
|
</label>;
|
||||||
|
})}
|
||||||
|
</div>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderSaveActions = () => canSave && <div className="form-actions">
|
||||||
|
<Link className="button secondary" to="/inventarios">Cancelar</Link>
|
||||||
|
<button className="button primary" disabled={saving}>
|
||||||
|
<Icon name="check" />
|
||||||
|
{saving ? 'Guardando…' : editing && !canEdit ? 'Actualizar estado' : editing ? 'Guardar cambios' : 'Crear registro'}
|
||||||
|
</button>
|
||||||
|
</div>;
|
||||||
|
|
||||||
|
const renderCompactStructuralForm = () => <form className="panel form-panel asset-compact-form" onSubmit={save}>
|
||||||
|
<section className="asset-compact-section">
|
||||||
|
<div className="asset-compact-section-heading">
|
||||||
|
<div>
|
||||||
|
<h2>Datos principales</h2>
|
||||||
|
<p className="section-copy">Lo que se usa todos los días para reconocer este registro.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-grid asset-compact-primary-grid">
|
||||||
|
<label className="field">
|
||||||
|
<span>Nombre técnico</span>
|
||||||
|
<input
|
||||||
|
value={name}
|
||||||
|
onChange={(event) => setName(event.target.value)}
|
||||||
|
disabled={!canEdit}
|
||||||
|
required
|
||||||
|
maxLength={200}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="field">
|
||||||
|
<span>Nombre habitual / sobrenombre <em>opcional</em></span>
|
||||||
|
<input
|
||||||
|
value={commonName}
|
||||||
|
onChange={(event) => setCommonName(event.target.value)}
|
||||||
|
disabled={!canEdit}
|
||||||
|
maxLength={200}
|
||||||
|
placeholder="Ej.: planta vieja, celda principal…"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="asset-compact-meta">
|
||||||
|
<span><small>Código DH</small><strong>{code}</strong></span>
|
||||||
|
<span><small>Tipo</small><strong>{selectedType?.name ?? 'Sin tipo'}</strong></span>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="asset-compact-section">
|
||||||
|
<div className="asset-compact-section-heading">
|
||||||
|
<div>
|
||||||
|
<h2>Ubicación actual</h2>
|
||||||
|
<p className="section-copy">Dónde está contenido el elemento dentro del Inventario.</p>
|
||||||
|
</div>
|
||||||
|
{canReadHistory && id && <Link className="button secondary asset-compact-context-button" to={`/inventarios/${id}?tab=history`}>
|
||||||
|
<Icon name="edit" />Cambiar / ver historial
|
||||||
|
</Link>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="asset-compact-context-grid">
|
||||||
|
<div className="asset-compact-context-item">
|
||||||
|
<small>Registro padre</small>
|
||||||
|
<strong>{asset?.parent?.name ?? 'Sin padre'}</strong>
|
||||||
|
{asset?.parent?.code && <span>{asset.parent.code}</span>}
|
||||||
|
</div>
|
||||||
|
<div className="asset-compact-context-item">
|
||||||
|
<small>Área</small>
|
||||||
|
<strong>{asset?.operationalArea?.name ?? 'Sin área asignada'}</strong>
|
||||||
|
{asset?.operationalArea?.code && <span>{asset.operationalArea.code}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{(canChangeStatus || canChangeOperationalStatus) && <details className="asset-compact-details">
|
||||||
|
<summary>
|
||||||
|
<span><strong>Estado y opciones</strong><small>Calidad del dato y situación operativa</small></span>
|
||||||
|
<span aria-hidden="true">⌄</span>
|
||||||
|
</summary>
|
||||||
|
<div className="asset-compact-details-body">
|
||||||
|
<div className="form-grid">
|
||||||
|
{canChangeStatus && <label className="field">
|
||||||
|
<span>Estado del dato</span>
|
||||||
|
<SearchableSelect
|
||||||
|
value={status}
|
||||||
|
onChange={(event) => setStatus(event.target.value as AssetInformationStatus)}
|
||||||
|
disabled={!canEdit && !canChangeStatus}
|
||||||
|
>
|
||||||
|
{ASSET_STATUSES.map((item) =>
|
||||||
|
<option key={item.value} value={item.value}>{item.label}</option>)}
|
||||||
|
</SearchableSelect>
|
||||||
|
</label>}
|
||||||
|
{canChangeOperationalStatus && <label className="field">
|
||||||
|
<span>Estado operativo</span>
|
||||||
|
<SearchableSelect
|
||||||
|
value={operationalStatus}
|
||||||
|
onChange={(event) => setOperationalStatus(event.target.value as AssetOperationalStatus)}
|
||||||
|
>
|
||||||
|
{ASSET_OPERATIONAL_STATUSES.map((item) =>
|
||||||
|
<option key={item.value} value={item.value}>{item.label}</option>)}
|
||||||
|
</SearchableSelect>
|
||||||
|
</label>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</details>}
|
||||||
|
|
||||||
|
<details className="asset-compact-details" open={missingRequiredTechnical || canDirectContextEdit}>
|
||||||
|
<summary>
|
||||||
|
<span>
|
||||||
|
<strong>Más datos</strong>
|
||||||
|
<small>
|
||||||
|
{description.trim() ? 'Descripción cargada' : 'Sin descripción'}
|
||||||
|
{' · '}
|
||||||
|
{technicalFilledCount}/{definitions.length} datos técnicos cargados
|
||||||
|
</small>
|
||||||
|
</span>
|
||||||
|
<span aria-hidden="true">⌄</span>
|
||||||
|
</summary>
|
||||||
|
<div className="asset-compact-details-body">
|
||||||
|
<div className="form-grid">
|
||||||
|
<label className="field">
|
||||||
|
<span>Código DH</span>
|
||||||
|
<input
|
||||||
|
value={code}
|
||||||
|
onChange={(event) => setCode(event.target.value.toUpperCase())}
|
||||||
|
disabled={!canEdit}
|
||||||
|
required
|
||||||
|
maxLength={120}
|
||||||
|
pattern="[A-Z0-9][A-Z0-9._/-]*"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{canDirectContextEdit && <label className="field">
|
||||||
|
<span>Tipo de elemento</span>
|
||||||
|
<SearchableSelect
|
||||||
|
value={typeId}
|
||||||
|
onChange={(event) => changeType(event.target.value)}
|
||||||
|
disabled={!canEdit}
|
||||||
|
required
|
||||||
|
>
|
||||||
|
<option value="">Seleccionar…</option>
|
||||||
|
{types.filter((type) => type.isActive || type.id === typeId).map((type) =>
|
||||||
|
<option key={type.id} value={type.id}>{type.name}</option>)}
|
||||||
|
</SearchableSelect>
|
||||||
|
</label>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{canDirectContextEdit && <div className="form-grid">
|
||||||
|
<div className="field parent-picker">
|
||||||
|
<span>Registro padre {!selectedType?.canBeRoot && <em>obligatorio</em>}</span>
|
||||||
|
<input
|
||||||
|
className="parent-search"
|
||||||
|
value={parentSearch}
|
||||||
|
onChange={(event) => setParentSearch(event.target.value)}
|
||||||
|
disabled={!canEdit}
|
||||||
|
placeholder="Buscar planta, batería, estación…"
|
||||||
|
/>
|
||||||
|
<SearchableSelect
|
||||||
|
value={parentId}
|
||||||
|
onChange={(event) => {
|
||||||
|
setParentId(event.target.value);
|
||||||
|
setParentSearch('');
|
||||||
|
}}
|
||||||
|
disabled={!canEdit}
|
||||||
|
required={!selectedType?.canBeRoot}
|
||||||
|
>
|
||||||
|
<option value="">
|
||||||
|
{selectedType?.canBeRoot ? 'Sin padre · registro raíz' : 'Seleccionar registro padre…'}
|
||||||
|
</option>
|
||||||
|
{parents.map((parent) =>
|
||||||
|
<option key={parent.id} value={parent.id}>{parent.name} · {parent.code} ({parent.type.name})</option>)}
|
||||||
|
</SearchableSelect>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{selectedType?.operationalRole === 'GENERIC' && canReadRelations && <label className="field">
|
||||||
|
<span>Área</span>
|
||||||
|
<SearchableSelect
|
||||||
|
value={operationalAreaId}
|
||||||
|
onChange={(event) => setOperationalAreaId(event.target.value)}
|
||||||
|
disabled={!canEdit}
|
||||||
|
>
|
||||||
|
<option value="">Sin asignación operativa</option>
|
||||||
|
{operationalAreas.map((area) =>
|
||||||
|
<option key={area.id} value={area.id}>{area.name}</option>)}
|
||||||
|
</SearchableSelect>
|
||||||
|
</label>}
|
||||||
|
</div>}
|
||||||
|
|
||||||
|
<label className="field">
|
||||||
|
<span>Descripción <em>opcional</em></span>
|
||||||
|
<textarea
|
||||||
|
value={description}
|
||||||
|
onChange={(event) => setDescription(event.target.value)}
|
||||||
|
disabled={!canEdit}
|
||||||
|
maxLength={4000}
|
||||||
|
rows={2}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<div className="asset-compact-technical">
|
||||||
|
<div>
|
||||||
|
<h3>Datos técnicos</h3>
|
||||||
|
<p className="section-copy">Sólo completá lo que corresponda para este tipo.</p>
|
||||||
|
</div>
|
||||||
|
{renderAttributes()}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
{renderSaveActions()}
|
||||||
|
</form>;
|
||||||
|
|
||||||
|
const renderFullForm = () => <form className="panel form-panel" onSubmit={save}>
|
||||||
|
<div className="form-section">
|
||||||
|
<div>
|
||||||
|
<h2>Identificación</h2>
|
||||||
|
<p className="section-copy">Conservá el nombre técnico y, cuando exista, agregá el nombre habitual usado en campo.</p>
|
||||||
|
</div>
|
||||||
|
<div className="form-grid">
|
||||||
|
<label className="field">
|
||||||
|
<span>Código DH</span>
|
||||||
|
<input
|
||||||
|
value={code}
|
||||||
|
onChange={(event) => setCode(event.target.value.toUpperCase())}
|
||||||
|
disabled={!canEdit}
|
||||||
|
required
|
||||||
|
maxLength={120}
|
||||||
|
pattern="[A-Z0-9][A-Z0-9._/-]*"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="field">
|
||||||
|
<span>Nombre técnico</span>
|
||||||
|
<input value={name} onChange={(event) => setName(event.target.value)} disabled={!canEdit} required maxLength={200} />
|
||||||
|
</label>
|
||||||
|
<label className="field">
|
||||||
|
<span>Nombre habitual / sobrenombre <em>opcional</em></span>
|
||||||
|
<input
|
||||||
|
value={commonName}
|
||||||
|
onChange={(event) => setCommonName(event.target.value)}
|
||||||
|
disabled={!canEdit}
|
||||||
|
maxLength={200}
|
||||||
|
placeholder="Ej.: tanque grande, ET vieja, batería norte…"
|
||||||
|
/>
|
||||||
|
<small>También se usa en las búsquedas del Inventario.</small>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<label className="field">
|
||||||
|
<span>Descripción <em>opcional</em></span>
|
||||||
|
<textarea
|
||||||
|
value={description}
|
||||||
|
onChange={(event) => setDescription(event.target.value)}
|
||||||
|
disabled={!canEdit}
|
||||||
|
maxLength={4000}
|
||||||
|
rows={2}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-section">
|
||||||
|
<div>
|
||||||
|
<h2>Ubicación en la estructura</h2>
|
||||||
|
<p className="section-copy">
|
||||||
|
Elegí qué es y dónde está contenido. La ubicación física es independiente de la Operadora del Área.
|
||||||
|
Los registros ya consolidados cambian de ubicación desde el bloque histórico inferior.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="form-grid">
|
||||||
|
<label className="field">
|
||||||
|
<span>Tipo de elemento</span>
|
||||||
|
<SearchableSelect
|
||||||
|
value={typeId}
|
||||||
|
onChange={(event) => changeType(event.target.value)}
|
||||||
|
disabled={(editing && !(asset?.dataOrigin === 'FIELD_SURVEY' && asset.informationStatus === 'DRAFT')) || !canEdit}
|
||||||
|
required
|
||||||
|
>
|
||||||
|
<option value="">Seleccionar…</option>
|
||||||
|
{types.filter((type) => type.isActive || type.id === typeId).map((type) =>
|
||||||
|
<option key={type.id} value={type.id}>{type.name}</option>)}
|
||||||
|
</SearchableSelect>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<div className="field parent-picker">
|
||||||
|
<span>Registro padre {!selectedType?.canBeRoot && <em>obligatorio</em>}</span>
|
||||||
|
<input
|
||||||
|
className="parent-search"
|
||||||
|
value={parentSearch}
|
||||||
|
onChange={(event) => setParentSearch(event.target.value)}
|
||||||
|
disabled={!canEdit || !canDirectContextEdit}
|
||||||
|
placeholder="Buscar planta, batería, estación…"
|
||||||
|
/>
|
||||||
|
<SearchableSelect
|
||||||
|
value={parentId}
|
||||||
|
onChange={(event) => {
|
||||||
|
setParentId(event.target.value);
|
||||||
|
setParentSearch('');
|
||||||
|
}}
|
||||||
|
disabled={!canEdit || !canDirectContextEdit}
|
||||||
|
required={!selectedType?.canBeRoot}
|
||||||
|
>
|
||||||
|
<option value="">
|
||||||
|
{selectedType?.canBeRoot ? 'Sin padre · registro raíz' : 'Seleccionar registro padre…'}
|
||||||
|
</option>
|
||||||
|
{parents.map((parent) =>
|
||||||
|
<option key={parent.id} value={parent.id}>{parent.name} · {parent.code} ({parent.type.name})</option>)}
|
||||||
|
</SearchableSelect>
|
||||||
|
<small>Escribí para buscar entre los registros compatibles.</small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-grid">
|
||||||
|
{canChangeStatus && <label className="field">
|
||||||
|
<span>Estado del dato</span>
|
||||||
|
<SearchableSelect
|
||||||
|
value={status}
|
||||||
|
onChange={(event) => setStatus(event.target.value as AssetInformationStatus)}
|
||||||
|
disabled={!canEdit && !canChangeStatus}
|
||||||
|
>
|
||||||
|
{ASSET_STATUSES.map((item) =>
|
||||||
|
<option key={item.value} value={item.value}>{item.label}</option>)}
|
||||||
|
</SearchableSelect>
|
||||||
|
<small>Calidad y validación del registro.</small>
|
||||||
|
</label>}
|
||||||
|
|
||||||
|
{editing && canChangeOperationalStatus && <label className="field">
|
||||||
|
<span>Estado operativo</span>
|
||||||
|
<SearchableSelect
|
||||||
|
value={operationalStatus}
|
||||||
|
onChange={(event) => setOperationalStatus(event.target.value as AssetOperationalStatus)}
|
||||||
|
>
|
||||||
|
{ASSET_OPERATIONAL_STATUSES.map((item) =>
|
||||||
|
<option key={item.value} value={item.value}>{item.label}</option>)}
|
||||||
|
</SearchableSelect>
|
||||||
|
<small>Situación física u operativa del elemento.</small>
|
||||||
|
</label>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{selectedType?.operationalRole === 'GENERIC' && canReadRelations && <div className="form-section">
|
||||||
|
<div>
|
||||||
|
<h2>{editing ? 'Área física' : 'Área y operadora al alta'}</h2>
|
||||||
|
<p className="section-copy">
|
||||||
|
{editing
|
||||||
|
? 'El Inventario pertenece físicamente al Área. La Operadora vigente se administra en las relaciones temporales del Área y no se reescribe dentro del Inventario.'
|
||||||
|
: 'Al crear el registro, la Operadora activa del Área queda guardada únicamente como snapshot histórico de alta.'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="form-grid">
|
||||||
|
<label className="field">
|
||||||
|
<span>Área</span>
|
||||||
|
<SearchableSelect
|
||||||
|
value={operationalAreaId}
|
||||||
|
onChange={(event) => {
|
||||||
|
setOperationalAreaId(event.target.value);
|
||||||
|
if (!editing) setOperatorCompanyId('');
|
||||||
|
}}
|
||||||
|
disabled={!canEdit || !canDirectContextEdit}
|
||||||
|
>
|
||||||
|
<option value="">Sin asignación operativa</option>
|
||||||
|
{operationalAreas.map((area) =>
|
||||||
|
<option key={area.id} value={area.id}>{area.name}</option>)}
|
||||||
|
</SearchableSelect>
|
||||||
|
{editing && <small>La Operadora se resuelve por la relación Área↔Empresa vigente.</small>}
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{!editing && <label className="field">
|
||||||
|
<span>Operadora {operationalAreaId && <em>obligatoria</em>}</span>
|
||||||
|
<SearchableSelect
|
||||||
|
value={operatorCompanyId}
|
||||||
|
onChange={(event) => setOperatorCompanyId(event.target.value)}
|
||||||
|
disabled={!canEdit || !operationalAreaId}
|
||||||
|
required={Boolean(operationalAreaId)}
|
||||||
|
>
|
||||||
|
<option value="">{operationalAreaId ? 'Seleccionar operadora…' : 'Primero seleccioná un área'}</option>
|
||||||
|
{operationalCompanies.map((company) =>
|
||||||
|
<option key={company.id} value={company.id}>{company.name}</option>)}
|
||||||
|
</SearchableSelect>
|
||||||
|
</label>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!editing && operationalAreaId && operatorCompanyId && <div className="temporal-notice">
|
||||||
|
<Icon name="check" />
|
||||||
|
<p><strong>Contexto de alta confirmado.</strong> La Operadora seleccionada se conservará como referencia histórica; futuros cambios se harán en la relación temporal del Área.</p>
|
||||||
|
</div>}
|
||||||
|
|
||||||
|
{editing && asset?.operatorCompany && <div className="temporal-notice">
|
||||||
|
<Icon name="layers" />
|
||||||
|
<p><strong>Snapshot histórico de alta:</strong> {asset.operatorCompany.name}. No se modifica desde este registro.</p>
|
||||||
|
</div>}
|
||||||
|
</div>}
|
||||||
|
|
||||||
|
<div className="form-section">
|
||||||
|
<div>
|
||||||
|
<h2>Datos técnicos</h2>
|
||||||
|
<p className="section-copy">Campos definidos para el tipo seleccionado.</p>
|
||||||
|
</div>
|
||||||
|
{renderAttributes()}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{renderSaveActions()}
|
||||||
|
</form>;
|
||||||
|
|
||||||
return <section className="narrow-section asset-detail-page">
|
return <section className="narrow-section asset-detail-page">
|
||||||
<nav className="breadcrumb asset-detail-breadcrumb" aria-label="Ruta del inventario">
|
<nav className="breadcrumb asset-detail-breadcrumb" aria-label="Ruta del inventario">
|
||||||
<Link to="/inventarios">Inventarios</Link><span>›</span>
|
<Link to="/inventarios">Inventarios</Link><span>›</span>
|
||||||
<Link to={breadcrumbSection === 'companies' ? '/inventarios?section=companies' : '/inventarios?section=territory'}>{breadcrumbSection === 'companies' ? 'Empresas' : 'Áreas y yacimientos'}</Link>
|
<Link to={breadcrumbSection === 'companies' ? '/inventarios?section=companies' : '/inventarios?section=territory'}>
|
||||||
|
{breadcrumbSection === 'companies' ? 'Empresas' : 'Áreas y yacimientos'}
|
||||||
|
</Link>
|
||||||
{lineage.map((item, index) => {
|
{lineage.map((item, index) => {
|
||||||
const isLast = index === lineage.length - 1;
|
const isLast = index === lineage.length - 1;
|
||||||
const showAsCurrent = editing ? isLast : false;
|
const showAsCurrent = editing ? isLast : false;
|
||||||
return <span className="asset-detail-crumb-part" key={item.id}><span>›</span>{showAsCurrent ? <strong>{item.name}</strong> : <Link to={`/inventarios?section=${breadcrumbSection}&parentId=${item.id}`}>{item.name}</Link>}</span>;
|
return <span className="asset-detail-crumb-part" key={item.id}>
|
||||||
|
<span>›</span>
|
||||||
|
{showAsCurrent
|
||||||
|
? <strong>{item.name}</strong>
|
||||||
|
: <Link to={`/inventarios?section=${breadcrumbSection}&parentId=${item.id}`}>{item.name}</Link>}
|
||||||
|
</span>;
|
||||||
})}
|
})}
|
||||||
{!editing && <><span>›</span><strong>Nuevo registro</strong></>}
|
{!editing && <><span>›</span><strong>Nuevo registro</strong></>}
|
||||||
</nav>
|
</nav>
|
||||||
<div className="page-heading asset-editor-heading"><div><span className="eyebrow">INVENTARIO</span><h1>{editing ? asset?.name ?? 'Registro' : contextParent ? `Agregar en ${contextParent.name}` : 'Nuevo registro'}</h1><p>{editing ? `${asset?.type.name} · ${asset?.code}` : contextParent ? `El sistema heredará el contexto disponible de ${contextParent.code}.` : 'Creá una entidad con identidad, jerarquía y atributos propios.'}</p></div><div className="asset-heading-actions">{editing && asset && <div className="heading-statuses"><span className={`status-badge ${assetStatusClass(asset.informationStatus)}`}>{assetStatusLabel(asset.informationStatus)}</span><small>{assetOperationalStatusLabel(asset.operationalStatus)}</small></div>}{editing && id && canCreate && <Link className="button primary" to={`/inventarios/nuevo?parentId=${id}`}><Icon name="plus" />Agregar registro aquí</Link>}</div></div>
|
|
||||||
{error && <Alert>{error}</Alert>}{success && <Alert type="success">{success}</Alert>}
|
|
||||||
|
|
||||||
{editing && <nav className="asset-detail-tabs">{detailTabs.filter((item) => item.show).map((item) => <Link key={item.key} className={tab === item.key ? 'active' : ''} to={`/inventarios/${id}${item.key === 'summary' ? '' : `?tab=${item.key}`}`}>{item.label}</Link>)}</nav>}
|
<div className="page-heading asset-editor-heading">
|
||||||
|
<div>
|
||||||
|
<span className="eyebrow">INVENTARIO</span>
|
||||||
|
<h1>{editing ? asset?.name ?? 'Registro' : contextParent ? `Agregar en ${contextParent.name}` : 'Nuevo registro'}</h1>
|
||||||
|
<p>
|
||||||
|
{editing
|
||||||
|
? `${asset?.type.name} · ${asset?.code}`
|
||||||
|
: contextParent
|
||||||
|
? `El sistema heredará el contexto disponible de ${contextParent.code}.`
|
||||||
|
: 'Creá una entidad con identidad, jerarquía y atributos propios.'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="asset-heading-actions">
|
||||||
|
{editing && asset && <div className="heading-statuses">
|
||||||
|
<span className={`status-badge ${assetStatusClass(asset.informationStatus)}`}>
|
||||||
|
{assetStatusLabel(asset.informationStatus)}
|
||||||
|
</span>
|
||||||
|
<small>{assetOperationalStatusLabel(asset.operationalStatus)}</small>
|
||||||
|
</div>}
|
||||||
|
{editing && id && canCreate && <Link className="button primary" to={`/inventarios/nuevo?parentId=${id}`}>
|
||||||
|
<Icon name="plus" />Agregar registro aquí
|
||||||
|
</Link>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && <Alert>{error}</Alert>}
|
||||||
|
{success && <Alert type="success">{success}</Alert>}
|
||||||
|
|
||||||
|
{editing && <nav className="asset-detail-tabs">
|
||||||
|
{detailTabs.filter((item) => item.show).map((item) =>
|
||||||
|
<Link
|
||||||
|
key={item.key}
|
||||||
|
className={tab === item.key ? 'active' : ''}
|
||||||
|
to={`/inventarios/${id}${item.key === 'summary' ? '' : `?tab=${item.key}`}`}
|
||||||
|
>
|
||||||
|
{item.label}
|
||||||
|
</Link>)}
|
||||||
|
</nav>}
|
||||||
|
|
||||||
{(!editing || tab === 'summary') && <>
|
{(!editing || tab === 'summary') && <>
|
||||||
{contextParent && !editing && <div className="context-create-banner"><Icon name="layers" /><div><strong>Alta contextual</strong><span>{contextParent.name} · {contextParent.code}</span></div><Link to={`/inventarios/${contextParent.id}`}>Ver padre</Link></div>}
|
{contextParent && !editing && <div className="context-create-banner">
|
||||||
<form className="panel form-panel" onSubmit={save}>
|
<Icon name="layers" />
|
||||||
<div className="form-section"><div><h2>Identificación</h2><p className="section-copy">Conservá el nombre técnico y, cuando exista, agregá el nombre habitual usado en campo.</p></div><div className="form-grid"><label className="field"><span>Código DH</span><input value={code} onChange={(event) => setCode(event.target.value.toUpperCase())} disabled={!canEdit} required maxLength={120} pattern="[A-Z0-9][A-Z0-9._/-]*" /></label><label className="field"><span>Nombre técnico</span><input value={name} onChange={(event) => setName(event.target.value)} disabled={!canEdit} required maxLength={200} /></label><label className="field"><span>Nombre habitual / sobrenombre <em>opcional</em></span><input value={commonName} onChange={(event) => setCommonName(event.target.value)} disabled={!canEdit} maxLength={200} placeholder="Ej.: tanque grande, ET vieja, batería norte…" /><small>También se usa en las búsquedas del Inventario.</small></label></div><label className="field"><span>Descripción <em>opcional</em></span><textarea value={description} onChange={(event) => setDescription(event.target.value)} disabled={!canEdit} maxLength={4000} rows={2} /></label></div>
|
<div><strong>Alta contextual</strong><span>{contextParent.name} · {contextParent.code}</span></div>
|
||||||
|
<Link to={`/inventarios/${contextParent.id}`}>Ver padre</Link>
|
||||||
|
</div>}
|
||||||
|
|
||||||
<div className="form-section"><div><h2>Ubicación en la estructura</h2><p className="section-copy">Elegí qué es y dónde está contenido. La ubicación física es independiente de la Operadora del Área. Los registros ya consolidados cambian de ubicación desde el bloque histórico inferior.</p></div><div className="form-grid"><label className="field"><span>Tipo de elemento</span><SearchableSelect value={typeId} onChange={(event) => changeType(event.target.value)} disabled={(editing && !(asset?.dataOrigin === 'FIELD_SURVEY' && asset.informationStatus === 'DRAFT')) || !canEdit} required><option value="">Seleccionar…</option>{types.filter((type) => type.isActive || type.id === typeId).map((type) => <option key={type.id} value={type.id}>{type.name}</option>)}</SearchableSelect></label><div className="field parent-picker"><span>Registro padre {!selectedType?.canBeRoot && <em>obligatorio</em>}</span><input className="parent-search" value={parentSearch} onChange={(event) => setParentSearch(event.target.value)} disabled={!canEdit || !canDirectContextEdit} placeholder="Buscar planta, batería, estación…" /><SearchableSelect value={parentId} onChange={(event) => { setParentId(event.target.value); setParentSearch(''); }} disabled={!canEdit || !canDirectContextEdit} required={!selectedType?.canBeRoot}><option value="">{selectedType?.canBeRoot ? 'Sin padre · registro raíz' : 'Seleccionar registro padre…'}</option>{parents.map((parent) => <option key={parent.id} value={parent.id}>{parent.name} · {parent.code} ({parent.type.name})</option>)}</SearchableSelect><small>Escribí para buscar entre los registros compatibles.</small></div></div><div className="form-grid">{canChangeStatus && <label className="field"><span>Estado del dato</span><SearchableSelect value={status} onChange={(event) => setStatus(event.target.value as AssetInformationStatus)} disabled={!canEdit && !canChangeStatus}>{ASSET_STATUSES.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}</SearchableSelect><small>Calidad y validación del registro.</small></label>}{editing && canChangeOperationalStatus && <label className="field"><span>Estado operativo</span><SearchableSelect value={operationalStatus} onChange={(event) => setOperationalStatus(event.target.value as AssetOperationalStatus)}>{ASSET_OPERATIONAL_STATUSES.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}</SearchableSelect><small>Situación física u operativa del elemento.</small></label>}</div></div>
|
{compactStructuralSummary ? renderCompactStructuralForm() : renderFullForm()}
|
||||||
|
|
||||||
{selectedType?.operationalRole === 'GENERIC' && canReadRelations && <div className="form-section"><div><h2>{editing ? 'Área física' : 'Área y operadora al alta'}</h2><p className="section-copy">{editing ? 'El Inventario pertenece físicamente al Área. La Operadora vigente se administra en las relaciones temporales del Área y no se reescribe dentro del Inventario.' : 'Al crear el registro, la Operadora activa del Área queda guardada únicamente como snapshot histórico de alta.'}</p></div><div className="form-grid"><label className="field"><span>Área</span><SearchableSelect value={operationalAreaId} onChange={(event) => { setOperationalAreaId(event.target.value); if (!editing) setOperatorCompanyId(''); }} disabled={!canEdit || !canDirectContextEdit}><option value="">Sin asignación operativa</option>{operationalAreas.map((area) => <option key={area.id} value={area.id}>{area.name}</option>)}</SearchableSelect>{editing && <small>La Operadora se resuelve por la relación Área↔Empresa vigente.</small>}</label>{!editing && <label className="field"><span>Operadora {operationalAreaId && <em>obligatoria</em>}</span><SearchableSelect value={operatorCompanyId} onChange={(event) => setOperatorCompanyId(event.target.value)} disabled={!canEdit || !operationalAreaId} required={Boolean(operationalAreaId)}><option value="">{operationalAreaId ? 'Seleccionar operadora…' : 'Primero seleccioná un área'}</option>{operationalCompanies.map((company) => <option key={company.id} value={company.id}>{company.name}</option>)}</SearchableSelect></label>}</div>{!editing && operationalAreaId && operatorCompanyId && <div className="temporal-notice"><Icon name="check" /><p><strong>Contexto de alta confirmado.</strong> La Operadora seleccionada se conservará como referencia histórica; futuros cambios se harán en la relación temporal del Área.</p></div>}{editing && asset?.operatorCompany && <div className="temporal-notice"><Icon name="layers" /><p><strong>Snapshot histórico de alta:</strong> {asset.operatorCompany.name}. No se modifica desde este registro.</p></div>}</div>}
|
{!compactStructuralSummary && editing && id && asset && selectedType && canReadHistory
|
||||||
|
&& <AssetContextHistoryPanel
|
||||||
|
asset={asset}
|
||||||
|
type={selectedType}
|
||||||
|
canManage={canManageContext}
|
||||||
|
onChanged={handleContextChanged}
|
||||||
|
/>}
|
||||||
|
|
||||||
<div className="form-section"><div><h2>Datos técnicos</h2><p className="section-copy">Campos definidos para el tipo seleccionado.</p></div>{definitions.length === 0 ? <div className="inline-empty">Este tipo no requiere datos técnicos adicionales.</div> : <div className="dynamic-attributes">{definitions.map((definition) => { const value = attributeValues[definition.id]; const label = <span>{definition.name}{definition.unit ? ` (${definition.unit})` : ''}{definition.isRequired ? <em>obligatorio</em> : <em>opcional</em>}</span>; if (definition.dataType === 'BOOLEAN') return <label className="check-row attribute-check" key={definition.id}><input type="checkbox" checked={Boolean(value)} onChange={(event) => setAttribute(definition.id, event.target.checked)} disabled={!canEdit} /><span><strong>{definition.name}</strong><small>{definition.code}</small></span></label>; if (definition.dataType === 'SELECT') return <label className="field" key={definition.id}>{label}<SearchableSelect value={String(value ?? '')} onChange={(event) => setAttribute(definition.id, event.target.value)} disabled={!canEdit} required={definition.isRequired}><option value="">Seleccionar…</option>{definition.options?.map((option) => <option key={option} value={option}>{option}</option>)}</SearchableSelect></label>; const inputType = definition.dataType === 'NUMBER' ? 'number' : definition.dataType === 'DATE' ? 'date' : definition.dataType === 'DATETIME' ? 'datetime-local' : 'text'; return <label className="field" key={definition.id}>{label}<input type={inputType} value={String(value ?? '')} onChange={(event) => setAttribute(definition.id, event.target.value)} disabled={!canEdit} required={definition.isRequired} step={definition.dataType === 'NUMBER' ? 'any' : undefined} maxLength={definition.dataType === 'TEXT' ? 4000 : undefined} /></label>; })}</div>}</div>
|
{editing && id && asset && canReadRelations && selectedType && selectedType.operationalRole !== 'GENERIC'
|
||||||
{canSave && <div className="form-actions"><Link className="button secondary" to="/inventarios">Cancelar</Link><button className="button primary" disabled={saving}><Icon name="check" />{saving ? 'Guardando…' : editing && !canEdit ? 'Actualizar estado' : editing ? 'Guardar cambios' : 'Crear registro'}</button></div>}
|
&& <AssetOperationalRelationsPanel assetId={id} role={selectedType.operationalRole} canManage={canManageRelations} />}
|
||||||
</form>
|
|
||||||
{editing && id && asset && selectedType && canReadHistory && <AssetContextHistoryPanel asset={asset} type={selectedType} canManage={canManageContext} onChanged={(saved) => { setAsset(saved); setParentId(saved.parent?.id ?? ''); setOperationalAreaId(saved.operationalArea?.id ?? ''); setOperatorCompanyId(saved.operatorCompany?.id ?? ''); setLineage([]); getAssetLineage(saved.id).then(setLineage).catch(() => undefined); setHistoryRefreshKey((current) => current + 1); }} />}
|
|
||||||
{editing && id && asset && canReadRelations && selectedType && selectedType.operationalRole !== 'GENERIC' && <AssetOperationalRelationsPanel assetId={id} role={selectedType.operationalRole} canManage={canManageRelations} />}
|
|
||||||
</>}
|
</>}
|
||||||
|
|
||||||
{editing && id && asset && tab === 'findings' && canReadFindingCatalog && <AssetFindingCatalogPanel assetId={id} canManage={canManageFindingCatalog} />}
|
{editing && id && asset && tab === 'findings' && canReadFindingCatalog
|
||||||
{editing && id && asset && tab === 'dossier' && canReadDossier && <AssetDossierPanel assetId={id} />}
|
&& <AssetFindingCatalogPanel assetId={id} canManage={canManageFindingCatalog} />}
|
||||||
{editing && id && asset && tab === 'location' && <Suspense fallback={<div className="panel"><LoadingBlock label="Cargando ubicación…" /></div>}><AssetGeometryEditor assetId={id} assetName={asset.name} canEdit={canEditGeometry} onChanged={() => setHistoryRefreshKey((current) => current + 1)} /></Suspense>}
|
|
||||||
{editing && id && asset && tab === 'registry' && <div className="asset-tab-stack">{canReadRegistry && selectedType && <AssetRegistryPanel assetId={id} assetName={asset.name} role={selectedType.operationalRole} canManage={canManageRegistry} onChanged={() => setHistoryRefreshKey((current) => current + 1)} />}{canReadProvenance && <AssetProvenancePanel assetId={id} canManage={canManageProvenance} canVerify={canVerifyProvenance} onChanged={() => setHistoryRefreshKey((current) => current + 1)} />}</div>}
|
{editing && id && asset && tab === 'dossier' && canReadDossier
|
||||||
{editing && id && asset && tab === 'files' && canReadMedia && <AssetMediaPanel assetId={id} assetName={asset.name} canManage={canManageMedia} onChanged={() => setHistoryRefreshKey((current) => current + 1)} />}
|
&& <AssetDossierPanel assetId={id} />}
|
||||||
{editing && id && tab === 'history' && canReadHistory && <AssetHistoryPanel assetId={id} refreshKey={historyRefreshKey} />}
|
|
||||||
|
{editing && id && asset && tab === 'location'
|
||||||
|
&& <Suspense fallback={<div className="panel"><LoadingBlock label="Cargando ubicación…" /></div>}>
|
||||||
|
<AssetGeometryEditor
|
||||||
|
assetId={id}
|
||||||
|
assetName={asset.name}
|
||||||
|
canEdit={canEditGeometry}
|
||||||
|
onChanged={() => setHistoryRefreshKey((current) => current + 1)}
|
||||||
|
/>
|
||||||
|
</Suspense>}
|
||||||
|
|
||||||
|
{editing && id && asset && tab === 'registry' && <div className="asset-tab-stack">
|
||||||
|
{canReadRegistry && selectedType && <AssetRegistryPanel
|
||||||
|
assetId={id}
|
||||||
|
assetName={asset.name}
|
||||||
|
role={selectedType.operationalRole}
|
||||||
|
canManage={canManageRegistry}
|
||||||
|
onChanged={() => setHistoryRefreshKey((current) => current + 1)}
|
||||||
|
/>}
|
||||||
|
{canReadProvenance && <AssetProvenancePanel
|
||||||
|
assetId={id}
|
||||||
|
canManage={canManageProvenance}
|
||||||
|
canVerify={canVerifyProvenance}
|
||||||
|
onChanged={() => setHistoryRefreshKey((current) => current + 1)}
|
||||||
|
/>}
|
||||||
|
</div>}
|
||||||
|
|
||||||
|
{editing && id && asset && tab === 'files' && canReadMedia
|
||||||
|
&& <AssetMediaPanel
|
||||||
|
assetId={id}
|
||||||
|
assetName={asset.name}
|
||||||
|
canManage={canManageMedia}
|
||||||
|
onChanged={() => setHistoryRefreshKey((current) => current + 1)}
|
||||||
|
/>}
|
||||||
|
|
||||||
|
{editing && id && tab === 'history' && canReadHistory && <div className="asset-tab-stack">
|
||||||
|
{compactStructuralSummary && asset && selectedType && <AssetContextHistoryPanel
|
||||||
|
asset={asset}
|
||||||
|
type={selectedType}
|
||||||
|
canManage={canManageContext}
|
||||||
|
onChanged={handleContextChanged}
|
||||||
|
/>}
|
||||||
|
<AssetHistoryPanel assetId={id} refreshKey={historyRefreshKey} />
|
||||||
|
</div>}
|
||||||
</section>;
|
</section>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,437 @@
|
|||||||
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
|
import type { FormEvent } from 'react';
|
||||||
|
import { Link, useSearchParams } from 'react-router';
|
||||||
|
import { useAuth } from '../auth/AuthContext';
|
||||||
|
import { Alert, EmptyState, LoadingBlock, errorMessage } from '../components/Feedback';
|
||||||
|
import { Icon } from '../components/Icon';
|
||||||
|
import { SearchableSelect } from '../components/SearchableSelect';
|
||||||
|
import { AssetHistoryPanel } from '../features/assets/AssetHistoryPanel';
|
||||||
|
import { AssetMediaPanel } from '../features/assets/AssetMediaPanel';
|
||||||
|
import { assetStatusClass, assetStatusLabel } from '../features/assets/assetPresentation';
|
||||||
|
import {
|
||||||
|
createAreaCompanyRelation,
|
||||||
|
endAreaCompanyRelation,
|
||||||
|
getAssetRegistry,
|
||||||
|
listAreaCompanyRelations,
|
||||||
|
listInspectionVisits,
|
||||||
|
listOperationalAreas,
|
||||||
|
updateAsset,
|
||||||
|
upsertOrganizationProfile,
|
||||||
|
} from '../lib/api';
|
||||||
|
import type {
|
||||||
|
AreaCompanyRelation,
|
||||||
|
AssetDetail,
|
||||||
|
AssetRegistry,
|
||||||
|
OperationalAssetSummary,
|
||||||
|
OrganizationKind,
|
||||||
|
} from '../lib/api';
|
||||||
|
import {
|
||||||
|
listInspectionActsGlobalF4,
|
||||||
|
type InspectionActListItemF4,
|
||||||
|
type InspectionActStatusF4,
|
||||||
|
} from '../lib/inspectionActF4Api';
|
||||||
|
import {
|
||||||
|
listInspectionReportsF4,
|
||||||
|
type InspectionReportDetailF4,
|
||||||
|
} from '../lib/reportWorkflowApi';
|
||||||
|
import { formatDate } from '../lib/format';
|
||||||
|
import './companyInventory.css';
|
||||||
|
|
||||||
|
type CompanyTab = 'summary' | 'issued' | 'documents' | 'history';
|
||||||
|
|
||||||
|
const organizationLabels: Record<OrganizationKind, string> = {
|
||||||
|
COMPANY: 'Empresa',
|
||||||
|
UTE: 'UTE',
|
||||||
|
PUBLIC_ENTITY: 'Entidad pública',
|
||||||
|
OTHER: 'Otra organización',
|
||||||
|
};
|
||||||
|
|
||||||
|
function relationRoleLabel(role: AreaCompanyRelation['relationRole']) {
|
||||||
|
if (role === 'OPERATOR') return 'Operadora';
|
||||||
|
if (role === 'TECHNICAL_OPERATOR') return 'Operadora técnica';
|
||||||
|
if (role === 'CONCESSIONAIRE') return 'Concesionaria / titular';
|
||||||
|
if (role === 'PERMIT_HOLDER') return 'Permisionaria';
|
||||||
|
if (role === 'PARTICIPANT') return 'Participante';
|
||||||
|
return 'Otro vínculo';
|
||||||
|
}
|
||||||
|
|
||||||
|
function reportStatusLabel(report: InspectionReportDetailF4) {
|
||||||
|
if (report.status === 'OFFICIALIZED') return report.gedoIfIdentifier ? `GEDO · ${report.gedoIfIdentifier}` : 'Oficializado en GEDO';
|
||||||
|
if (report.status === 'WORKING') return 'INF en preparación';
|
||||||
|
if (report.status === 'CANCELLED') return 'Cancelado';
|
||||||
|
return 'Informe histórico';
|
||||||
|
}
|
||||||
|
|
||||||
|
function reportStatusClass(report: InspectionReportDetailF4) {
|
||||||
|
if (report.status === 'OFFICIALIZED') return 'active';
|
||||||
|
if (report.status === 'CANCELLED') return 'danger';
|
||||||
|
return 'pending';
|
||||||
|
}
|
||||||
|
|
||||||
|
function areaLabel(items: Array<{ name: string }>) {
|
||||||
|
if (!items.length) return 'Área sin informar';
|
||||||
|
const first = items[0];
|
||||||
|
if (!first) return 'Área sin informar';
|
||||||
|
return items.length === 1 ? first.name : `${first.name} +${items.length - 1}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAllActs(companyId: string): Promise<InspectionActListItemF4[]> {
|
||||||
|
const statuses: InspectionActStatusF4[] = ['SEALED', 'CLOSED', 'RECTIFIED'];
|
||||||
|
const groups = await Promise.all(statuses.map(async (status) => {
|
||||||
|
const collected: InspectionActListItemF4[] = [];
|
||||||
|
let page = 1;
|
||||||
|
let totalPages = 1;
|
||||||
|
do {
|
||||||
|
const response = await listInspectionActsGlobalF4({ companyId, status, page, pageSize: 100 });
|
||||||
|
collected.push(...response.data);
|
||||||
|
totalPages = response.meta.totalPages;
|
||||||
|
page += 1;
|
||||||
|
} while (page <= totalPages);
|
||||||
|
return collected;
|
||||||
|
}));
|
||||||
|
return groups.flat().sort((a, b) => new Date(b.occurredAt).getTime() - new Date(a.occurredAt).getTime());
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAllReports(companyId: string): Promise<InspectionReportDetailF4[]> {
|
||||||
|
const collected: InspectionReportDetailF4[] = [];
|
||||||
|
let page = 1;
|
||||||
|
let totalPages = 1;
|
||||||
|
do {
|
||||||
|
const response = await listInspectionReportsF4({ companyId, page, pageSize: 100 });
|
||||||
|
collected.push(...response.data);
|
||||||
|
totalPages = response.meta.totalPages;
|
||||||
|
page += 1;
|
||||||
|
} while (page <= totalPages);
|
||||||
|
return collected
|
||||||
|
.filter((item) => item.status !== 'CANCELLED')
|
||||||
|
.sort((a, b) => new Date(b.generatedAt).getTime() - new Date(a.generatedAt).getTime());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CompanyInventoryPage({ initialAsset }: { initialAsset: AssetDetail }) {
|
||||||
|
const [params, setParams] = useSearchParams();
|
||||||
|
const requestedTab = params.get('tab') as CompanyTab | null;
|
||||||
|
const tab: CompanyTab = requestedTab && ['summary', 'issued', 'documents', 'history'].includes(requestedTab)
|
||||||
|
? requestedTab
|
||||||
|
: 'summary';
|
||||||
|
const { hasPermission } = useAuth();
|
||||||
|
const canEditAsset = hasPermission('assets.update');
|
||||||
|
const canReadRegistry = hasPermission('asset_registry.read');
|
||||||
|
const canManageRegistry = hasPermission('asset_registry.manage');
|
||||||
|
const canReadRelations = hasPermission('asset_relations.read');
|
||||||
|
const canManageRelations = hasPermission('asset_relations.manage');
|
||||||
|
const canReadActs = hasPermission('inspection_acts.read');
|
||||||
|
const canReadReports = hasPermission('inspection_reports.read');
|
||||||
|
const canReadInspections = hasPermission('inspections.read');
|
||||||
|
const canReadMedia = hasPermission('assets.read_media');
|
||||||
|
const canManageMedia = hasPermission('assets.manage_media');
|
||||||
|
const canReadHistory = hasPermission('assets.read_history');
|
||||||
|
|
||||||
|
const [asset, setAsset] = useState(initialAsset);
|
||||||
|
const [registry, setRegistry] = useState<AssetRegistry | null>(null);
|
||||||
|
const [relations, setRelations] = useState<AreaCompanyRelation[]>([]);
|
||||||
|
const [areas, setAreas] = useState<OperationalAssetSummary[]>([]);
|
||||||
|
const [loadingContext, setLoadingContext] = useState(true);
|
||||||
|
const [contextError, setContextError] = useState('');
|
||||||
|
const [success, setSuccess] = useState('');
|
||||||
|
const [editing, setEditing] = useState(false);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [companyForm, setCompanyForm] = useState({
|
||||||
|
name: initialAsset.name,
|
||||||
|
commonName: initialAsset.commonName ?? '',
|
||||||
|
organizationKind: 'COMPANY' as OrganizationKind,
|
||||||
|
legalName: initialAsset.name,
|
||||||
|
taxId: '',
|
||||||
|
notificationEmail: '',
|
||||||
|
notes: '',
|
||||||
|
});
|
||||||
|
const [relationForm, setRelationForm] = useState({ areaId: '', reason: '' });
|
||||||
|
const [metrics, setMetrics] = useState({ acts: 0, reports: 0, activeInspections: 0 });
|
||||||
|
const [acts, setActs] = useState<InspectionActListItemF4[]>([]);
|
||||||
|
const [reports, setReports] = useState<InspectionReportDetailF4[]>([]);
|
||||||
|
const [documentsLoading, setDocumentsLoading] = useState(false);
|
||||||
|
const [documentsError, setDocumentsError] = useState('');
|
||||||
|
const [documentSearch, setDocumentSearch] = useState('');
|
||||||
|
|
||||||
|
const activeRelations = useMemo(() => relations.filter((item) => item.active), [relations]);
|
||||||
|
|
||||||
|
const loadContext = async () => {
|
||||||
|
setLoadingContext(true);
|
||||||
|
setContextError('');
|
||||||
|
try {
|
||||||
|
const [loadedRegistry, loadedRelations, loadedAreas] = await Promise.all([
|
||||||
|
canReadRegistry ? getAssetRegistry(asset.id) : Promise.resolve(null),
|
||||||
|
canReadRelations ? listAreaCompanyRelations({ companyId: asset.id, includeHistory: true }) : Promise.resolve([]),
|
||||||
|
canManageRelations ? listOperationalAreas() : Promise.resolve([]),
|
||||||
|
]);
|
||||||
|
setRegistry(loadedRegistry);
|
||||||
|
setRelations(loadedRelations);
|
||||||
|
setAreas(loadedAreas);
|
||||||
|
if (loadedRegistry?.organizationProfile) {
|
||||||
|
const profile = loadedRegistry.organizationProfile;
|
||||||
|
setCompanyForm({
|
||||||
|
name: asset.name,
|
||||||
|
commonName: asset.commonName ?? '',
|
||||||
|
organizationKind: profile.organizationKind,
|
||||||
|
legalName: profile.legalName ?? asset.name,
|
||||||
|
taxId: profile.taxId ?? '',
|
||||||
|
notificationEmail: profile.notificationEmail ?? '',
|
||||||
|
notes: profile.notes ?? '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (requestError) {
|
||||||
|
setContextError(errorMessage(requestError));
|
||||||
|
} finally {
|
||||||
|
setLoadingContext(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => { void loadContext(); }, [asset.id]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
const loadMetrics = async () => {
|
||||||
|
try {
|
||||||
|
const [sealed, closed, rectified, reportPage, planned, inProgress] = await Promise.all([
|
||||||
|
canReadActs ? listInspectionActsGlobalF4({ companyId: asset.id, status: 'SEALED', pageSize: 1 }) : Promise.resolve(null),
|
||||||
|
canReadActs ? listInspectionActsGlobalF4({ companyId: asset.id, status: 'CLOSED', pageSize: 1 }) : Promise.resolve(null),
|
||||||
|
canReadActs ? listInspectionActsGlobalF4({ companyId: asset.id, status: 'RECTIFIED', pageSize: 1 }) : Promise.resolve(null),
|
||||||
|
canReadReports ? listInspectionReportsF4({ companyId: asset.id, pageSize: 1 }) : Promise.resolve(null),
|
||||||
|
canReadInspections ? listInspectionVisits({ companyId: asset.id, status: 'PLANNED', pageSize: 1 }) : Promise.resolve(null),
|
||||||
|
canReadInspections ? listInspectionVisits({ companyId: asset.id, status: 'IN_PROGRESS', pageSize: 1 }) : Promise.resolve(null),
|
||||||
|
]);
|
||||||
|
if (cancelled) return;
|
||||||
|
setMetrics({
|
||||||
|
acts: (sealed?.meta.total ?? 0) + (closed?.meta.total ?? 0) + (rectified?.meta.total ?? 0),
|
||||||
|
reports: reportPage?.meta.total ?? 0,
|
||||||
|
activeInspections: (planned?.meta.total ?? 0) + (inProgress?.meta.total ?? 0),
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
if (!cancelled) setMetrics({ acts: 0, reports: 0, activeInspections: 0 });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
void loadMetrics();
|
||||||
|
return () => { cancelled = true; };
|
||||||
|
}, [asset.id, canReadActs, canReadReports, canReadInspections]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (tab !== 'issued' || (!canReadActs && !canReadReports)) return;
|
||||||
|
let cancelled = false;
|
||||||
|
setDocumentsLoading(true);
|
||||||
|
setDocumentsError('');
|
||||||
|
Promise.all([
|
||||||
|
canReadActs ? loadAllActs(asset.id) : Promise.resolve([]),
|
||||||
|
canReadReports ? loadAllReports(asset.id) : Promise.resolve([]),
|
||||||
|
])
|
||||||
|
.then(([loadedActs, loadedReports]) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
setActs(loadedActs);
|
||||||
|
setReports(loadedReports);
|
||||||
|
})
|
||||||
|
.catch((requestError) => { if (!cancelled) setDocumentsError(errorMessage(requestError)); })
|
||||||
|
.finally(() => { if (!cancelled) setDocumentsLoading(false); });
|
||||||
|
return () => { cancelled = true; };
|
||||||
|
}, [tab, asset.id, canReadActs, canReadReports]);
|
||||||
|
|
||||||
|
const saveCompany = async (event: FormEvent) => {
|
||||||
|
event.preventDefault();
|
||||||
|
setSaving(true); setContextError(''); setSuccess('');
|
||||||
|
try {
|
||||||
|
let savedAsset = asset;
|
||||||
|
if (canEditAsset) {
|
||||||
|
savedAsset = await updateAsset(asset.id, {
|
||||||
|
name: companyForm.name.trim(),
|
||||||
|
commonName: companyForm.commonName.trim() || null,
|
||||||
|
});
|
||||||
|
setAsset(savedAsset);
|
||||||
|
}
|
||||||
|
if (canManageRegistry) {
|
||||||
|
await upsertOrganizationProfile(asset.id, {
|
||||||
|
organizationKind: companyForm.organizationKind,
|
||||||
|
legalName: companyForm.legalName.trim() || null,
|
||||||
|
taxId: companyForm.taxId.trim() || null,
|
||||||
|
notificationEmail: companyForm.notificationEmail.trim() || null,
|
||||||
|
notes: companyForm.notes.trim() || null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
setEditing(false);
|
||||||
|
setSuccess('Datos de la empresa actualizados.');
|
||||||
|
await loadContext();
|
||||||
|
} catch (requestError) {
|
||||||
|
setContextError(errorMessage(requestError));
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const addRelation = async (event: FormEvent) => {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!relationForm.areaId || relationForm.reason.trim().length < 3) return;
|
||||||
|
setSaving(true); setContextError(''); setSuccess('');
|
||||||
|
try {
|
||||||
|
await createAreaCompanyRelation({
|
||||||
|
areaId: relationForm.areaId,
|
||||||
|
companyId: asset.id,
|
||||||
|
reason: relationForm.reason.trim(),
|
||||||
|
});
|
||||||
|
setRelationForm({ areaId: '', reason: '' });
|
||||||
|
setSuccess('Área vinculada a la empresa.');
|
||||||
|
await loadContext();
|
||||||
|
} catch (requestError) {
|
||||||
|
setContextError(errorMessage(requestError));
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const endRelation = async (relation: AreaCompanyRelation) => {
|
||||||
|
const reason = window.prompt(`Motivo para finalizar el vínculo con ${relation.area.name}`);
|
||||||
|
if (!reason?.trim() || reason.trim().length < 3) return;
|
||||||
|
setSaving(true); setContextError(''); setSuccess('');
|
||||||
|
try {
|
||||||
|
await endAreaCompanyRelation(relation.id, reason.trim());
|
||||||
|
setSuccess('Vínculo finalizado. El historial quedó conservado.');
|
||||||
|
await loadContext();
|
||||||
|
} catch (requestError) {
|
||||||
|
setContextError(errorMessage(requestError));
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const setTab = (next: CompanyTab) => {
|
||||||
|
const nextParams = new URLSearchParams(params);
|
||||||
|
next === 'summary' ? nextParams.delete('tab') : nextParams.set('tab', next);
|
||||||
|
nextParams.delete('advanced');
|
||||||
|
setParams(nextParams);
|
||||||
|
};
|
||||||
|
|
||||||
|
const reportByAct = useMemo(() => new Map(reports.map((report) => [report.actId, report])), [reports]);
|
||||||
|
const filteredActs = useMemo(() => {
|
||||||
|
const needle = documentSearch.trim().toLocaleLowerCase('es');
|
||||||
|
if (!needle) return acts;
|
||||||
|
return acts.filter((act) => [
|
||||||
|
act.code,
|
||||||
|
act.title,
|
||||||
|
act.visit.code,
|
||||||
|
...act.areas.map((item) => item.name),
|
||||||
|
reportByAct.get(act.id)?.code ?? '',
|
||||||
|
reportByAct.get(act.id)?.gedoIfIdentifier ?? '',
|
||||||
|
].join(' ').toLocaleLowerCase('es').includes(needle));
|
||||||
|
}, [acts, documentSearch, reportByAct]);
|
||||||
|
|
||||||
|
const usedAreaIds = new Set(activeRelations.map((relation) => relation.area.id));
|
||||||
|
const availableAreas = areas.filter((item) => !usedAreaIds.has(item.id));
|
||||||
|
const profile = registry?.organizationProfile ?? null;
|
||||||
|
|
||||||
|
return <section className="narrow-section company-page">
|
||||||
|
<nav className="breadcrumb company-breadcrumb" aria-label="Ruta de empresa">
|
||||||
|
<Link to="/inventarios">Inventarios</Link><span>›</span>
|
||||||
|
<Link to="/inventarios?section=companies">Empresas</Link><span>›</span><strong>{asset.name}</strong>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header className="company-hero">
|
||||||
|
<div>
|
||||||
|
<span className="eyebrow">EMPRESA</span>
|
||||||
|
<h1>{asset.name}</h1>
|
||||||
|
<p><strong>{asset.code}</strong>{profile?.taxId ? ` · CUIT ${profile.taxId}` : ''}</p>
|
||||||
|
</div>
|
||||||
|
<div className="company-hero-actions">
|
||||||
|
<span className={`status-badge ${assetStatusClass(asset.informationStatus)}`}>{assetStatusLabel(asset.informationStatus)}</span>
|
||||||
|
{(canEditAsset || canManageRegistry) && tab === 'summary' && <button type="button" className="button primary" onClick={() => setEditing((current) => !current)}><Icon name="edit" />{editing ? 'Cerrar edición' : 'Editar empresa'}</button>}
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<nav className="company-tabs" aria-label="Secciones de la empresa">
|
||||||
|
<button type="button" className={tab === 'summary' ? 'active' : ''} onClick={() => setTab('summary')}>Resumen</button>
|
||||||
|
{(canReadActs || canReadReports) && <button type="button" className={tab === 'issued' ? 'active' : ''} onClick={() => setTab('issued')}>Actas e informes</button>}
|
||||||
|
{(canReadRegistry || canReadMedia) && <button type="button" className={tab === 'documents' ? 'active' : ''} onClick={() => setTab('documents')}>Documentación</button>}
|
||||||
|
{canReadHistory && <button type="button" className={tab === 'history' ? 'active' : ''} onClick={() => setTab('history')}>Historial</button>}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
{contextError && <Alert>{contextError}</Alert>}
|
||||||
|
{success && <Alert type="success">{success}</Alert>}
|
||||||
|
|
||||||
|
{tab === 'summary' && <div className="company-stack">
|
||||||
|
{loadingContext ? <LoadingBlock label="Cargando empresa…" /> : <>
|
||||||
|
<article className="panel company-card">
|
||||||
|
<div className="company-card-heading">
|
||||||
|
<div><span className="eyebrow">IDENTIDAD</span><h2>Datos de la empresa</h2><p>La información que se usa para identificarla y enviar documentación oficial.</p></div>
|
||||||
|
</div>
|
||||||
|
{editing ? <form className="company-edit-form" onSubmit={saveCompany}>
|
||||||
|
<div className="form-grid">
|
||||||
|
<label className="field"><span>Nombre</span><input value={companyForm.name} disabled={!canEditAsset} onChange={(event) => setCompanyForm({ ...companyForm, name: event.target.value })} required /></label>
|
||||||
|
<label className="field"><span>Nombre corto / sigla <em>opcional</em></span><input value={companyForm.commonName} disabled={!canEditAsset} onChange={(event) => setCompanyForm({ ...companyForm, commonName: event.target.value })} placeholder="Ej.: EMESA" /></label>
|
||||||
|
<label className="field"><span>Tipo</span><SearchableSelect value={companyForm.organizationKind} disabled={!canManageRegistry} onChange={(event) => setCompanyForm({ ...companyForm, organizationKind: event.target.value as OrganizationKind })}>{Object.entries(organizationLabels).map(([value, label]) => <option key={value} value={value}>{label}</option>)}</SearchableSelect></label>
|
||||||
|
<label className="field"><span>Razón social <em>opcional</em></span><input value={companyForm.legalName} disabled={!canManageRegistry} onChange={(event) => setCompanyForm({ ...companyForm, legalName: event.target.value })} /></label>
|
||||||
|
<label className="field"><span>CUIT <em>opcional</em></span><input value={companyForm.taxId} disabled={!canManageRegistry} onChange={(event) => setCompanyForm({ ...companyForm, taxId: event.target.value })} /></label>
|
||||||
|
<label className="field"><span>Email oficial para actas <em>opcional</em></span><input type="email" value={companyForm.notificationEmail} disabled={!canManageRegistry} onChange={(event) => setCompanyForm({ ...companyForm, notificationEmail: event.target.value })} /></label>
|
||||||
|
</div>
|
||||||
|
<label className="field"><span>Notas <em>opcional</em></span><textarea rows={2} value={companyForm.notes} disabled={!canManageRegistry} onChange={(event) => setCompanyForm({ ...companyForm, notes: event.target.value })} /></label>
|
||||||
|
<div className="form-actions"><button type="button" className="button secondary" onClick={() => setEditing(false)}>Cancelar</button><button className="button primary" disabled={saving}>{saving ? 'Guardando…' : 'Guardar cambios'}</button></div>
|
||||||
|
</form> : <div className="company-data-grid">
|
||||||
|
<div><small>Razón social</small><strong>{profile?.legalName || asset.name}</strong></div>
|
||||||
|
<div><small>Tipo</small><strong>{organizationLabels[profile?.organizationKind ?? 'COMPANY']}</strong></div>
|
||||||
|
<div><small>CUIT</small><strong>{profile?.taxId || 'Sin informar'}</strong></div>
|
||||||
|
<div><small>Email oficial para actas</small><strong>{profile?.notificationEmail || 'Sin informar'}</strong></div>
|
||||||
|
</div>}
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<article className="panel company-card">
|
||||||
|
<div className="company-card-heading">
|
||||||
|
<div><span className="eyebrow">OPERACIÓN</span><h2>Áreas donde opera</h2><p>Estas relaciones indican dónde participa la empresa. No cambian la jerarquía física del Inventario.</p></div>
|
||||||
|
<span className="count-pill">{activeRelations.length}</span>
|
||||||
|
</div>
|
||||||
|
{activeRelations.length === 0 ? <EmptyState title="Sin áreas vinculadas" text="Todavía no hay áreas operativas asociadas a esta empresa." /> : <div className="company-area-list">{activeRelations.map((relation) => <div className="company-area-row" key={relation.id}>
|
||||||
|
<Link to={`/inventarios/${relation.area.id}`}><strong>{relation.area.name}</strong><small>{relation.area.code} · {relationRoleLabel(relation.relationRole)}</small></Link>
|
||||||
|
<div><span className="status-badge active">Activa</span>{canManageRelations && <button type="button" className="button text compact" disabled={saving} onClick={() => void endRelation(relation)}>Finalizar</button>}</div>
|
||||||
|
</div>)}</div>}
|
||||||
|
{canManageRelations && <details className="company-inline-action"><summary><Icon name="plus" size={15} />Vincular otra área</summary><form onSubmit={addRelation}><div className="form-grid"><label className="field"><span>Área</span><SearchableSelect value={relationForm.areaId} onChange={(event) => setRelationForm({ ...relationForm, areaId: event.target.value })} required><option value="">Seleccionar área…</option>{availableAreas.map((item) => <option key={item.id} value={item.id}>{item.name} · {item.code}</option>)}</SearchableSelect></label><label className="field"><span>Motivo</span><input value={relationForm.reason} onChange={(event) => setRelationForm({ ...relationForm, reason: event.target.value })} minLength={3} required placeholder="Ej.: operación vigente" /></label></div><button className="button primary" disabled={saving || !relationForm.areaId || relationForm.reason.trim().length < 3}>Vincular área</button></form></details>}
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<article className="panel company-card company-activity-card">
|
||||||
|
<div className="company-card-heading"><div><span className="eyebrow">INSPECCIONES</span><h2>Actividad de la empresa</h2><p>Acceso rápido a la documentación que ya fue emitida.</p></div></div>
|
||||||
|
<div className="company-metrics">
|
||||||
|
<div><small>Actas emitidas</small><strong>{metrics.acts}</strong></div>
|
||||||
|
<div><small>Informes</small><strong>{metrics.reports}</strong></div>
|
||||||
|
<div><small>Inspecciones activas</small><strong>{metrics.activeInspections}</strong></div>
|
||||||
|
</div>
|
||||||
|
{(canReadActs || canReadReports) && <div className="company-card-actions"><button type="button" className="button primary" onClick={() => setTab('issued')}>Ver actas e informes <Icon name="chevron" /></button></div>}
|
||||||
|
</article>
|
||||||
|
</>}
|
||||||
|
</div>}
|
||||||
|
|
||||||
|
{tab === 'issued' && <div className="company-stack">
|
||||||
|
<article className="panel company-card">
|
||||||
|
<div className="company-card-heading company-doc-heading"><div><span className="eyebrow">DOCUMENTACIÓN EMITIDA</span><h2>Actas e informes</h2><p>Historial documental de esta empresa. Sólo se muestran Actas ya emitidas y sus Informes asociados.</p></div><div className="company-doc-counts"><span>{acts.length} actas</span><span>{reports.length} informes</span></div></div>
|
||||||
|
<label className="company-document-search"><Icon name="search" /><input value={documentSearch} onChange={(event) => setDocumentSearch(event.target.value)} placeholder="Buscar por acta, informe, inspección, área o GEDO" /></label>
|
||||||
|
{documentsError && <Alert>{documentsError}</Alert>}
|
||||||
|
{documentsLoading ? <LoadingBlock label="Cargando documentación emitida…" /> : filteredActs.length === 0 ? <EmptyState title="Sin documentación emitida" text="Todavía no hay Actas selladas para esta empresa." /> : <div className="table-scroll company-doc-table"><table><thead><tr><th>Fecha</th><th>Área</th><th>Acta</th><th>Inspección</th><th>Informe</th><th>Oficialización</th><th /></tr></thead><tbody>{filteredActs.map((act) => {
|
||||||
|
const report = reportByAct.get(act.id);
|
||||||
|
return <tr key={act.id}>
|
||||||
|
<td>{formatDate(act.occurredAt)}</td>
|
||||||
|
<td><strong className="table-primary">{areaLabel(act.areas)}</strong></td>
|
||||||
|
<td><Link className="text-link" to={`/inspecciones/actas/${act.id}`}>{act.code}</Link></td>
|
||||||
|
<td><Link className="text-link" to={`/inspecciones/${act.visitId}`}>{act.visit.code}</Link></td>
|
||||||
|
<td>{report ? <Link className="text-link" to={`/informes/${report.id}`}>{report.code}</Link> : <span className="status-badge pending">Pendiente de INF</span>}</td>
|
||||||
|
<td>{report ? <span className={`status-badge ${reportStatusClass(report)}`}>{reportStatusLabel(report)}</span> : <span className="muted">—</span>}</td>
|
||||||
|
<td className="action-cell"><Link className="icon-button" to={`/inspecciones/actas/${act.id}`} aria-label={`Abrir ${act.code}`}><Icon name="chevron" /></Link></td>
|
||||||
|
</tr>;
|
||||||
|
})}</tbody></table></div>}
|
||||||
|
</article>
|
||||||
|
</div>}
|
||||||
|
|
||||||
|
{tab === 'documents' && <div className="company-stack">
|
||||||
|
{loadingContext ? <LoadingBlock label="Cargando documentación…" /> : <>
|
||||||
|
{canReadRegistry && <article className="panel company-card">
|
||||||
|
<div className="company-card-heading"><div><span className="eyebrow">RESPALDO</span><h2>Documentos de la empresa</h2><p>Documentos e identificadores que respaldan los datos institucionales.</p></div><Link className="button secondary" to={`/inventarios/${asset.id}?advanced=1&tab=registry`}>Administrar</Link></div>
|
||||||
|
{registry?.sourceDocuments.length ? <div className="company-document-list">{registry.sourceDocuments.map((document) => <div key={document.linkId}><div><strong>{document.title}</strong><small>{document.documentNumber || document.documentType}{document.issuer ? ` · ${document.issuer}` : ''}</small></div><span className="tag">{document.relationType}</span></div>)}</div> : <div className="inline-empty">Todavía no hay documentos respaldatorios vinculados.</div>}
|
||||||
|
{registry?.externalIdentifiers.length ? <details className="company-more"><summary>Ver identificadores externos ({registry.externalIdentifiers.length})</summary><div className="company-identifier-list">{registry.externalIdentifiers.map((item) => <div key={item.id}><strong>{item.namespace}</strong><span>{item.value}</span><small>{item.validUntil ? 'Histórico' : 'Vigente'}</small></div>)}</div></details> : null}
|
||||||
|
</article>}
|
||||||
|
{canReadMedia && <AssetMediaPanel assetId={asset.id} assetName={asset.name} canManage={canManageMedia} />}
|
||||||
|
<div className="company-advanced-link"><span>¿Necesitás procedencia, composición UTE u otros datos técnicos?</span><Link to={`/inventarios/${asset.id}?advanced=1&tab=registry`}>Abrir administración avanzada</Link></div>
|
||||||
|
</>}
|
||||||
|
</div>}
|
||||||
|
|
||||||
|
{tab === 'history' && canReadHistory && <AssetHistoryPanel assetId={asset.id} />}
|
||||||
|
</section>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { useParams, useSearchParams } from 'react-router';
|
||||||
|
import { useAuth } from '../auth/AuthContext';
|
||||||
|
import { hasAdministratorRole } from '../auth/adminAccess';
|
||||||
|
import { Alert, LoadingBlock, errorMessage } from '../components/Feedback';
|
||||||
|
import { getAsset } from '../lib/api';
|
||||||
|
import type { AssetDetail } from '../lib/api';
|
||||||
|
import { AssetEditorPage } from './AssetEditorPage';
|
||||||
|
import { CompanyInventoryPage } from './CompanyInventoryPage';
|
||||||
|
import { TerritorialInventoryPage, isTerritorialInventoryAsset } from './TerritorialInventoryPage';
|
||||||
|
|
||||||
|
export function InventoryDetailPage() {
|
||||||
|
const { id } = useParams();
|
||||||
|
const [params] = useSearchParams();
|
||||||
|
const { user } = useAuth();
|
||||||
|
const [asset, setAsset] = useState<AssetDetail | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!id) {
|
||||||
|
setError('No se encontró el registro solicitado.');
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoading(true);
|
||||||
|
setError('');
|
||||||
|
getAsset(id)
|
||||||
|
.then(setAsset)
|
||||||
|
.catch((requestError) => setError(errorMessage(requestError)))
|
||||||
|
.finally(() => setLoading(false));
|
||||||
|
}, [id]);
|
||||||
|
|
||||||
|
if (loading) return <LoadingBlock label="Cargando registro…" />;
|
||||||
|
if (!asset) return <Alert>{error || 'No se pudo cargar el registro.'}</Alert>;
|
||||||
|
|
||||||
|
const advancedRequested = params.get('advanced') === '1';
|
||||||
|
const advancedAllowed = hasAdministratorRole(user);
|
||||||
|
const advanced = advancedRequested && advancedAllowed;
|
||||||
|
const isCompany = asset.type.code.toLowerCase() === 'empresa';
|
||||||
|
|
||||||
|
if (isCompany && !advanced) {
|
||||||
|
return <CompanyInventoryPage initialAsset={asset} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isTerritorialInventoryAsset(asset) && !advanced) {
|
||||||
|
return <TerritorialInventoryPage initialAsset={asset} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <AssetEditorPage />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
|
import type { FormEvent } from 'react';
|
||||||
|
import { Link, useSearchParams } from 'react-router';
|
||||||
|
import { useAuth } from '../auth/AuthContext';
|
||||||
|
import { hasAdministratorRole } from '../auth/adminAccess';
|
||||||
|
import { Alert, LoadingBlock, errorMessage } from '../components/Feedback';
|
||||||
|
import { Icon } from '../components/Icon';
|
||||||
|
import { AssetHistoryPanel } from '../features/assets/AssetHistoryPanel';
|
||||||
|
import { assetStatusClass, assetStatusLabel } from '../features/assets/assetPresentation';
|
||||||
|
import {
|
||||||
|
getAssetLineage,
|
||||||
|
listAreaCompanyRelations,
|
||||||
|
listAssetTreeChildren,
|
||||||
|
listInspectionVisits,
|
||||||
|
updateAsset,
|
||||||
|
} from '../lib/api';
|
||||||
|
import type { AreaCompanyRelation, AssetDetail, AssetLineageItem, AssetListItem } from '../lib/api';
|
||||||
|
import {
|
||||||
|
listInspectionActsGlobalF4,
|
||||||
|
type InspectionActStatusF4,
|
||||||
|
} from '../lib/inspectionActF4Api';
|
||||||
|
import { listInspectionReportsF4 } from '../lib/reportWorkflowApi';
|
||||||
|
import './territorialInventory.css';
|
||||||
|
|
||||||
|
type TerritoryTab = 'summary' | 'history';
|
||||||
|
|
||||||
|
function normalized(value: string) {
|
||||||
|
return value
|
||||||
|
.normalize('NFD')
|
||||||
|
.replace(/[\u0300-\u036f]/g, '')
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, ' ')
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function tokensForType(type: { code: string; name: string }) {
|
||||||
|
return new Set(`${normalized(type.code)} ${normalized(type.name)}`.split(' ').filter(Boolean));
|
||||||
|
}
|
||||||
|
|
||||||
|
function typeTokens(asset: AssetDetail) {
|
||||||
|
return tokensForType(asset.type);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isTerritorialInventoryAsset(asset: AssetDetail) {
|
||||||
|
const tokens = typeTokens(asset);
|
||||||
|
return tokens.has('departamento') || tokens.has('area') || tokens.has('yacimiento');
|
||||||
|
}
|
||||||
|
|
||||||
|
function isOperationalArea(asset: AssetDetail) {
|
||||||
|
return typeTokens(asset).has('area');
|
||||||
|
}
|
||||||
|
|
||||||
|
function isYacimiento(asset: AssetDetail) {
|
||||||
|
return typeTokens(asset).has('yacimiento');
|
||||||
|
}
|
||||||
|
|
||||||
|
function lineageArea(lineage: AssetLineageItem[]) {
|
||||||
|
return [...lineage].reverse().find((item) => tokensForType(item.type).has('area')) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function relationRoleLabel(role: AreaCompanyRelation['relationRole']) {
|
||||||
|
if (role === 'OPERATOR') return 'Operadora';
|
||||||
|
if (role === 'TECHNICAL_OPERATOR') return 'Operadora técnica';
|
||||||
|
if (role === 'CONCESSIONAIRE') return 'Concesionaria / titular';
|
||||||
|
if (role === 'PERMIT_HOLDER') return 'Permisionaria';
|
||||||
|
if (role === 'PARTICIPANT') return 'Participante';
|
||||||
|
return 'Vinculada';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TerritorialInventoryPage({ initialAsset }: { initialAsset: AssetDetail }) {
|
||||||
|
const [params, setParams] = useSearchParams();
|
||||||
|
const requestedTab = params.get('tab') as TerritoryTab | null;
|
||||||
|
const tab: TerritoryTab = requestedTab === 'history' ? 'history' : 'summary';
|
||||||
|
const { user, hasPermission } = useAuth();
|
||||||
|
const canEdit = hasPermission('assets.update');
|
||||||
|
const canCreate = hasPermission('assets.create');
|
||||||
|
const canReadHistory = hasPermission('assets.read_history');
|
||||||
|
const canReadRelations = hasPermission('asset_relations.read');
|
||||||
|
const canReadActs = hasPermission('inspection_acts.read');
|
||||||
|
const canReadReports = hasPermission('inspection_reports.read');
|
||||||
|
const canReadInspections = hasPermission('inspections.read');
|
||||||
|
const canAdvanced = hasAdministratorRole(user);
|
||||||
|
|
||||||
|
const [asset, setAsset] = useState(initialAsset);
|
||||||
|
const [children, setChildren] = useState<AssetListItem[]>([]);
|
||||||
|
const [childrenHasMore, setChildrenHasMore] = useState(false);
|
||||||
|
const [lineage, setLineage] = useState<AssetLineageItem[]>([]);
|
||||||
|
const [relations, setRelations] = useState<AreaCompanyRelation[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
const [success, setSuccess] = useState('');
|
||||||
|
const [editing, setEditing] = useState(false);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [name, setName] = useState(initialAsset.name);
|
||||||
|
const [description, setDescription] = useState(initialAsset.description ?? '');
|
||||||
|
const [metrics, setMetrics] = useState({ activeInspections: 0, acts: 0, reports: 0 });
|
||||||
|
|
||||||
|
const area = isOperationalArea(asset);
|
||||||
|
const yacimiento = isYacimiento(asset);
|
||||||
|
const activeRelations = useMemo(() => relations.filter((item) => item.active), [relations]);
|
||||||
|
const relationAreaContext = useMemo(() => {
|
||||||
|
if (area) return { id: asset.id, code: asset.code, name: asset.name };
|
||||||
|
if (asset.operationalArea) return asset.operationalArea;
|
||||||
|
const ancestor = lineageArea(lineage);
|
||||||
|
return ancestor ? { id: ancestor.id, code: ancestor.code, name: ancestor.name } : null;
|
||||||
|
}, [area, asset.id, asset.code, asset.name, asset.operationalArea, lineage]);
|
||||||
|
|
||||||
|
const loadSummary = async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError('');
|
||||||
|
try {
|
||||||
|
const loadedLineage = await getAssetLineage(asset.id);
|
||||||
|
const ancestorArea = lineageArea(loadedLineage);
|
||||||
|
const relationAreaId = area
|
||||||
|
? asset.id
|
||||||
|
: asset.operationalArea?.id ?? ancestorArea?.id ?? null;
|
||||||
|
const [childPage, loadedRelations] = await Promise.all([
|
||||||
|
listAssetTreeChildren({ parentId: asset.id, limit: 100 }),
|
||||||
|
relationAreaId && canReadRelations
|
||||||
|
? listAreaCompanyRelations({ areaId: relationAreaId, includeHistory: true })
|
||||||
|
: Promise.resolve([]),
|
||||||
|
]);
|
||||||
|
setLineage(loadedLineage);
|
||||||
|
setChildren(childPage.data);
|
||||||
|
setChildrenHasMore(childPage.meta.hasMore);
|
||||||
|
setRelations(loadedRelations);
|
||||||
|
} catch (requestError) {
|
||||||
|
setError(errorMessage(requestError));
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => { void loadSummary(); }, [asset.id, area, canReadRelations]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!area) {
|
||||||
|
setMetrics({ activeInspections: 0, acts: 0, reports: 0 });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let cancelled = false;
|
||||||
|
const loadMetrics = async () => {
|
||||||
|
try {
|
||||||
|
const actStatuses: InspectionActStatusF4[] = ['SEALED', 'CLOSED', 'RECTIFIED'];
|
||||||
|
const [planned, inProgress, actPages, reportPage] = await Promise.all([
|
||||||
|
canReadInspections ? listInspectionVisits({ areaId: asset.id, status: 'PLANNED', pageSize: 1 }) : Promise.resolve(null),
|
||||||
|
canReadInspections ? listInspectionVisits({ areaId: asset.id, status: 'IN_PROGRESS', pageSize: 1 }) : Promise.resolve(null),
|
||||||
|
canReadActs
|
||||||
|
? Promise.all(actStatuses.map((status) => listInspectionActsGlobalF4({ areaId: asset.id, status, pageSize: 1 })))
|
||||||
|
: Promise.resolve([]),
|
||||||
|
canReadReports ? listInspectionReportsF4({ areaId: asset.id, pageSize: 1 }) : Promise.resolve(null),
|
||||||
|
]);
|
||||||
|
if (cancelled) return;
|
||||||
|
setMetrics({
|
||||||
|
activeInspections: (planned?.meta.total ?? 0) + (inProgress?.meta.total ?? 0),
|
||||||
|
acts: actPages.reduce((total, page) => total + page.meta.total, 0),
|
||||||
|
reports: reportPage?.meta.total ?? 0,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
if (!cancelled) setMetrics({ activeInspections: 0, acts: 0, reports: 0 });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
void loadMetrics();
|
||||||
|
return () => { cancelled = true; };
|
||||||
|
}, [asset.id, area, canReadActs, canReadReports, canReadInspections]);
|
||||||
|
|
||||||
|
const save = async (event: FormEvent) => {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!canEdit || !name.trim()) return;
|
||||||
|
setSaving(true); setError(''); setSuccess('');
|
||||||
|
try {
|
||||||
|
const saved = await updateAsset(asset.id, {
|
||||||
|
name: name.trim(),
|
||||||
|
description: description.trim() || null,
|
||||||
|
});
|
||||||
|
setAsset(saved);
|
||||||
|
setName(saved.name);
|
||||||
|
setDescription(saved.description ?? '');
|
||||||
|
setEditing(false);
|
||||||
|
setSuccess('Datos actualizados.');
|
||||||
|
} catch (requestError) {
|
||||||
|
setError(errorMessage(requestError));
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const setTab = (next: TerritoryTab) => {
|
||||||
|
const nextParams = new URLSearchParams(params);
|
||||||
|
next === 'summary' ? nextParams.delete('tab') : nextParams.set('tab', next);
|
||||||
|
nextParams.delete('advanced');
|
||||||
|
setParams(nextParams);
|
||||||
|
};
|
||||||
|
|
||||||
|
return <section className="narrow-section territory-page">
|
||||||
|
<nav className="breadcrumb territory-breadcrumb" aria-label="Ruta territorial">
|
||||||
|
<Link to="/inventarios">Inventarios</Link><span>›</span>
|
||||||
|
<Link to="/inventarios?section=territory">Áreas y yacimientos</Link><span>›</span><strong>{asset.name}</strong>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<header className="territory-hero">
|
||||||
|
<div>
|
||||||
|
<span className="eyebrow">{asset.type.name.toUpperCase()}</span>
|
||||||
|
<h1>{asset.name}</h1>
|
||||||
|
<p><strong>{asset.code}</strong></p>
|
||||||
|
</div>
|
||||||
|
<div className="territory-hero-actions">
|
||||||
|
<span className={`status-badge ${assetStatusClass(asset.informationStatus)}`}>{assetStatusLabel(asset.informationStatus)}</span>
|
||||||
|
{canEdit && tab === 'summary' && <button type="button" className="button secondary" onClick={() => setEditing((current) => !current)}><Icon name="edit" />{editing ? 'Cancelar edición' : 'Editar'}</button>}
|
||||||
|
{canCreate && tab === 'summary' && <Link className="button primary" to={`/inventarios/nuevo?parentId=${asset.id}`}><Icon name="plus" />Agregar elemento</Link>}
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div className="territory-purpose-note"><Icon name="map" /><span>Este nivel organiza el territorio y la navegación. Los hallazgos se cargan sobre elementos inspeccionables, no sobre {asset.type.name.toLowerCase()}s.</span></div>
|
||||||
|
|
||||||
|
<nav className="territory-tabs" aria-label="Secciones territoriales">
|
||||||
|
<button type="button" className={tab === 'summary' ? 'active' : ''} onClick={() => setTab('summary')}>Resumen</button>
|
||||||
|
{canReadHistory && <button type="button" className={tab === 'history' ? 'active' : ''} onClick={() => setTab('history')}>Historial</button>}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
{error && <Alert>{error}</Alert>}{success && <Alert type="success">{success}</Alert>}
|
||||||
|
|
||||||
|
{tab === 'summary' && <div className="territory-stack">
|
||||||
|
<article className="panel territory-card">
|
||||||
|
<div className="territory-card-heading">
|
||||||
|
<div><span className="eyebrow">DATOS BÁSICOS</span><h2>Identificación</h2></div>
|
||||||
|
</div>
|
||||||
|
{editing ? <form className="territory-edit-form" onSubmit={save}>
|
||||||
|
<label className="field"><span>Nombre</span><input value={name} onChange={(event) => setName(event.target.value)} required maxLength={200} /></label>
|
||||||
|
<label className="field"><span>Descripción <em>opcional</em></span><textarea value={description} onChange={(event) => setDescription(event.target.value)} rows={3} maxLength={4000} /></label>
|
||||||
|
<div className="form-actions"><button type="button" className="button secondary" onClick={() => { setEditing(false); setName(asset.name); setDescription(asset.description ?? ''); }}>Cancelar</button><button className="button primary" disabled={saving}><Icon name="check" />{saving ? 'Guardando…' : 'Guardar'}</button></div>
|
||||||
|
</form> : <div className="territory-data-grid">
|
||||||
|
<div><small>Tipo</small><strong>{asset.type.name}</strong></div>
|
||||||
|
<div><small>Código DH</small><strong>{asset.code}</strong></div>
|
||||||
|
{asset.description && <div className="wide"><small>Descripción</small><strong>{asset.description}</strong></div>}
|
||||||
|
</div>}
|
||||||
|
</article>
|
||||||
|
|
||||||
|
<article className="panel territory-card">
|
||||||
|
<div className="territory-card-heading">
|
||||||
|
<div><span className="eyebrow">CONTENIDO</span><h2>Registros dentro de {asset.name}</h2><p>Acceso directo a los niveles que dependen de este registro.</p></div>
|
||||||
|
<span className="count-pill">{children.length}{childrenHasMore ? '+' : ''}</span>
|
||||||
|
</div>
|
||||||
|
{loading ? <LoadingBlock label="Cargando contenido…" /> : children.length === 0 ? <div className="inline-empty">Todavía no hay registros dentro de {asset.name}.</div> : <div className="territory-child-list">
|
||||||
|
{children.map((child) => <Link to={`/inventarios/${child.id}`} key={child.id} className="territory-child-row">
|
||||||
|
<span className="asset-symbol"><Icon name="layers" /></span>
|
||||||
|
<span><strong>{child.name}</strong><small>{child.type.name} · {child.code}</small></span>
|
||||||
|
<span className={`status-badge ${assetStatusClass(child.informationStatus)}`}>{assetStatusLabel(child.informationStatus)}</span>
|
||||||
|
<Icon name="chevron" size={16} />
|
||||||
|
</Link>)}
|
||||||
|
</div>}
|
||||||
|
{childrenHasMore && <div className="territory-card-actions"><Link className="button secondary" to={`/inventarios?section=territory&parentId=${asset.id}`}>Ver contenido completo</Link></div>}
|
||||||
|
</article>
|
||||||
|
|
||||||
|
{relationAreaContext && canReadRelations && <article className="panel territory-card">
|
||||||
|
<div className="territory-card-heading"><div><span className="eyebrow">OPERACIÓN</span><h2>Empresas vinculadas</h2><p>{area ? 'Quién opera o participa actualmente en esta área.' : yacimiento ? `Empresas que operan o participan en el Área ${relationAreaContext.name}, contexto operativo de este yacimiento.` : `Empresas vinculadas al Área ${relationAreaContext.name}.`}</p></div><span className="count-pill">{activeRelations.length}</span></div>
|
||||||
|
{loading ? <LoadingBlock label="Cargando empresas…" /> : activeRelations.length === 0 ? <div className="inline-empty">No hay empresas con vínculo vigente en el Área {relationAreaContext.name}.</div> : <div className="territory-company-list">
|
||||||
|
{activeRelations.map((relation) => <Link to={`/inventarios/${relation.company.id}`} key={relation.id} className="territory-company-row"><span><strong>{relation.company.name}</strong><small>{relationRoleLabel(relation.relationRole)}{!area ? ` · ${relation.area.name}` : ''}</small></span><Icon name="chevron" size={16} /></Link>)}
|
||||||
|
</div>}
|
||||||
|
</article>}
|
||||||
|
|
||||||
|
{area && (canReadInspections || canReadActs || canReadReports) && <article className="panel territory-card">
|
||||||
|
<div className="territory-card-heading"><div><span className="eyebrow">ACTIVIDAD</span><h2>Actividad del área</h2><p>Resumen documental y operativo, sin mezclarlo con hallazgos de los elementos inspeccionados.</p></div></div>
|
||||||
|
<div className="territory-metrics">
|
||||||
|
{canReadInspections && <div><small>Inspecciones activas</small><strong>{metrics.activeInspections}</strong></div>}
|
||||||
|
{canReadActs && <div><small>Actas emitidas</small><strong>{metrics.acts}</strong></div>}
|
||||||
|
{canReadReports && <div><small>Informes</small><strong>{metrics.reports}</strong></div>}
|
||||||
|
</div>
|
||||||
|
</article>}
|
||||||
|
|
||||||
|
{canAdvanced && <div className="territory-advanced-link"><span>Los datos estructurales, procedencia, ubicación y opciones técnicas quedan fuera de la vista cotidiana.</span><Link to={`/inventarios/${asset.id}?advanced=1`}>Administración avanzada</Link></div>}
|
||||||
|
</div>}
|
||||||
|
|
||||||
|
{tab === 'history' && canReadHistory && <AssetHistoryPanel assetId={asset.id} />}
|
||||||
|
</section>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
.company-page { display: grid; gap: 18px; }
|
||||||
|
.company-breadcrumb { margin-bottom: 0; }
|
||||||
|
|
||||||
|
.company-hero {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-end;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 24px;
|
||||||
|
padding: 4px 0 2px;
|
||||||
|
}
|
||||||
|
.company-hero h1 { margin: 6px 0 5px; font-size: clamp(31px, 3.5vw, 44px); line-height: 1.02; letter-spacing: -.045em; }
|
||||||
|
.company-hero p { margin: 0; color: var(--muted); font-size: 13px; }
|
||||||
|
.company-hero-actions { display: flex; align-items: center; gap: 12px; }
|
||||||
|
|
||||||
|
.company-tabs {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
overflow-x: auto;
|
||||||
|
padding: 0 0 1px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.company-tabs button {
|
||||||
|
position: relative;
|
||||||
|
min-height: 43px;
|
||||||
|
padding: 9px 13px;
|
||||||
|
border: 0;
|
||||||
|
color: #566178;
|
||||||
|
background: transparent;
|
||||||
|
cursor: pointer;
|
||||||
|
white-space: nowrap;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
.company-tabs button:hover { color: var(--ink); }
|
||||||
|
.company-tabs button.active { color: var(--blue); }
|
||||||
|
.company-tabs button.active::after { content: ''; position: absolute; left: 10px; right: 10px; bottom: -1px; height: 2px; border-radius: 2px; background: var(--blue); }
|
||||||
|
|
||||||
|
.company-stack { display: grid; gap: 15px; }
|
||||||
|
.company-card { padding: 23px; }
|
||||||
|
.company-card-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 18px; margin-bottom: 18px; }
|
||||||
|
.company-card-heading h2 { margin: 4px 0 4px; }
|
||||||
|
.company-card-heading p { max-width: 680px; margin: 0; color: var(--muted); font-size: 12px; line-height: 1.5; }
|
||||||
|
.company-card-actions { display: flex; justify-content: flex-end; margin-top: 17px; }
|
||||||
|
|
||||||
|
.company-data-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1px; overflow: hidden; border: 1px solid var(--line); border-radius: 11px; background: var(--line); }
|
||||||
|
.company-data-grid > div { min-height: 78px; padding: 15px 16px; background: #fff; }
|
||||||
|
.company-data-grid small, .company-data-grid strong { display: block; }
|
||||||
|
.company-data-grid small { margin-bottom: 7px; color: var(--muted); font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .04em; }
|
||||||
|
.company-data-grid strong { font-size: 13px; font-weight: 750; }
|
||||||
|
.company-edit-form { display: grid; gap: 16px; }
|
||||||
|
|
||||||
|
.company-area-list { display: grid; gap: 8px; }
|
||||||
|
.company-area-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; min-height: 62px; padding: 12px 14px; border: 1px solid #e3e7ee; border-radius: 10px; background: #fafbfc; }
|
||||||
|
.company-area-row > a { min-width: 0; text-decoration: none; }
|
||||||
|
.company-area-row > a:hover strong { color: var(--blue); }
|
||||||
|
.company-area-row strong, .company-area-row small { display: block; }
|
||||||
|
.company-area-row strong { font-size: 13px; }
|
||||||
|
.company-area-row small { margin-top: 4px; color: var(--muted); font-size: 10px; }
|
||||||
|
.company-area-row > div { display: flex; align-items: center; gap: 7px; }
|
||||||
|
.company-inline-action { margin-top: 13px; border: 1px dashed #cfd7e5; border-radius: 10px; background: #fbfcfe; }
|
||||||
|
.company-inline-action summary { display: flex; align-items: center; gap: 7px; padding: 13px 14px; cursor: pointer; color: var(--blue); font-size: 12px; font-weight: 750; list-style: none; }
|
||||||
|
.company-inline-action summary::-webkit-details-marker { display: none; }
|
||||||
|
.company-inline-action form { display: grid; gap: 13px; padding: 0 14px 14px; }
|
||||||
|
|
||||||
|
.company-metrics { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }
|
||||||
|
.company-metrics > div { display: grid; gap: 6px; padding: 16px; border: 1px solid #e2e7ef; border-radius: 11px; background: #f8faff; }
|
||||||
|
.company-metrics small { color: var(--muted); font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .05em; }
|
||||||
|
.company-metrics strong { color: #173b7a; font-size: 25px; line-height: 1; letter-spacing: -.04em; }
|
||||||
|
|
||||||
|
.company-doc-heading { align-items: center; }
|
||||||
|
.company-doc-counts { display: flex; gap: 7px; }
|
||||||
|
.company-doc-counts span { padding: 6px 9px; border-radius: 999px; color: #536078; background: #f0f3f8; font-size: 10px; font-weight: 750; }
|
||||||
|
.company-document-search { display: flex; align-items: center; gap: 9px; width: 100%; margin-bottom: 17px; padding: 0 12px; border: 1px solid #d8dee8; border-radius: 10px; background: white; }
|
||||||
|
.company-document-search .icon { color: #818ba0; }
|
||||||
|
.company-document-search input { width: 100%; min-height: 43px; border: 0; outline: 0; background: transparent; font-size: 12px; }
|
||||||
|
.company-doc-table table { min-width: 870px; }
|
||||||
|
.company-doc-table td { vertical-align: middle; }
|
||||||
|
|
||||||
|
.company-document-list { display: grid; gap: 8px; }
|
||||||
|
.company-document-list > div { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding: 13px 14px; border: 1px solid #e2e6ed; border-radius: 10px; background: #fbfcfd; }
|
||||||
|
.company-document-list strong, .company-document-list small { display: block; }
|
||||||
|
.company-document-list strong { font-size: 12px; }
|
||||||
|
.company-document-list small { margin-top: 4px; color: var(--muted); font-size: 10px; }
|
||||||
|
.company-more { margin-top: 13px; }
|
||||||
|
.company-more summary { cursor: pointer; color: #59657b; font-size: 11px; font-weight: 750; }
|
||||||
|
.company-identifier-list { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 8px; margin-top: 10px; }
|
||||||
|
.company-identifier-list > div { display: grid; gap: 3px; padding: 11px 12px; border: 1px solid var(--line); border-radius: 9px; background: #fafbfc; }
|
||||||
|
.company-identifier-list strong { font-size: 10px; color: var(--blue); }
|
||||||
|
.company-identifier-list span { font-size: 12px; font-weight: 750; }
|
||||||
|
.company-identifier-list small { color: var(--muted); font-size: 9px; }
|
||||||
|
.company-advanced-link { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding: 12px 15px; border: 1px dashed #ccd4e2; border-radius: 10px; color: var(--muted); background: rgba(255,255,255,.55); font-size: 11px; }
|
||||||
|
.company-advanced-link a { color: var(--blue); font-weight: 750; text-decoration: none; }
|
||||||
|
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.company-hero { align-items: flex-start; flex-direction: column; }
|
||||||
|
.company-hero-actions { width: 100%; justify-content: space-between; }
|
||||||
|
.company-card { padding: 18px; }
|
||||||
|
.company-card-heading { align-items: flex-start; flex-direction: column; }
|
||||||
|
.company-data-grid, .company-metrics { grid-template-columns: 1fr; }
|
||||||
|
.company-area-row { align-items: flex-start; flex-direction: column; }
|
||||||
|
.company-area-row > div { width: 100%; justify-content: space-between; }
|
||||||
|
.company-doc-counts { width: 100%; }
|
||||||
|
.company-advanced-link { align-items: flex-start; flex-direction: column; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
.territory-page { display: grid; gap: 18px; }
|
||||||
|
.territory-breadcrumb { margin-bottom: 0; }
|
||||||
|
|
||||||
|
.territory-hero {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-end;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 24px;
|
||||||
|
padding: 4px 0 2px;
|
||||||
|
}
|
||||||
|
.territory-hero h1 { margin: 6px 0 5px; font-size: clamp(31px, 3.5vw, 44px); line-height: 1.02; letter-spacing: -.045em; }
|
||||||
|
.territory-hero p { margin: 0; color: var(--muted); font-size: 13px; }
|
||||||
|
.territory-hero-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||||
|
|
||||||
|
.territory-purpose-note {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 9px;
|
||||||
|
padding: 11px 13px;
|
||||||
|
border: 1px solid #dbe4f2;
|
||||||
|
border-radius: 10px;
|
||||||
|
color: #536078;
|
||||||
|
background: #f7f9fd;
|
||||||
|
font-size: 11px;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
.territory-purpose-note .icon { color: var(--blue); flex: 0 0 auto; }
|
||||||
|
|
||||||
|
.territory-tabs {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
overflow-x: auto;
|
||||||
|
padding: 0 0 1px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.territory-tabs button {
|
||||||
|
position: relative;
|
||||||
|
min-height: 43px;
|
||||||
|
padding: 9px 13px;
|
||||||
|
border: 0;
|
||||||
|
color: #566178;
|
||||||
|
background: transparent;
|
||||||
|
cursor: pointer;
|
||||||
|
white-space: nowrap;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
.territory-tabs button:hover { color: var(--ink); }
|
||||||
|
.territory-tabs button.active { color: var(--blue); }
|
||||||
|
.territory-tabs button.active::after { content: ''; position: absolute; left: 10px; right: 10px; bottom: -1px; height: 2px; border-radius: 2px; background: var(--blue); }
|
||||||
|
|
||||||
|
.territory-stack { display: grid; gap: 15px; }
|
||||||
|
.territory-card { padding: 22px; }
|
||||||
|
.territory-card-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 18px; margin-bottom: 16px; }
|
||||||
|
.territory-card-heading h2 { margin: 4px 0; }
|
||||||
|
.territory-card-heading p { max-width: 680px; margin: 0; color: var(--muted); font-size: 12px; line-height: 1.5; }
|
||||||
|
.territory-card-actions { display: flex; justify-content: flex-end; margin-top: 14px; }
|
||||||
|
|
||||||
|
.territory-data-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1px; overflow: hidden; border: 1px solid var(--line); border-radius: 11px; background: var(--line); }
|
||||||
|
.territory-data-grid > div { min-height: 74px; padding: 15px 16px; background: #fff; }
|
||||||
|
.territory-data-grid > div.wide { grid-column: 1 / -1; }
|
||||||
|
.territory-data-grid small, .territory-data-grid strong { display: block; }
|
||||||
|
.territory-data-grid small { margin-bottom: 7px; color: var(--muted); font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .04em; }
|
||||||
|
.territory-data-grid strong { font-size: 13px; font-weight: 750; line-height: 1.45; }
|
||||||
|
.territory-edit-form { display: grid; gap: 15px; }
|
||||||
|
|
||||||
|
.territory-child-list, .territory-company-list { display: grid; gap: 8px; }
|
||||||
|
.territory-child-row, .territory-company-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
min-height: 60px;
|
||||||
|
padding: 11px 13px;
|
||||||
|
border: 1px solid #e2e7ef;
|
||||||
|
border-radius: 10px;
|
||||||
|
color: inherit;
|
||||||
|
background: #fbfcfd;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.territory-child-row:hover, .territory-company-row:hover { border-color: #bfd0ee; background: #f7faff; }
|
||||||
|
.territory-child-row > span:nth-child(2), .territory-company-row > span:first-child { flex: 1; min-width: 0; }
|
||||||
|
.territory-child-row strong, .territory-child-row small, .territory-company-row strong, .territory-company-row small { display: block; }
|
||||||
|
.territory-child-row strong, .territory-company-row strong { font-size: 12px; }
|
||||||
|
.territory-child-row small, .territory-company-row small { margin-top: 4px; color: var(--muted); font-size: 10px; }
|
||||||
|
.territory-child-row > .icon:last-child, .territory-company-row > .icon:last-child { color: #8b96aa; }
|
||||||
|
|
||||||
|
.territory-metrics { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }
|
||||||
|
.territory-metrics > div { display: grid; gap: 6px; padding: 16px; border: 1px solid #e2e7ef; border-radius: 11px; background: #f8faff; }
|
||||||
|
.territory-metrics small { color: var(--muted); font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .05em; }
|
||||||
|
.territory-metrics strong { color: #173b7a; font-size: 25px; line-height: 1; letter-spacing: -.04em; }
|
||||||
|
|
||||||
|
.territory-advanced-link { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding: 12px 15px; border: 1px dashed #ccd4e2; border-radius: 10px; color: var(--muted); background: rgba(255,255,255,.55); font-size: 11px; }
|
||||||
|
.territory-advanced-link a { color: var(--blue); font-weight: 750; text-decoration: none; }
|
||||||
|
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.territory-hero { align-items: flex-start; flex-direction: column; }
|
||||||
|
.territory-hero-actions { width: 100%; }
|
||||||
|
.territory-card { padding: 18px; }
|
||||||
|
.territory-card-heading { align-items: flex-start; flex-direction: column; }
|
||||||
|
.territory-data-grid, .territory-metrics { grid-template-columns: 1fr; }
|
||||||
|
.territory-data-grid > div.wide { grid-column: auto; }
|
||||||
|
.territory-child-row { align-items: flex-start; flex-wrap: wrap; }
|
||||||
|
.territory-child-row .status-badge { margin-left: 44px; }
|
||||||
|
.territory-advanced-link { align-items: flex-start; flex-direction: column; }
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user