Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47cd985931 | ||
|
|
da7c1ddb55 | ||
|
|
a2ec846721 | ||
|
|
9eef156197 | ||
|
|
08f164a209 | ||
|
|
23450bb6d0 | ||
|
|
20ccba5292 | ||
|
|
c0a5367920 | ||
|
|
ff30462259 | ||
|
|
975f9ee13e | ||
|
|
39dcd6bd4a | ||
|
|
ffeae96530 | ||
|
|
9b12144052 | ||
|
|
becf9fc050 | ||
|
|
7fe59bccd2 | ||
|
|
103ecf2fae | ||
|
|
23880521d9 | ||
|
|
637c28dc2f | ||
|
|
fc0c62c70a |
@@ -1,5 +1,5 @@
|
||||
name: Android CI / RC
|
||||
# F6.1 presentation barrier: lint + real tests + debug artifact + release compile.
|
||||
# F6.7 field closing barrier: lint + real tests + debug artifact + release compile.
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -43,6 +43,8 @@ jobs:
|
||||
|
||||
- name: Android SDK
|
||||
uses: android-actions/setup-android@v3
|
||||
with:
|
||||
packages: platform-tools
|
||||
|
||||
- name: Android API 36
|
||||
run: sdkmanager 'platforms;android-36' 'build-tools;36.0.0'
|
||||
@@ -109,7 +111,7 @@ jobs:
|
||||
cp android-app/app/build/outputs/apk/debug/app-debug.apk "$apk"
|
||||
sha256sum "$apk" > "${apk}.sha256"
|
||||
{
|
||||
echo "phase=F6.1"
|
||||
echo "phase=F6.7"
|
||||
echo "version=$version"
|
||||
echo "versionCode=$code"
|
||||
echo "commit=$GITHUB_SHA"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Checklist final Android 0.19.2
|
||||
# Checklist final Android 0.19.3
|
||||
|
||||
La candidata sólo se promueve si el mismo SHA cumple:
|
||||
|
||||
@@ -8,6 +8,10 @@ La candidata sólo se promueve si el mismo SHA cumple:
|
||||
- exigir GPS + fotografía para Inventario nacido en campo antes de Hallazgos;
|
||||
- registrar Hallazgos sobre el elemento seleccionado;
|
||||
- al cerrar el contenido, exigir Urgente/No urgente, persistir esa decisión y mostrar **Pendiente de firma**;
|
||||
- exigir por cada Acta los datos del **Representante de la empresa**: nombres y apellidos, DNI, cargo/función y email;
|
||||
- permitir precargar esos datos desde el Acta anterior de la misma Inspección, pero exigir confirmación y firma nueva en cada Acta;
|
||||
- resolver por Acta **firma en conformidad**, **firma en disconformidad con motivo** o **negativa a firmar con motivo**;
|
||||
- verificar que la urgencia existe sólo a nivel **Acta** y nunca a nivel Hallazgo;
|
||||
- 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;
|
||||
|
||||
+25
-8
@@ -1,19 +1,31 @@
|
||||
# DH Inspección Android · release final de campo 0.19.2
|
||||
# DH Inspección Android · release final de campo 0.19.9
|
||||
|
||||
## Candidata vigente
|
||||
|
||||
- Fase funcional: **Flujo final de campo · Inspección → Acta → Hallazgos → Firma**.
|
||||
- `versionName`: **0.19.2**.
|
||||
- `versionCode`: **30**.
|
||||
- `versionName`: **0.19.9**.
|
||||
- `versionCode`: **37**.
|
||||
- Application ID release: `com.korexlabs.dhinspeccion`.
|
||||
- Application ID debug/QA: `com.korexlabs.dhinspeccion.debug`.
|
||||
- API: `https://dhv2.korexlabs.com/api/v3/`.
|
||||
- Servidor compatible de esta candidata: **API 0.29.0-7 / WEB 0.23.0-4**.
|
||||
|
||||
La variante debug es independiente de la app productiva y puede instalarse para QA/presentación sin sobrescribir una instalación release histórica.
|
||||
|
||||
### Ajustes 0.19.9
|
||||
|
||||
- Corrige el cierre de Actas evitando `NaN` en el versionado de LOCKED/SEALED.
|
||||
- El cierre pasa a **Para firmar**; la APK captura sólo la manifestación/firma del acompañante.
|
||||
- La firma del Inspector se guarda una vez en Mi perfil y se copia de forma inmutable al sellar cada Acta.
|
||||
- Elimina la tarjeta duplicada del Acta seleccionada y simplifica la jerarquía visual inspirada en la referencia Figma.
|
||||
|
||||
- El encabezado de **Mis inspecciones** separa las acciones para que **Salir** nunca se comprima ni se corte en pantallas angostas.
|
||||
- El alta de Hallazgos corrige la captura de versión que podía transformar el número en `NaN` después del INSERT y devolver error 500.
|
||||
- Un Hallazgo admite **múltiples fotografías con GPS**; después de cada captura queda disponible **Agregar otra foto con GPS** y se muestra el contador.
|
||||
|
||||
## Procedimiento operativo validado
|
||||
|
||||
La APK 0.19.2 fija como recorrido principal de campo:
|
||||
La APK 0.19.9 fija como recorrido principal de campo:
|
||||
|
||||
1. **Iniciar Inspección**. Al iniciarla se habilita el circuito de **Actas y Hallazgos**; Inventario no es una acción independiente de la Inspección.
|
||||
2. **Crear o abrir un Acta**. Puede haber varias Actas dentro de una misma Inspección, pero sólo una puede permanecer en elaboración al mismo tiempo. La urgencia todavía no se define.
|
||||
@@ -21,9 +33,10 @@ La APK 0.19.2 fija como recorrido principal de campo:
|
||||
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 elige **Urgente / No urgente** y luego se usa **Cerrar Acta y dejar pendiente de firma**. La urgencia queda fijada con el cierre; desde ese momento el contenido queda inmutable y el estado visible es **Pendiente de firma**.
|
||||
8. La firma del Inspector y la manifestación/firma o negativa de la empresa completan el Acta, que pasa a **Firmada y cerrada**.
|
||||
9. La Inspección sólo puede cerrarse cuando todas sus Actas no canceladas están firmadas y cerradas.
|
||||
7. Antes del cierre se identifican, para esa Acta, los datos del **Representante de la empresa** que acompañó el recorrido: nombres y apellidos, DNI, cargo/función y email. Si coincide con el Acta anterior, la APK puede precargarlos, pero deben confirmarse nuevamente.
|
||||
8. Al terminar el contenido del Acta se elige **Urgente / No urgente** y luego se usa **Cerrar contenido y pasar a firma**. La urgencia pertenece al Acta completa, nunca a cada Hallazgo; desde ese momento el contenido queda inmutable y el estado visible es **Para firmar**.
|
||||
9. En **Para firmar**, el acompañante de la empresa registra su manifestación: **conformidad**, **disconformidad con motivo obligatorio**, **negativa a firmar con motivo obligatorio** o **ausencia documentada**. La firma del Inspector no se dibuja en la tablet: se guarda una sola vez desde **Mi perfil** del Dashboard y el servidor copia esa firma de forma inmutable a cada Acta al usar **Aplicar mi firma y cerrar Acta**.
|
||||
10. La Inspección sólo puede cerrarse cuando todas sus Actas no canceladas están firmadas y cerradas.
|
||||
|
||||
La nomenclatura técnica interna de API (`DRAFT`, `LOCKED`, `SEALED`, etc.) no se muestra al inspector: la interfaz usa textos operativos en castellano.
|
||||
|
||||
@@ -49,6 +62,10 @@ Además de lo anterior requiere elegir primero la **Instalación padre**. El bus
|
||||
|
||||
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.
|
||||
|
||||
## Alta de Hallazgos
|
||||
|
||||
El alta de Hallazgos usa un selector desplegable con búsqueda por nombre. La pantalla muestra sólo la información necesaria para decidir, mantiene **Otro / No está en la lista** como salida manual y evita exponer códigos o leyendas internas del catálogo. La fecha de corrección no se solicita al inspector al crear un Hallazgo; los plazos administrativos se gestionan fuera de este alta de campo. Los campos de carga son compactos y el teclado avanza con **Siguiente** entre ellos.
|
||||
|
||||
## Actas y firma
|
||||
|
||||
La terminología visible se simplifica:
|
||||
@@ -117,7 +134,7 @@ Esta candidata requiere conexión. No implementa trabajo offline ni cola persist
|
||||
- Se agregan siete pruebas para coordenadas y valores técnicos.
|
||||
|
||||
|
||||
## Revisión 0.19.2 · flujo conceptual corregido
|
||||
## Revisión 0.19.3 · flujo conceptual corregido
|
||||
|
||||
- Se elimina **Inventario de campo** como acción independiente de la pantalla de Inspección.
|
||||
- El alta o selección de Inventario existe únicamente dentro de **Agregar Hallazgo**.
|
||||
|
||||
@@ -12,8 +12,8 @@ android {
|
||||
applicationId = "com.korexlabs.dhinspeccion"
|
||||
minSdk = 26
|
||||
targetSdk = 36
|
||||
versionCode = 30
|
||||
versionName = "0.19.2"
|
||||
versionCode = 37
|
||||
versionName = "0.19.9"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
vectorDrawables.useSupportLibrary = true
|
||||
|
||||
@@ -244,7 +244,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
return
|
||||
}
|
||||
if (type.familyRequired && familyId == null) {
|
||||
error = "Elegí una clasificación técnica o la opción Otro / no catalogado."
|
||||
error = "Elegí el Tipo de instalación o subinstalación correspondiente."
|
||||
return
|
||||
}
|
||||
launchBusy(mutation = true) {
|
||||
@@ -316,7 +316,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
)
|
||||
selectedFieldAsset = selectedFieldAsset?.copy(capture = response.capture)
|
||||
notice = if (response.capture.readyForFinding) {
|
||||
"Captura completa: GPS y fotografía registrados."
|
||||
"Inventario listo: ubicación y foto registradas."
|
||||
} else {
|
||||
"Fotografía registrada."
|
||||
}
|
||||
@@ -353,7 +353,6 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
customLegalBasis: String?,
|
||||
description: String,
|
||||
severity: Int?,
|
||||
correctionDueOn: String?,
|
||||
) {
|
||||
val visitId = visit?.id ?: return
|
||||
val assetId = selectedFieldAsset?.asset?.id ?: return
|
||||
@@ -386,7 +385,6 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
customLegalBasis = customLegalBasis?.trim()?.takeIf { it.isNotBlank() },
|
||||
description = description.trim(),
|
||||
severity = severity,
|
||||
correctionDueOn = correctionDueOn?.trim()?.takeIf { it.isNotBlank() },
|
||||
),
|
||||
)
|
||||
lastCreatedFinding = response.finding
|
||||
@@ -433,8 +431,10 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
phone: String?,
|
||||
) {
|
||||
val actId = selectedAct?.id ?: return
|
||||
if (fullName.isBlank() || documentNumber.isBlank() || position.isBlank()) {
|
||||
error = "Completá nombre, documento y cargo del responsable de la empresa."
|
||||
val normalizedEmail = email?.trim().orEmpty()
|
||||
val emailValid = Regex("""^[^\s@]+@[^\s@]+\.[^\s@]+$""").matches(normalizedEmail)
|
||||
if (fullName.isBlank() || documentNumber.isBlank() || position.isBlank() || !emailValid) {
|
||||
error = "Completá nombres y apellidos, DNI, cargo/función y un email válido del representante de la empresa."
|
||||
return
|
||||
}
|
||||
launchBusy(mutation = true) {
|
||||
@@ -446,11 +446,11 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
documentType = documentType,
|
||||
documentNumber = documentNumber.trim(),
|
||||
position = position.trim(),
|
||||
email = email?.trim()?.takeIf { it.isNotBlank() },
|
||||
email = normalizedEmail.lowercase(),
|
||||
phone = phone?.trim()?.takeIf { it.isNotBlank() },
|
||||
),
|
||||
)
|
||||
notice = "Responsable de empresa registrado para el Acta."
|
||||
notice = "Representante de la empresa registrado para esta Acta."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -468,7 +468,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
absenceReason = reason.trim(),
|
||||
),
|
||||
)
|
||||
notice = "Ausencia del responsable registrada. La manifestación de empresa quedará pendiente y deberá resolverse antes de firmar y cerrar el Acta."
|
||||
notice = "Ausencia del representante registrada. La manifestación de la empresa deberá resolverse antes de firmar y cerrar el Acta."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,7 +482,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
actClosure = actsRepository.lock(actId, urgency)
|
||||
refreshSelectedActInternal(actId)
|
||||
val urgencyLabel = if (urgency == "URGENT") "urgente" else "no urgente"
|
||||
notice = "Acta cerrada como $urgencyLabel y pendiente de firma. Su contenido quedó inmutable."
|
||||
notice = "Acta cerrada como $urgencyLabel. La urgencia quedó definida sobre el Acta y su contenido quedó inmutable, pendiente de firmas."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -517,9 +517,9 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
actId, png, latitude, longitude, accuracyM, manifestation, statement,
|
||||
)
|
||||
notice = if (manifestation == "DISSENT") {
|
||||
"Firma de empresa registrada con disidencia."
|
||||
"Firma del representante registrada en disconformidad."
|
||||
} else {
|
||||
"Firma de empresa registrada."
|
||||
"Firma del representante de la empresa registrada."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -561,8 +561,10 @@ class DhRepository(context: Context) {
|
||||
if (error is HttpException) {
|
||||
val body = runCatching { error.response()?.errorBody()?.string() }.getOrNull()
|
||||
val message = runCatching { JSONObject(body.orEmpty()).optString("message") }.getOrNull()
|
||||
if (message == "Error interno") return "No se pudo completar la operación. Intentá nuevamente."
|
||||
if (!message.isNullOrBlank()) return message
|
||||
return "Error HTTP ${error.code()}"
|
||||
if (error.code() >= 500) return "No se pudo completar la operación. Intentá nuevamente."
|
||||
return "No se pudo procesar la solicitud (${error.code()})."
|
||||
}
|
||||
return error.message ?: "Ocurrió un error inesperado"
|
||||
}
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.korexlabs.dhinspeccion.data
|
||||
|
||||
/** Builds the API payload using definition IDs while the form keeps stable field codes. */
|
||||
internal fun fieldAttributePayload(
|
||||
definitions: List<FieldAttributeDefinition>,
|
||||
valuesByCode: Map<String, String>,
|
||||
): Map<String, Any?> = definitions.mapNotNull { definition ->
|
||||
val raw = valuesByCode[definition.code]?.trim().orEmpty()
|
||||
if (raw.isBlank()) return@mapNotNull null
|
||||
definition.id to coerceFieldAttribute(definition, raw)
|
||||
}.toMap()
|
||||
|
||||
private fun coerceFieldAttribute(definition: FieldAttributeDefinition, raw: String): Any =
|
||||
when (definition.dataType.uppercase()) {
|
||||
"INTEGER", "INT" -> raw.toLongOrNull() ?: raw
|
||||
"NUMBER", "DECIMAL", "FLOAT", "DOUBLE" -> raw.replace(',', '.').toDoubleOrNull() ?: raw
|
||||
"BOOLEAN", "BOOL" -> raw.lowercase() in setOf("true", "1", "si", "sí", "yes")
|
||||
else -> raw
|
||||
}
|
||||
@@ -113,7 +113,6 @@ data class CreateFieldFindingRequest(
|
||||
val customLegalBasis: String? = null,
|
||||
val description: String,
|
||||
val severity: Int? = null,
|
||||
val correctionDueOn: String? = null,
|
||||
)
|
||||
|
||||
data class FieldFindingCreateResponse(
|
||||
|
||||
@@ -188,6 +188,7 @@ data class MobileActClosure(
|
||||
val act: MobileActClosureHeader,
|
||||
val visit: MobileVisitClosureHeader,
|
||||
val responsible: MobileResponsible? = null,
|
||||
val representativeSuggestion: MobileResponsible? = null,
|
||||
val closure: MobileClosureRecord? = null,
|
||||
val signatures: List<MobileSignature> = emptyList(),
|
||||
val consents: MobileClosureConsents = MobileClosureConsents(),
|
||||
|
||||
@@ -60,6 +60,7 @@ import com.korexlabs.dhinspeccion.MainViewModel
|
||||
import com.korexlabs.dhinspeccion.data.FieldAttributeDefinition
|
||||
import com.korexlabs.dhinspeccion.data.FieldInventoryItem
|
||||
import com.korexlabs.dhinspeccion.data.FieldType
|
||||
import com.korexlabs.dhinspeccion.data.fieldAttributePayload
|
||||
import com.korexlabs.dhinspeccion.data.VisitDetail
|
||||
import com.korexlabs.dhinspeccion.data.VisitSummary
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -521,18 +522,7 @@ private fun InventoryCard(item: FieldInventoryItem, canModify: Boolean, onSelect
|
||||
}
|
||||
|
||||
private fun buildAttributes(type: FieldType, values: Map<String, String>): Map<String, Any?> =
|
||||
type.attributes.mapNotNull { definition ->
|
||||
val raw = values[definition.code]?.trim().orEmpty()
|
||||
if (raw.isBlank()) return@mapNotNull null
|
||||
definition.code to coerceAttribute(definition, raw)
|
||||
}.toMap()
|
||||
|
||||
private fun coerceAttribute(definition: FieldAttributeDefinition, raw: String): Any = when (definition.dataType.uppercase()) {
|
||||
"INTEGER", "INT" -> raw.toLongOrNull() ?: raw
|
||||
"NUMBER", "DECIMAL", "FLOAT", "DOUBLE" -> raw.replace(',', '.').toDoubleOrNull() ?: raw
|
||||
"BOOLEAN", "BOOL" -> raw.lowercase() in setOf("true", "1", "si", "sí", "yes")
|
||||
else -> raw
|
||||
}
|
||||
fieldAttributePayload(type.attributes, values)
|
||||
|
||||
private fun hasPermission(context: Context, permission: String): Boolean =
|
||||
ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
@@ -56,6 +56,7 @@ import com.korexlabs.dhinspeccion.MainViewModel
|
||||
import com.korexlabs.dhinspeccion.data.FieldAttributeDefinition
|
||||
import com.korexlabs.dhinspeccion.data.FieldInventoryItem
|
||||
import com.korexlabs.dhinspeccion.data.FieldType
|
||||
import com.korexlabs.dhinspeccion.data.fieldAttributePayload
|
||||
import com.korexlabs.dhinspeccion.data.VisitDetail
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
@@ -693,11 +694,11 @@ private fun DynamicFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit
|
||||
}
|
||||
|
||||
if (selectedType?.familyRequired == true) {
|
||||
Text("Clasificación técnica *", fontWeight = FontWeight.Bold)
|
||||
Text("Tipo de instalación *", fontWeight = FontWeight.Bold)
|
||||
OutlinedTextField(
|
||||
value = familySearch,
|
||||
onValueChange = { familySearch = it },
|
||||
label = { Text("Buscar clasificación") },
|
||||
label = { Text("Buscar tipo de instalación") },
|
||||
supportingText = { Text("${filteredFamilies.size} opciones compatibles") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
@@ -906,18 +907,7 @@ private fun dynamicStatusLabel(status: String): String = when (status) {
|
||||
}
|
||||
|
||||
private fun buildDynamicAttributes(type: FieldType, values: Map<String, String>): Map<String, Any?> =
|
||||
type.attributes.mapNotNull { definition ->
|
||||
val raw = values[definition.code]?.trim().orEmpty()
|
||||
if (raw.isBlank()) return@mapNotNull null
|
||||
definition.code to coerceDynamicAttribute(definition, raw)
|
||||
}.toMap()
|
||||
|
||||
private fun coerceDynamicAttribute(definition: FieldAttributeDefinition, raw: String): Any = when (definition.dataType.uppercase()) {
|
||||
"INTEGER", "INT" -> raw.toLongOrNull() ?: raw
|
||||
"NUMBER", "DECIMAL", "FLOAT", "DOUBLE" -> raw.replace(',', '.').toDoubleOrNull() ?: raw
|
||||
"BOOLEAN", "BOOL" -> raw.lowercase() in setOf("true", "1", "si", "sí", "yes")
|
||||
else -> raw
|
||||
}
|
||||
fieldAttributePayload(type.attributes, values)
|
||||
|
||||
private fun dynamicHasPermission(context: Context, permission: String): Boolean =
|
||||
ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
@@ -57,6 +57,7 @@ import com.korexlabs.dhinspeccion.MainViewModel
|
||||
import com.korexlabs.dhinspeccion.data.FieldAttributeDefinition
|
||||
import com.korexlabs.dhinspeccion.data.FieldInventoryItem
|
||||
import com.korexlabs.dhinspeccion.data.FieldType
|
||||
import com.korexlabs.dhinspeccion.data.fieldAttributePayload
|
||||
import com.korexlabs.dhinspeccion.data.VisitDetail
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
@@ -720,18 +721,7 @@ private fun statusLabel(status: String): String = when (status) {
|
||||
}
|
||||
|
||||
private fun buildF3Attributes(type: FieldType, values: Map<String, String>): Map<String, Any?> =
|
||||
type.attributes.mapNotNull { definition ->
|
||||
val raw = values[definition.code]?.trim().orEmpty()
|
||||
if (raw.isBlank()) return@mapNotNull null
|
||||
definition.code to coerceF3Attribute(definition, raw)
|
||||
}.toMap()
|
||||
|
||||
private fun coerceF3Attribute(definition: FieldAttributeDefinition, raw: String): Any = when (definition.dataType.uppercase()) {
|
||||
"INTEGER", "INT" -> raw.toLongOrNull() ?: raw
|
||||
"NUMBER", "DECIMAL", "FLOAT", "DOUBLE" -> raw.replace(',', '.').toDoubleOrNull() ?: raw
|
||||
"BOOLEAN", "BOOL" -> raw.lowercase() in setOf("true", "1", "si", "sí", "yes")
|
||||
else -> raw
|
||||
}
|
||||
fieldAttributePayload(type.attributes, values)
|
||||
|
||||
private fun f3HasPermission(context: Context, permission: String): Boolean =
|
||||
ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
+116
-64
@@ -7,21 +7,27 @@ import android.net.Uri
|
||||
import android.os.Environment
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ExposedDropdownMenuBox
|
||||
import androidx.compose.material3.ExposedDropdownMenuDefaults
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.MenuAnchorType
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
@@ -34,8 +40,12 @@ import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusDirection
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
@@ -60,20 +70,23 @@ private data class FindingGeoSnapshot(
|
||||
val accuracyM: Double?,
|
||||
)
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun FieldFindingScreen(model: MainViewModel) {
|
||||
val options = model.fieldFindingOptions ?: return
|
||||
val asset = model.selectedFieldAsset?.asset ?: return
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val focusManager = LocalFocusManager.current
|
||||
val keyboard = LocalSoftwareKeyboardController.current
|
||||
var search by rememberSaveable(asset.id) { mutableStateOf("") }
|
||||
var catalogExpanded by rememberSaveable(asset.id) { mutableStateOf(false) }
|
||||
var selectedCatalogId by rememberSaveable(asset.id) { mutableStateOf<String?>(null) }
|
||||
var other by rememberSaveable(asset.id) { mutableStateOf(false) }
|
||||
var customTitle by rememberSaveable(asset.id) { mutableStateOf("") }
|
||||
var customLegalBasis by rememberSaveable(asset.id) { mutableStateOf("") }
|
||||
var description by rememberSaveable(asset.id) { mutableStateOf("") }
|
||||
var severityText by rememberSaveable(asset.id) { mutableStateOf("") }
|
||||
var correctionDueOn by rememberSaveable(asset.id) { mutableStateOf("") }
|
||||
|
||||
var localError by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var requestedFindingId by remember { mutableStateOf<String?>(null) }
|
||||
@@ -164,8 +177,8 @@ fun FieldFindingScreen(model: MainViewModel) {
|
||||
customLegalBasis = ""
|
||||
description = ""
|
||||
severityText = ""
|
||||
correctionDueOn = ""
|
||||
search = ""
|
||||
catalogExpanded = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,15 +193,15 @@ fun FieldFindingScreen(model: MainViewModel) {
|
||||
OutlinedButton(onClick = { model.clearFindingFlow() }, enabled = !model.busy) {
|
||||
Text("Volver")
|
||||
}
|
||||
Text("Hallazgo de campo", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
|
||||
Text("Nuevo Hallazgo", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(asset.name, fontWeight = FontWeight.Bold)
|
||||
Text("${asset.code} · Acta ${options.act.code}", style = MaterialTheme.typography.bodySmall)
|
||||
Text("${asset.code} · ${options.act.code}", style = MaterialTheme.typography.bodySmall)
|
||||
Text(
|
||||
"GPS + foto del Inventario: ${if (options.capture.readyForFinding) "completo" else "pendiente"}",
|
||||
if (options.capture.readyForFinding) "Inventario listo para registrar Hallazgos" else "Completá GPS y foto antes de continuar",
|
||||
color = if (options.capture.readyForFinding) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
@@ -225,87 +238,123 @@ fun FieldFindingScreen(model: MainViewModel) {
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
val photoCount = evidence.count { it.kind == "PHOTO" }
|
||||
Button(
|
||||
onClick = { requestPhoto(finding.id) },
|
||||
enabled = !model.busy,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text("Tomar foto con GPS")
|
||||
Text(if (photoCount == 0) "Agregar foto con GPS" else "Agregar otra foto con GPS")
|
||||
}
|
||||
Text(
|
||||
if (photoCount == 0) "Podés adjuntar una o varias fotos." else "$photoCount foto${if (photoCount == 1) "" else "s"} adjunta${if (photoCount == 1) "" else "s"}. Podés seguir agregando.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
HorizontalDivider()
|
||||
}
|
||||
|
||||
Text("1. Elegí el tipo de Hallazgo", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text("1. Tipo de Hallazgo", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
if (!options.catalog.typeConfigured) {
|
||||
Text(
|
||||
options.catalog.configurationReason
|
||||
?: "Este tipo de Inventario todavía no tiene un catálogo contextual configurado. Podés usar OTROS.",
|
||||
color = MaterialTheme.colorScheme.secondary,
|
||||
"No hay tipos sugeridos para este Inventario. Elegí Otro para cargarlo manualmente.",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
OutlinedTextField(
|
||||
value = search,
|
||||
onValueChange = { search = it },
|
||||
label = { Text("Buscar en catálogo") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
)
|
||||
|
||||
filtered.forEach { item ->
|
||||
val chosen = !other && selectedCatalogId == item.id
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth().clickable {
|
||||
selectedCatalogId = item.id
|
||||
other = false
|
||||
severityText = item.suggestedSeverity?.toString().orEmpty()
|
||||
},
|
||||
colors = if (chosen) {
|
||||
CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer)
|
||||
} else {
|
||||
CardDefaults.cardColors()
|
||||
ExposedDropdownMenuBox(
|
||||
expanded = catalogExpanded && !model.busy,
|
||||
onExpandedChange = {
|
||||
if (!model.busy) {
|
||||
catalogExpanded = it
|
||||
if (it) search = ""
|
||||
}
|
||||
},
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = if (catalogExpanded) search else when {
|
||||
other -> "Otro / No está en la lista"
|
||||
selected != null -> selected.title
|
||||
else -> ""
|
||||
},
|
||||
onValueChange = { search = it; catalogExpanded = true },
|
||||
label = { Text("Tipo de Hallazgo *") },
|
||||
placeholder = { Text("Buscar o seleccionar") },
|
||||
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = catalogExpanded) },
|
||||
modifier = Modifier.fillMaxWidth().menuAnchor(MenuAnchorType.PrimaryEditable),
|
||||
enabled = !model.busy,
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
|
||||
keyboardActions = KeyboardActions(onNext = {
|
||||
catalogExpanded = false
|
||||
focusManager.moveFocus(FocusDirection.Down)
|
||||
}),
|
||||
)
|
||||
ExposedDropdownMenu(
|
||||
expanded = catalogExpanded && !model.busy,
|
||||
onDismissRequest = { catalogExpanded = false; search = "" },
|
||||
modifier = Modifier.heightIn(max = 320.dp),
|
||||
) {
|
||||
Column(Modifier.padding(10.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text(if (chosen) "✓ ${item.title}" else item.title, fontWeight = FontWeight.SemiBold)
|
||||
Text(
|
||||
listOfNotNull(item.categoryName, item.code, item.suggestedSeverity?.let { "Gravedad sugerida $it" })
|
||||
.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
filtered.forEach { item ->
|
||||
DropdownMenuItem(
|
||||
text = {
|
||||
Column {
|
||||
Text(item.title, fontWeight = FontWeight.SemiBold)
|
||||
item.suggestedSeverity?.let {
|
||||
Text("Gravedad sugerida: $it/10", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
},
|
||||
onClick = {
|
||||
selectedCatalogId = item.id
|
||||
other = false
|
||||
severityText = item.suggestedSeverity?.toString().orEmpty()
|
||||
catalogExpanded = false
|
||||
search = ""
|
||||
keyboard?.hide()
|
||||
focusManager.moveFocus(FocusDirection.Down)
|
||||
},
|
||||
)
|
||||
}
|
||||
DropdownMenuItem(
|
||||
text = { Text("Otro / No está en la lista", fontWeight = FontWeight.SemiBold) },
|
||||
onClick = {
|
||||
other = true
|
||||
selectedCatalogId = null
|
||||
severityText = ""
|
||||
catalogExpanded = false
|
||||
search = ""
|
||||
keyboard?.hide()
|
||||
focusManager.moveFocus(FocusDirection.Down)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
other = true
|
||||
selectedCatalogId = null
|
||||
severityText = ""
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(if (other) "✓ OTROS · Hallazgo no catalogado" else "OTROS · No está en el catálogo")
|
||||
}
|
||||
if (other) {
|
||||
options.catalog.other.help?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
Text("Cargá un nombre claro para identificar el Hallazgo.", style = MaterialTheme.typography.bodySmall)
|
||||
OutlinedTextField(
|
||||
value = customTitle,
|
||||
onValueChange = { customTitle = it },
|
||||
label = { Text("Título del nuevo Hallazgo *") },
|
||||
label = { Text("Nombre del Hallazgo *") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
|
||||
keyboardActions = KeyboardActions(onNext = { focusManager.moveFocus(FocusDirection.Down) }),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = customLegalBasis,
|
||||
onValueChange = { customLegalBasis = it },
|
||||
label = { Text("Base legal / normativa (opcional)") },
|
||||
label = { Text("Normativa (opcional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
|
||||
keyboardActions = KeyboardActions(onNext = { focusManager.moveFocus(FocusDirection.Down) }),
|
||||
)
|
||||
}
|
||||
|
||||
Text("2. Describí lo observado", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text("2. Qué observaste", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
selected?.let {
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(10.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
@@ -318,23 +367,21 @@ fun FieldFindingScreen(model: MainViewModel) {
|
||||
OutlinedTextField(
|
||||
value = description,
|
||||
onValueChange = { description = it },
|
||||
label = { Text("Descripción del Hallazgo *") },
|
||||
label = { Text("Qué observaste *") },
|
||||
placeholder = { Text("Describí brevemente el problema") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
minLines = 3,
|
||||
maxLines = 6,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
|
||||
keyboardActions = KeyboardActions(onNext = { focusManager.moveFocus(FocusDirection.Down) }),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = severityText,
|
||||
onValueChange = { value -> severityText = value.filter(Char::isDigit).take(2) },
|
||||
label = { Text("Gravedad 1 a 10") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
singleLine = true,
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = correctionDueOn,
|
||||
onValueChange = { correctionDueOn = it },
|
||||
label = { Text("Fecha de corrección AAAA-MM-DD (opcional)") },
|
||||
label = { Text("Gravedad (1 a 10, opcional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done),
|
||||
keyboardActions = KeyboardActions(onDone = { keyboard?.hide(); focusManager.clearFocus() }),
|
||||
singleLine = true,
|
||||
)
|
||||
|
||||
@@ -348,7 +395,6 @@ fun FieldFindingScreen(model: MainViewModel) {
|
||||
customLegalBasis = if (other) customLegalBasis else null,
|
||||
description = description,
|
||||
severity = severity,
|
||||
correctionDueOn = correctionDueOn,
|
||||
)
|
||||
},
|
||||
enabled = choiceReady && description.isNotBlank() && (severity == null || severity in 1..10) && !model.busy,
|
||||
@@ -365,13 +411,19 @@ fun FieldFindingScreen(model: MainViewModel) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Text("Hallazgo registrado", fontWeight = FontWeight.Bold)
|
||||
Text("${finding.code} · ${finding.title}")
|
||||
val createdEvidence = model.fieldFindingEvidence[finding.id].orEmpty()
|
||||
val createdPhotoCount = createdEvidence.count { it.kind == "PHOTO" }
|
||||
Button(
|
||||
onClick = { requestPhoto(finding.id) },
|
||||
enabled = !model.busy,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text("Tomar foto con GPS")
|
||||
Text(if (createdPhotoCount == 0) "Agregar foto con GPS" else "Agregar otra foto con GPS")
|
||||
}
|
||||
Text(
|
||||
if (createdPhotoCount == 0) "Podés adjuntar todas las fotos que necesites." else "Fotos adjuntas: $createdPhotoCount. Podés seguir agregando.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Text("También podés registrar otro Hallazgo sobre el mismo Inventario.", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,30 +57,31 @@ fun MobileActsScreen(
|
||||
val visit = model.visit ?: return
|
||||
val selected = model.selectedAct
|
||||
val closure = model.actClosure
|
||||
val representativeSeed = closure?.responsible ?: closure?.representativeSuggestion
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
var closingUrgency by rememberSaveable(selected?.id) { mutableStateOf("") }
|
||||
var attendance by rememberSaveable(selected?.id) {
|
||||
mutableStateOf(closure?.responsible?.attendanceStatus ?: "PRESENT")
|
||||
mutableStateOf(representativeSeed?.attendanceStatus ?: "PRESENT")
|
||||
}
|
||||
var fullName by rememberSaveable(selected?.id) {
|
||||
mutableStateOf(closure?.responsible?.fullName.orEmpty())
|
||||
mutableStateOf(representativeSeed?.fullName.orEmpty())
|
||||
}
|
||||
var documentType by rememberSaveable(selected?.id) {
|
||||
mutableStateOf(closure?.responsible?.documentType ?: "DNI")
|
||||
mutableStateOf("DNI")
|
||||
}
|
||||
var documentNumber by rememberSaveable(selected?.id) {
|
||||
mutableStateOf(closure?.responsible?.documentNumber.orEmpty())
|
||||
mutableStateOf(representativeSeed?.documentNumber.orEmpty())
|
||||
}
|
||||
var position by rememberSaveable(selected?.id) {
|
||||
mutableStateOf(closure?.responsible?.position.orEmpty())
|
||||
mutableStateOf(representativeSeed?.position.orEmpty())
|
||||
}
|
||||
var email by rememberSaveable(selected?.id) {
|
||||
mutableStateOf(closure?.responsible?.email.orEmpty())
|
||||
mutableStateOf(representativeSeed?.email.orEmpty())
|
||||
}
|
||||
var phone by rememberSaveable(selected?.id) {
|
||||
mutableStateOf(closure?.responsible?.phone.orEmpty())
|
||||
mutableStateOf(representativeSeed?.phone.orEmpty())
|
||||
}
|
||||
var absenceReason by rememberSaveable(selected?.id) {
|
||||
mutableStateOf(closure?.responsible?.absenceReason.orEmpty())
|
||||
@@ -91,26 +92,17 @@ fun MobileActsScreen(
|
||||
|
||||
LaunchedEffect(visit.id) { model.reloadActs() }
|
||||
|
||||
fun signWithGeo(file: File, company: Boolean) {
|
||||
fun signCompanyWithGeo(file: File) {
|
||||
scope.launch {
|
||||
val geo = runCatching { currentActSignatureGeo(context) }.getOrNull()
|
||||
if (company) {
|
||||
model.signSelectedActAsCompany(
|
||||
png = file,
|
||||
latitude = geo?.latitude,
|
||||
longitude = geo?.longitude,
|
||||
accuracyM = geo?.accuracyM,
|
||||
manifestation = manifestation,
|
||||
statement = dissentStatement.takeIf { manifestation == "DISSENT" },
|
||||
)
|
||||
} else {
|
||||
model.signSelectedActAsInspector(
|
||||
png = file,
|
||||
latitude = geo?.latitude,
|
||||
longitude = geo?.longitude,
|
||||
accuracyM = geo?.accuracyM,
|
||||
)
|
||||
}
|
||||
model.signSelectedActAsCompany(
|
||||
png = file,
|
||||
latitude = geo?.latitude,
|
||||
longitude = geo?.longitude,
|
||||
accuracyM = geo?.accuracyM,
|
||||
manifestation = manifestation,
|
||||
statement = dissentStatement.takeIf { manifestation == "DISSENT" },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,28 +179,6 @@ fun MobileActsScreen(
|
||||
}
|
||||
|
||||
if (selected != null) {
|
||||
HorizontalDivider()
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||
Text(selected.code, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(actStatusLabel(selected.status))
|
||||
Text(
|
||||
when (selected.urgency) {
|
||||
"URGENT" -> "Urgencia: Urgente"
|
||||
"NON_URGENT" -> "Urgencia: No urgente"
|
||||
else -> "Urgencia: se define al cerrar el Acta"
|
||||
},
|
||||
)
|
||||
Text("${selected.findingCount} Hallazgo${if (selected.findingCount == 1) "" else "s"} · ${selected.assetCount} elemento${if (selected.assetCount == 1) "" else "s"} de Inventario")
|
||||
selected.deadlineAt?.let { Text("Vencimiento calculado: $it", style = MaterialTheme.typography.bodySmall) }
|
||||
if (selected.deadlineAt == null && selected.deadlineBasis == "GEDO_DATE") {
|
||||
Text("Vencimiento pendiente de fecha GEDO.", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
selected.lockedSha256?.let { Text("Hash bloqueado: $it", style = MaterialTheme.typography.bodySmall) }
|
||||
selected.closureSha256?.let { Text("Hash sellado: $it", style = MaterialTheme.typography.bodySmall) }
|
||||
}
|
||||
}
|
||||
|
||||
when (selected.status) {
|
||||
"DRAFT" -> {
|
||||
Card(
|
||||
@@ -225,29 +195,26 @@ fun MobileActsScreen(
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Text("Responsable de la empresa", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text("Representante de la empresa", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
AssistChip(onClick = { attendance = "PRESENT" }, label = { Text(if (attendance == "PRESENT") "✓ Presente" else "Presente") })
|
||||
AssistChip(onClick = { attendance = "ABSENT" }, label = { Text(if (attendance == "ABSENT") "✓ Ausente" else "Ausente") })
|
||||
}
|
||||
if (attendance == "PRESENT") {
|
||||
OutlinedTextField(fullName, { fullName = it }, label = { Text("Nombre y apellido *") }, modifier = Modifier.fillMaxWidth())
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
listOf("DNI", "CUIL", "PASSPORT", "OTHER").forEach { kind ->
|
||||
AssistChip(onClick = { documentType = kind }, label = { Text(if (documentType == kind) "✓ $kind" else kind) })
|
||||
}
|
||||
OutlinedTextField(fullName, { fullName = it }, label = { Text("Nombres y apellidos *") }, modifier = Modifier.fillMaxWidth())
|
||||
OutlinedTextField(documentNumber, { documentNumber = it.filter(Char::isDigit) }, label = { Text("DNI *") }, modifier = Modifier.fillMaxWidth())
|
||||
OutlinedTextField(position, { position = it }, label = { Text("Cargo / función *") }, modifier = Modifier.fillMaxWidth())
|
||||
OutlinedTextField(email, { email = it }, label = { Text("Email *") }, modifier = Modifier.fillMaxWidth())
|
||||
if (closure?.responsible == null && closure?.representativeSuggestion != null) {
|
||||
Text("Datos precargados del Acta anterior. Confirmalos para esta Acta.", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
OutlinedTextField(documentNumber, { documentNumber = it }, label = { Text("Documento *") }, modifier = Modifier.fillMaxWidth())
|
||||
OutlinedTextField(position, { position = it }, label = { Text("Cargo *") }, modifier = Modifier.fillMaxWidth())
|
||||
OutlinedTextField(email, { email = it }, label = { Text("Email") }, modifier = Modifier.fillMaxWidth())
|
||||
OutlinedTextField(phone, { phone = it }, label = { Text("Teléfono") }, modifier = Modifier.fillMaxWidth())
|
||||
Button(
|
||||
onClick = {
|
||||
model.setCompanyResponsiblePresent(fullName, documentType, documentNumber, position, email, phone)
|
||||
},
|
||||
enabled = !model.busy && fullName.isNotBlank() && documentNumber.isNotBlank() && position.isNotBlank(),
|
||||
enabled = !model.busy && fullName.isNotBlank() && documentNumber.isNotBlank() && position.isNotBlank() && email.contains("@") && email.contains("."),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Guardar responsable") }
|
||||
) { Text("Guardar representante") }
|
||||
} else {
|
||||
OutlinedTextField(
|
||||
absenceReason,
|
||||
@@ -265,7 +232,7 @@ fun MobileActsScreen(
|
||||
|
||||
HorizontalDivider()
|
||||
Text("Finalizar contenido", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text("Al cerrar el Acta, el contenido y los Hallazgos quedan inmutables. Definí ahora la urgencia según lo constatado.")
|
||||
Text("Al cerrar el contenido, el Acta queda inmutable y pasa a Para firmar. La firma del inspector se toma de Mi perfil del Dashboard; en la tablet firma el acompañante de la empresa.")
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
AssistChip(
|
||||
onClick = { closingUrgency = "NON_URGENT" },
|
||||
@@ -280,69 +247,57 @@ fun MobileActsScreen(
|
||||
onClick = { model.prepareSelectedAct(closingUrgency) },
|
||||
enabled = !model.busy && closure?.responsible != null && closingUrgency.isNotBlank(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Finalizar y BLOQUEAR Acta") }
|
||||
) { Text("Cerrar contenido y pasar a firma") }
|
||||
}
|
||||
|
||||
"LOCKED" -> {
|
||||
val signatures = closure?.signatures.orEmpty()
|
||||
val inspectorSigned = signatures.any { it.signerType == "INSPECTOR" && it.status == "SIGNED" }
|
||||
val companyOutcome = signatures.firstOrNull { it.signerType == "COMPANY_RESPONSIBLE" }
|
||||
val companyResolved = companyOutcome?.status == "SIGNED" || companyOutcome?.status == "REFUSED"
|
||||
val companyResolved = companyOutcome?.status == "SIGNED" || companyOutcome?.status == "REFUSED" || companyOutcome?.status == "ABSENT"
|
||||
|
||||
Text("Acta BLOQUEADA", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text("El contenido ya es inmutable. Sólo resta resolver firmas y manifestaciones para poder SELLARLA.")
|
||||
closure?.closure?.preparedSha256?.let { Text("Hash bloqueado: $it", style = MaterialTheme.typography.bodySmall) }
|
||||
Text("Para firmar", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text("El contenido ya es inmutable. La firma del inspector está guardada en el Dashboard y se aplicará al cierre final.")
|
||||
|
||||
HorizontalDivider()
|
||||
Text("Firma del inspector", fontWeight = FontWeight.Bold)
|
||||
if (inspectorSigned) {
|
||||
Text("✓ Firma del inspector registrada", color = MaterialTheme.colorScheme.primary)
|
||||
} else {
|
||||
Text(closure?.consents?.inspector.orEmpty(), style = MaterialTheme.typography.bodySmall)
|
||||
SignaturePad(
|
||||
label = "Firmá como inspector/a",
|
||||
enabled = !model.busy,
|
||||
onCaptured = { file -> signWithGeo(file, company = false) },
|
||||
)
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Text("Manifestación de la empresa", fontWeight = FontWeight.Bold)
|
||||
Text("Acompañante / representante de la empresa", fontWeight = FontWeight.Bold)
|
||||
if (companyOutcome != null && companyResolved) {
|
||||
val detail = when (companyOutcome.status) {
|
||||
"SIGNED" -> if (companyOutcome.companyManifestation == "DISSENT") "Firma en disidencia" else "Firma en conformidad"
|
||||
"REFUSED" -> "Negativa a firmar"
|
||||
"SIGNED" -> if (companyOutcome.companyManifestation == "DISSENT") "Firmó en disconformidad" else "Firmó en conformidad"
|
||||
"REFUSED" -> "Se negó a firmar"
|
||||
"ABSENT" -> "Ausencia documentada"
|
||||
else -> companyOutcome.status
|
||||
}
|
||||
Text("✓ $detail", color = MaterialTheme.colorScheme.primary)
|
||||
companyOutcome.reason?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
companyOutcome.companyStatement?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
} else if (closure?.responsible?.attendanceStatus == "ABSENT") {
|
||||
Text(
|
||||
"El responsable fue registrado como ausente. La ausencia NO resuelve la manifestación: deberá obtenerse firma o negativa posteriormente antes de SELLAR el Acta.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
val recordedAbsence = closure.responsible.absenceReason.orEmpty()
|
||||
Text("El representante fue registrado como ausente. Confirmá esta ausencia para dejar la constancia documental.")
|
||||
Text(recordedAbsence, style = MaterialTheme.typography.bodySmall)
|
||||
OutlinedButton(
|
||||
onClick = { model.recordCompanyOutcome("ABSENT", recordedAbsence) },
|
||||
enabled = !model.busy && recordedAbsence.trim().length >= 10,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Confirmar ausencia documentada") }
|
||||
} else {
|
||||
Text(closure?.consents?.company.orEmpty(), style = MaterialTheme.typography.bodySmall)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
AssistChip(onClick = { manifestation = "CONFORMITY" }, label = { Text(if (manifestation == "CONFORMITY") "✓ Conforme" else "Conforme") })
|
||||
AssistChip(onClick = { manifestation = "DISSENT" }, label = { Text(if (manifestation == "DISSENT") "✓ En disidencia" else "En disidencia") })
|
||||
AssistChip(onClick = { manifestation = "DISSENT" }, label = { Text(if (manifestation == "DISSENT") "✓ En disconformidad" else "En disconformidad") })
|
||||
}
|
||||
if (manifestation == "DISSENT") {
|
||||
OutlinedTextField(
|
||||
dissentStatement,
|
||||
{ dissentStatement = it },
|
||||
label = { Text("Manifestación de disidencia *") },
|
||||
label = { Text("Motivo de disconformidad *") },
|
||||
minLines = 2,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
SignaturePad(
|
||||
label = "Firma del responsable de empresa",
|
||||
enabled = !model.busy && inspectorSigned && (manifestation != "DISSENT" || dissentStatement.trim().length >= 10),
|
||||
onCaptured = { file -> signWithGeo(file, company = true) },
|
||||
label = "Firma del representante de la empresa (acompañante)",
|
||||
enabled = !model.busy && (manifestation != "DISSENT" || dissentStatement.trim().length >= 10),
|
||||
onCaptured = { file -> signCompanyWithGeo(file) },
|
||||
)
|
||||
Text("Si la persona presente se niega a firmar, asentá el motivo en lugar de dibujar una firma.", style = MaterialTheme.typography.bodySmall)
|
||||
OutlinedTextField(
|
||||
refusalReason,
|
||||
{ refusalReason = it },
|
||||
@@ -352,23 +307,20 @@ fun MobileActsScreen(
|
||||
)
|
||||
OutlinedButton(
|
||||
onClick = { model.recordCompanyOutcome("REFUSED", refusalReason) },
|
||||
enabled = !model.busy && inspectorSigned && refusalReason.trim().length >= 10,
|
||||
enabled = !model.busy && refusalReason.trim().length >= 10,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Registrar negativa a firmar") }
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
if (inspectorSigned && companyResolved) {
|
||||
if (companyResolved) {
|
||||
Button(
|
||||
onClick = { model.closeSelectedAct() },
|
||||
enabled = !model.busy,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("SELLAR Acta definitivamente") }
|
||||
) { Text("Aplicar mi firma y cerrar Acta") }
|
||||
} else {
|
||||
Text(
|
||||
"Esta Acta bloquea el cierre de la Inspección hasta tener firma de inspector y firma o negativa válida de la empresa.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Text("Completá la firma, disconformidad o negativa del acompañante para habilitar el cierre final.", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.items
|
||||
@@ -86,21 +85,33 @@ fun MobileHomeScreen(model: MainViewModel) {
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().padding(top = 28.dp)) {
|
||||
Row(
|
||||
Column(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Column {
|
||||
Text("Mis inspecciones", style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)
|
||||
Text(session.displayName, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
Row {
|
||||
OutlinedButton(onClick = { model.loadVisits() }, enabled = !model.busy && !opening) {
|
||||
Text("Actualizar")
|
||||
Row(
|
||||
Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
OutlinedButton(
|
||||
onClick = { model.loadVisits() },
|
||||
enabled = !model.busy && !opening,
|
||||
modifier = Modifier.weight(1f),
|
||||
) {
|
||||
Text("Actualizar", maxLines = 1)
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = { model.logout() },
|
||||
enabled = !opening,
|
||||
modifier = Modifier.weight(1f),
|
||||
) {
|
||||
Text("Salir", maxLines = 1)
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
OutlinedButton(onClick = { model.logout() }, enabled = !opening) { Text("Salir") }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+81
-113
@@ -3,7 +3,6 @@ package com.korexlabs.dhinspeccion.ui
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
@@ -72,17 +71,18 @@ fun ModernMobileActsScreen(
|
||||
val visit = model.visit ?: return
|
||||
val selected = model.selectedAct
|
||||
val closure = model.actClosure
|
||||
val representativeSeed = closure?.responsible ?: closure?.representativeSuggestion
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
var closingUrgency by rememberSaveable(selected?.id) { mutableStateOf("") }
|
||||
var attendance by rememberSaveable(selected?.id) { mutableStateOf(closure?.responsible?.attendanceStatus ?: "PRESENT") }
|
||||
var fullName by rememberSaveable(selected?.id) { mutableStateOf(closure?.responsible?.fullName.orEmpty()) }
|
||||
var documentType by rememberSaveable(selected?.id) { mutableStateOf(closure?.responsible?.documentType ?: "DNI") }
|
||||
var documentNumber by rememberSaveable(selected?.id) { mutableStateOf(closure?.responsible?.documentNumber.orEmpty()) }
|
||||
var position by rememberSaveable(selected?.id) { mutableStateOf(closure?.responsible?.position.orEmpty()) }
|
||||
var email by rememberSaveable(selected?.id) { mutableStateOf(closure?.responsible?.email.orEmpty()) }
|
||||
var phone by rememberSaveable(selected?.id) { mutableStateOf(closure?.responsible?.phone.orEmpty()) }
|
||||
var attendance by rememberSaveable(selected?.id) { mutableStateOf(representativeSeed?.attendanceStatus ?: "PRESENT") }
|
||||
var fullName by rememberSaveable(selected?.id) { mutableStateOf(representativeSeed?.fullName.orEmpty()) }
|
||||
var documentType by rememberSaveable(selected?.id) { mutableStateOf("DNI") }
|
||||
var documentNumber by rememberSaveable(selected?.id) { mutableStateOf(representativeSeed?.documentNumber.orEmpty()) }
|
||||
var position by rememberSaveable(selected?.id) { mutableStateOf(representativeSeed?.position.orEmpty()) }
|
||||
var email by rememberSaveable(selected?.id) { mutableStateOf(representativeSeed?.email.orEmpty()) }
|
||||
var phone by rememberSaveable(selected?.id) { mutableStateOf(representativeSeed?.phone.orEmpty()) }
|
||||
var absenceReason by rememberSaveable(selected?.id) { mutableStateOf(closure?.responsible?.absenceReason.orEmpty()) }
|
||||
var refusalReason by rememberSaveable(selected?.id) { mutableStateOf("") }
|
||||
var manifestation by rememberSaveable(selected?.id) { mutableStateOf("CONFORMITY") }
|
||||
@@ -90,26 +90,17 @@ fun ModernMobileActsScreen(
|
||||
|
||||
LaunchedEffect(visit.id) { model.reloadActs() }
|
||||
|
||||
fun signWithGeo(file: File, company: Boolean) {
|
||||
fun signCompanyWithGeo(file: File) {
|
||||
scope.launch {
|
||||
val geo = runCatching { currentModernActSignatureGeo(context) }.getOrNull()
|
||||
if (company) {
|
||||
model.signSelectedActAsCompany(
|
||||
png = file,
|
||||
latitude = geo?.latitude,
|
||||
longitude = geo?.longitude,
|
||||
accuracyM = geo?.accuracyM,
|
||||
manifestation = manifestation,
|
||||
statement = dissentStatement.takeIf { manifestation == "DISSENT" },
|
||||
)
|
||||
} else {
|
||||
model.signSelectedActAsInspector(
|
||||
png = file,
|
||||
latitude = geo?.latitude,
|
||||
longitude = geo?.longitude,
|
||||
accuracyM = geo?.accuracyM,
|
||||
)
|
||||
}
|
||||
model.signSelectedActAsCompany(
|
||||
png = file,
|
||||
latitude = geo?.latitude,
|
||||
longitude = geo?.longitude,
|
||||
accuracyM = geo?.accuracyM,
|
||||
manifestation = manifestation,
|
||||
statement = dissentStatement.takeIf { manifestation == "DISSENT" },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,12 +162,8 @@ fun ModernMobileActsScreen(
|
||||
onClick = { model.selectAct(act.id) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.large,
|
||||
color = if (active) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surface,
|
||||
tonalElevation = if (active) 1.dp else 0.dp,
|
||||
border = BorderStroke(
|
||||
if (active) 2.dp else 1.dp,
|
||||
if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outlineVariant,
|
||||
),
|
||||
color = if (active) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant,
|
||||
tonalElevation = 0.dp,
|
||||
) {
|
||||
Row(
|
||||
Modifier.padding(15.dp),
|
||||
@@ -244,33 +231,6 @@ fun ModernMobileActsScreen(
|
||||
}
|
||||
|
||||
if (selected != null) {
|
||||
HorizontalDivider()
|
||||
Surface(
|
||||
Modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.large,
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
) {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(selected.code, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
StatusPill(modernActStatusLabel(selected.status))
|
||||
}
|
||||
Text(
|
||||
when (selected.urgency) {
|
||||
"URGENT" -> "Urgencia · Urgente"
|
||||
"NON_URGENT" -> "Urgencia · No urgente"
|
||||
else -> "Urgencia · Se define al cerrar el Acta"
|
||||
},
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text("${selected.findingCount} Hallazgos · ${selected.assetCount} elementos de Inventario", style = MaterialTheme.typography.bodySmall)
|
||||
selected.deadlineAt?.let { Text("Vencimiento · $it", style = MaterialTheme.typography.bodySmall) }
|
||||
if (selected.deadlineAt == null && selected.deadlineBasis == "GEDO_DATE") {
|
||||
Text("Vencimiento pendiente de fecha GEDO", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
when (selected.status) {
|
||||
"DRAFT" -> {
|
||||
ElevatedCard(Modifier.fillMaxWidth()) {
|
||||
@@ -293,28 +253,25 @@ fun ModernMobileActsScreen(
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Person, null, tint = MaterialTheme.colorScheme.primary)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("Responsable de la empresa", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text("Representante de la empresa", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
FilterChip(selected = attendance == "PRESENT", onClick = { attendance = "PRESENT" }, label = { Text("Presente") })
|
||||
FilterChip(selected = attendance == "ABSENT", onClick = { attendance = "ABSENT" }, label = { Text("Ausente") })
|
||||
}
|
||||
if (attendance == "PRESENT") {
|
||||
OutlinedTextField(fullName, { fullName = it }, label = { Text("Nombre y apellido *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
listOf("DNI", "CUIL", "PASSPORT", "OTHER").forEach { kind ->
|
||||
FilterChip(selected = documentType == kind, onClick = { documentType = kind }, label = { Text(documentTypeLabelEs(kind)) })
|
||||
}
|
||||
OutlinedTextField(fullName, { fullName = it }, label = { Text("Nombres y apellidos *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||
OutlinedTextField(documentNumber, { documentNumber = it.filter(Char::isDigit) }, label = { Text("DNI *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||
OutlinedTextField(position, { position = it }, label = { Text("Cargo / función *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||
OutlinedTextField(email, { email = it }, label = { Text("Email *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||
if (closure?.responsible == null && closure?.representativeSuggestion != null) {
|
||||
Text("Datos precargados del Acta anterior. Confirmalos antes de cerrar esta Acta.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
OutlinedTextField(documentNumber, { documentNumber = it }, label = { Text("Documento *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||
OutlinedTextField(position, { position = it }, label = { Text("Cargo *") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||
OutlinedTextField(email, { email = it }, label = { Text("Correo electrónico") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||
OutlinedTextField(phone, { phone = it }, label = { Text("Teléfono") }, modifier = Modifier.fillMaxWidth(), singleLine = true)
|
||||
Button(
|
||||
onClick = { model.setCompanyResponsiblePresent(fullName, documentType, documentNumber, position, email, phone) },
|
||||
enabled = !model.busy && fullName.isNotBlank() && documentNumber.isNotBlank() && position.isNotBlank(),
|
||||
enabled = !model.busy && fullName.isNotBlank() && documentNumber.isNotBlank() && position.isNotBlank() && email.contains("@") && email.contains("."),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Guardar responsable") }
|
||||
) { Text("Guardar representante") }
|
||||
} else {
|
||||
OutlinedTextField(
|
||||
absenceReason,
|
||||
@@ -340,7 +297,7 @@ fun ModernMobileActsScreen(
|
||||
Text("Cerrar Acta", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
Text(
|
||||
"Al cerrar el contenido, el Acta queda inmutable y pasa a Pendiente de firma. En este momento definí la urgencia según lo constatado en campo.",
|
||||
"Al cerrar el contenido, el Acta queda inmutable y pasa a Para firmar. La firma del inspector se toma de Mi perfil del Dashboard; en la tablet sólo firma el acompañante de la empresa. La urgencia pertenece al Acta completa. La urgencia no se asigna a cada Hallazgo.",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text("Urgencia del Acta", fontWeight = FontWeight.SemiBold)
|
||||
@@ -369,83 +326,94 @@ fun ModernMobileActsScreen(
|
||||
onClick = { model.prepareSelectedAct(closingUrgency) },
|
||||
enabled = !model.busy && closure?.responsible != null && closingUrgency.isNotBlank(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Cerrar Acta y dejar pendiente de firma") }
|
||||
) { Text("Cerrar contenido y pasar a firma") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
"LOCKED" -> {
|
||||
val signatures = closure?.signatures.orEmpty()
|
||||
val inspectorSigned = signatures.any { it.signerType == "INSPECTOR" && it.status == "SIGNED" }
|
||||
val companyOutcome = signatures.firstOrNull { it.signerType == "COMPANY_RESPONSIBLE" }
|
||||
val companyResolved = companyOutcome?.status == "SIGNED" || companyOutcome?.status == "REFUSED"
|
||||
val companyResolved = companyOutcome?.status == "SIGNED" || companyOutcome?.status == "REFUSED" || companyOutcome?.status == "ABSENT"
|
||||
|
||||
ElevatedCard(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Lock, null, tint = MaterialTheme.colorScheme.secondary)
|
||||
Icon(Icons.Filled.EditNote, null, tint = MaterialTheme.colorScheme.primary)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("Acta pendiente de firma", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text("Para firmar", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
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("Huella de integridad · $it", style = MaterialTheme.typography.bodySmall) }
|
||||
|
||||
HorizontalDivider()
|
||||
Text("Firma del inspector", fontWeight = FontWeight.Bold)
|
||||
if (inspectorSigned) {
|
||||
SuccessLine("Firma del inspector registrada")
|
||||
} else {
|
||||
Text(closure?.consents?.inspector.orEmpty(), style = MaterialTheme.typography.bodySmall)
|
||||
SignaturePad(
|
||||
label = "Firmá como inspector/a",
|
||||
enabled = !model.busy,
|
||||
onCaptured = { file -> signWithGeo(file, company = false) },
|
||||
)
|
||||
Text(
|
||||
"El contenido ya está cerrado e inmutable. Ahora corresponde la manifestación y firma del acompañante de la empresa.",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
color = MaterialTheme.colorScheme.primaryContainer,
|
||||
) {
|
||||
Row(Modifier.padding(12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Icon(Icons.Filled.CheckCircle, null, tint = MaterialTheme.colorScheme.primary)
|
||||
Text(
|
||||
"Tu firma de inspector está guardada en el Dashboard y se incorporará automáticamente cuando cierres esta Acta.",
|
||||
Modifier.weight(1f),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Text("Manifestación de la empresa", fontWeight = FontWeight.Bold)
|
||||
Text("Acompañante / representante de la empresa", fontWeight = FontWeight.Bold)
|
||||
if (companyOutcome != null && companyResolved) {
|
||||
val detail = when (companyOutcome.status) {
|
||||
"SIGNED" -> if (companyOutcome.companyManifestation == "DISSENT") "Firma en disidencia" else "Firma en conformidad"
|
||||
"REFUSED" -> "Negativa a firmar"
|
||||
"SIGNED" -> if (companyOutcome.companyManifestation == "DISSENT") "Firmó en disconformidad" else "Firmó en conformidad"
|
||||
"REFUSED" -> "Se negó a firmar"
|
||||
"ABSENT" -> "Ausencia documentada"
|
||||
else -> humanBackendLabelEs(companyOutcome.status)
|
||||
}
|
||||
SuccessLine(detail)
|
||||
companyOutcome.reason?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
companyOutcome.companyStatement?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
} else if (closure?.responsible?.attendanceStatus == "ABSENT") {
|
||||
Surface(Modifier.fillMaxWidth(), shape = MaterialTheme.shapes.medium, color = MaterialTheme.colorScheme.errorContainer) {
|
||||
Row(Modifier.padding(12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Icon(Icons.Filled.ErrorOutline, null, tint = MaterialTheme.colorScheme.error)
|
||||
Text(
|
||||
"La ausencia no resuelve la manifestación. Debe registrarse firma o negativa antes de firmar y cerrar el Acta.",
|
||||
Modifier.weight(1f),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
val recordedAbsence = closure.responsible.absenceReason.orEmpty()
|
||||
Surface(Modifier.fillMaxWidth(), shape = MaterialTheme.shapes.medium, color = MaterialTheme.colorScheme.secondaryContainer) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Icon(Icons.Filled.ErrorOutline, null, tint = MaterialTheme.colorScheme.secondary)
|
||||
Text(
|
||||
"El representante fue registrado como ausente. Confirmá esta ausencia para dejar la constancia documental.",
|
||||
Modifier.weight(1f),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
Text(recordedAbsence, style = MaterialTheme.typography.bodySmall)
|
||||
OutlinedButton(
|
||||
onClick = { model.recordCompanyOutcome("ABSENT", recordedAbsence) },
|
||||
enabled = !model.busy && recordedAbsence.trim().length >= 10,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Confirmar ausencia documentada") }
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Text(closure?.consents?.company.orEmpty(), style = MaterialTheme.typography.bodySmall)
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
FilterChip(selected = manifestation == "CONFORMITY", onClick = { manifestation = "CONFORMITY" }, label = { Text("Conforme") })
|
||||
FilterChip(selected = manifestation == "DISSENT", onClick = { manifestation = "DISSENT" }, label = { Text("En disidencia") })
|
||||
FilterChip(selected = manifestation == "DISSENT", onClick = { manifestation = "DISSENT" }, label = { Text("En disconformidad") })
|
||||
}
|
||||
if (manifestation == "DISSENT") {
|
||||
OutlinedTextField(
|
||||
dissentStatement,
|
||||
{ dissentStatement = it },
|
||||
label = { Text("Manifestación de disidencia *") },
|
||||
label = { Text("Motivo de disconformidad *") },
|
||||
minLines = 2,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
SignaturePad(
|
||||
label = "Firma del responsable de empresa",
|
||||
enabled = !model.busy && inspectorSigned && (manifestation != "DISSENT" || dissentStatement.trim().length >= 10),
|
||||
onCaptured = { file -> signWithGeo(file, company = true) },
|
||||
label = "Firma del representante de la empresa (acompañante)",
|
||||
enabled = !model.busy && (manifestation != "DISSENT" || dissentStatement.trim().length >= 10),
|
||||
onCaptured = { file -> signCompanyWithGeo(file) },
|
||||
)
|
||||
Text("Si se niega a firmar, registrá el motivo.", style = MaterialTheme.typography.bodySmall)
|
||||
Text("Si se niega a firmar, asentá el motivo para dejar la constancia.", style = MaterialTheme.typography.bodySmall)
|
||||
OutlinedTextField(
|
||||
refusalReason,
|
||||
{ refusalReason = it },
|
||||
@@ -455,12 +423,12 @@ fun ModernMobileActsScreen(
|
||||
)
|
||||
OutlinedButton(
|
||||
onClick = { model.recordCompanyOutcome("REFUSED", refusalReason) },
|
||||
enabled = !model.busy && inspectorSigned && refusalReason.trim().length >= 10,
|
||||
enabled = !model.busy && refusalReason.trim().length >= 10,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Registrar negativa a firmar") }
|
||||
}
|
||||
|
||||
if (inspectorSigned && companyResolved) {
|
||||
if (companyResolved) {
|
||||
Button(
|
||||
onClick = { model.closeSelectedAct() },
|
||||
enabled = !model.busy,
|
||||
@@ -468,11 +436,11 @@ fun ModernMobileActsScreen(
|
||||
) {
|
||||
Icon(Icons.Filled.CheckCircle, null)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("Firmar y cerrar Acta")
|
||||
Text("Aplicar mi firma y cerrar Acta")
|
||||
}
|
||||
} else {
|
||||
Text(
|
||||
"La Inspección no puede cerrarse hasta completar las manifestaciones de esta Acta.",
|
||||
"Completá la firma, disconformidad o negativa del acompañante para habilitar el cierre final.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
@@ -16,6 +16,7 @@ import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
@@ -36,6 +37,11 @@ import androidx.compose.material.icons.filled.LocationOn
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material.icons.filled.WarningAmber
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ExposedDropdownMenuBox
|
||||
import androidx.compose.material3.MenuAnchorType
|
||||
import androidx.compose.material3.ExposedDropdownMenuDefaults
|
||||
import androidx.compose.material3.ElevatedCard
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
@@ -57,6 +63,7 @@ import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.focus.FocusDirection
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
@@ -76,6 +83,7 @@ import com.korexlabs.dhinspeccion.MainViewModel
|
||||
import com.korexlabs.dhinspeccion.data.FieldAttributeDefinition
|
||||
import com.korexlabs.dhinspeccion.data.FieldInventoryItem
|
||||
import com.korexlabs.dhinspeccion.data.FieldType
|
||||
import com.korexlabs.dhinspeccion.data.fieldAttributePayload
|
||||
import com.korexlabs.dhinspeccion.data.VisitDetail
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -259,6 +267,7 @@ private fun ModernChecklistCard(visit: VisitDetail) {
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
@@ -279,6 +288,7 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
||||
var selectedTypeId by rememberSaveable(visit.id) { mutableStateOf<String?>(null) }
|
||||
var selectedFamilyId by rememberSaveable(visit.id) { mutableStateOf<String?>(null) }
|
||||
var familySearch by rememberSaveable(visit.id) { mutableStateOf("") }
|
||||
var familyExpanded by remember { mutableStateOf(false) }
|
||||
val attributeValues = remember { mutableStateMapOf<String, String>() }
|
||||
var pendingAutoPhoto by rememberSaveable(visit.id) { mutableStateOf(false) }
|
||||
var localError by rememberSaveable(visit.id) { mutableStateOf<String?>(null) }
|
||||
@@ -295,6 +305,7 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
||||
selectedTypeId = null
|
||||
selectedFamilyId = null
|
||||
familySearch = ""
|
||||
familyExpanded = false
|
||||
attributeValues.clear()
|
||||
localError = null
|
||||
}
|
||||
@@ -379,6 +390,9 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
||||
}
|
||||
|
||||
val selectedType = model.fieldTypes.firstOrNull { it.id == selectedTypeId }
|
||||
val editableAttributes = selectedType?.attributes.orEmpty().filterNot {
|
||||
selectedType?.familyRequired == true && it.code == "tipo_instalacion"
|
||||
}
|
||||
val selectedFamily = selectedType?.families?.firstOrNull { it.id == selectedFamilyId }
|
||||
val filteredFamilies = remember(selectedType, familySearch) {
|
||||
val needle = modernNormalize(familySearch)
|
||||
@@ -746,37 +760,56 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
||||
}
|
||||
|
||||
if (selectedType?.familyRequired == true) {
|
||||
Text("Clasificación técnica", fontWeight = FontWeight.Bold)
|
||||
OutlinedTextField(
|
||||
value = familySearch,
|
||||
onValueChange = { familySearch = it },
|
||||
label = { Text("Buscar clasificación") },
|
||||
leadingIcon = { Icon(Icons.Filled.Search, null) },
|
||||
supportingText = { Text("${filteredFamilies.size} opciones compatibles") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
)
|
||||
filteredFamilies.take(12).forEach { family ->
|
||||
Surface(
|
||||
onClick = { selectedFamilyId = family.id },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
color = if (selectedFamilyId == family.id) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surface,
|
||||
border = BorderStroke(1.dp, if (selectedFamilyId == family.id) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outlineVariant),
|
||||
ExposedDropdownMenuBox(
|
||||
expanded = familyExpanded && !model.busy,
|
||||
onExpandedChange = {
|
||||
if (!model.busy) {
|
||||
familyExpanded = it
|
||||
familySearch = ""
|
||||
}
|
||||
},
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = if (familyExpanded) familySearch else selectedFamily?.name.orEmpty(),
|
||||
onValueChange = { familySearch = it; familyExpanded = true },
|
||||
label = { Text(if (isSubinstallation) "Tipo de subinstalación" else "Tipo de instalación") },
|
||||
placeholder = { Text("Buscar por nombre o código") },
|
||||
leadingIcon = { Icon(Icons.Filled.Search, null) },
|
||||
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = familyExpanded) },
|
||||
enabled = !model.busy,
|
||||
modifier = Modifier.fillMaxWidth().menuAnchor(MenuAnchorType.PrimaryEditable),
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
|
||||
keyboardActions = KeyboardActions(onNext = {
|
||||
familyExpanded = false
|
||||
focusManager.moveFocus(FocusDirection.Down)
|
||||
}),
|
||||
)
|
||||
ExposedDropdownMenu(
|
||||
expanded = familyExpanded && !model.busy,
|
||||
onDismissRequest = { familyExpanded = false; familySearch = "" },
|
||||
modifier = Modifier.heightIn(max = 280.dp),
|
||||
) {
|
||||
Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
(if (family.isOther) "Otro · " else "") + family.name,
|
||||
Modifier.weight(1f),
|
||||
fontWeight = if (selectedFamilyId == family.id) FontWeight.Bold else FontWeight.Normal,
|
||||
if (filteredFamilies.isEmpty()) {
|
||||
DropdownMenuItem(text = { Text("Sin coincidencias") }, onClick = {}, enabled = false)
|
||||
}
|
||||
filteredFamilies.forEach { family ->
|
||||
DropdownMenuItem(
|
||||
text = { Text((if (family.isOther) "Otro · " else "") + family.name) },
|
||||
trailingIcon = {
|
||||
if (selectedFamilyId == family.id) Icon(Icons.Filled.CheckCircle, "Seleccionado")
|
||||
},
|
||||
onClick = {
|
||||
selectedFamilyId = family.id
|
||||
familyExpanded = false
|
||||
familySearch = ""
|
||||
keyboard?.hide()
|
||||
focusManager.clearFocus()
|
||||
},
|
||||
)
|
||||
if (selectedFamilyId == family.id) Icon(Icons.Filled.CheckCircle, null, tint = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (filteredFamilies.size > 12) {
|
||||
Text("Seguí escribiendo para reducir la lista.", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
selectedFamily?.let { family ->
|
||||
if (family.isOther) {
|
||||
Text("Quedará marcado para revisión en oficina.", color = MaterialTheme.colorScheme.secondary)
|
||||
@@ -791,9 +824,11 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
label = { Text("Nombre técnico *") },
|
||||
supportingText = { Text("Usá la denominación técnica del elemento. El código DH se genera automáticamente.") },
|
||||
placeholder = { Text("Denominación técnica") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
|
||||
keyboardActions = KeyboardActions(onNext = { focusManager.moveFocus(FocusDirection.Down) }),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = commonName,
|
||||
@@ -801,17 +836,24 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
||||
label = { Text("Nombre habitual (opcional)") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
|
||||
keyboardActions = KeyboardActions(onNext = { focusManager.moveFocus(FocusDirection.Down) }),
|
||||
)
|
||||
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,
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(imeAction = if (editableAttributes.isEmpty()) ImeAction.Done else ImeAction.Next),
|
||||
keyboardActions = KeyboardActions(
|
||||
onNext = { focusManager.moveFocus(FocusDirection.Down) },
|
||||
onDone = { keyboard?.hide(); focusManager.clearFocus() },
|
||||
),
|
||||
)
|
||||
|
||||
selectedType?.attributes?.forEach { definition ->
|
||||
editableAttributes.forEachIndexed { index, definition ->
|
||||
val isLastAttribute = index == editableAttributes.lastIndex
|
||||
OutlinedTextField(
|
||||
value = attributeValues[definition.code].orEmpty(),
|
||||
onValueChange = { attributeValues[definition.code] = it },
|
||||
@@ -822,8 +864,14 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
||||
},
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = if (definition.dataType.uppercase() in setOf("NUMBER", "DECIMAL", "INTEGER", "FLOAT")) KeyboardType.Decimal else KeyboardType.Text,
|
||||
imeAction = if (isLastAttribute) ImeAction.Done else ImeAction.Next,
|
||||
),
|
||||
keyboardActions = KeyboardActions(
|
||||
onNext = { focusManager.moveFocus(FocusDirection.Down) },
|
||||
onDone = { keyboard?.hide(); focusManager.clearFocus() },
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -840,10 +888,9 @@ private fun ModernFieldInventoryScreen(model: MainViewModel, onBack: () -> Unit)
|
||||
}
|
||||
}
|
||||
|
||||
val attributesReady = selectedType?.attributes
|
||||
?.filter { it.isRequired }
|
||||
?.all { attributeValues[it.code].orEmpty().isNotBlank() }
|
||||
?: false
|
||||
val attributesReady = editableAttributes
|
||||
.filter { it.isRequired }
|
||||
.all { attributeValues[it.code].orEmpty().isNotBlank() }
|
||||
val familyReady = selectedType?.familyRequired != true || selectedFamilyId != null
|
||||
Button(
|
||||
onClick = { requestCreate() },
|
||||
@@ -1074,18 +1121,7 @@ private fun modernNormalize(value: String): String = value.trim().lowercase()
|
||||
private fun modernStatusLabel(status: String): String = visitStatusLabelEs(status)
|
||||
|
||||
private fun buildModernAttributes(type: FieldType, values: Map<String, String>): Map<String, Any?> =
|
||||
type.attributes.mapNotNull { definition ->
|
||||
val raw = values[definition.code]?.trim().orEmpty()
|
||||
if (raw.isBlank()) return@mapNotNull null
|
||||
definition.code to coerceModernAttribute(definition, raw)
|
||||
}.toMap()
|
||||
|
||||
private fun coerceModernAttribute(definition: FieldAttributeDefinition, raw: String): Any = when (definition.dataType.uppercase()) {
|
||||
"INTEGER", "INT" -> raw.toLongOrNull() ?: raw
|
||||
"NUMBER", "DECIMAL", "FLOAT", "DOUBLE" -> raw.replace(',', '.').toDoubleOrNull() ?: raw
|
||||
"BOOLEAN", "BOOL" -> raw.lowercase() in setOf("true", "1", "si", "sí", "yes")
|
||||
else -> raw
|
||||
}
|
||||
fieldAttributePayload(type.attributes, values)
|
||||
|
||||
private fun modernHasPermission(context: Context, permission: String): Boolean =
|
||||
ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
@@ -13,7 +13,7 @@ internal fun visitStatusLabelEs(status: String?): String = when (status?.upperca
|
||||
|
||||
internal fun actStatusLabelEs(status: String?): String = when (status?.uppercase(Locale.ROOT)) {
|
||||
"DRAFT" -> "En elaboración"
|
||||
"LOCKED" -> "Pendiente de firma"
|
||||
"LOCKED" -> "Para firmar"
|
||||
"SEALED" -> "Firmada y cerrada"
|
||||
"CLOSED" -> "Cerrada"
|
||||
"RECTIFIED" -> "Rectificada"
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 6.5 KiB After Width: | Height: | Size: 8.2 KiB |
+1
-1
@@ -10,7 +10,7 @@ class DynamicFieldFlowContractTest {
|
||||
@Test
|
||||
fun fastSubinstallationFlowKeepsParentClassificationAndCaptureSteps() {
|
||||
assertTrue(source.contains("Elegí la Instalación padre"))
|
||||
assertTrue(source.contains("Clasificación técnica *"))
|
||||
assertTrue(source.contains("Tipo de instalación *"))
|
||||
assertTrue(source.contains("Guardar y tomar foto"))
|
||||
assertTrue(source.contains("model.loadFieldTypes(item.id)"))
|
||||
assertTrue(source.contains("parentId = item.id"))
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.korexlabs.dhinspeccion
|
||||
|
||||
import com.korexlabs.dhinspeccion.data.FieldAttributeDefinition
|
||||
import com.korexlabs.dhinspeccion.data.fieldAttributePayload
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class FieldAttributePayloadTest {
|
||||
@Test
|
||||
fun payloadUsesDefinitionIdsExpectedByApiAndKeepsTypedValues() {
|
||||
val definitions = listOf(
|
||||
FieldAttributeDefinition("id-marca", "campo_marca", "Marca", "TEXT"),
|
||||
FieldAttributeDefinition("id-capacidad", "campo_capacidad", "Capacidad", "NUMBER"),
|
||||
FieldAttributeDefinition("id-serie", "campo_numero_serie", "Número de serie", "TEXT"),
|
||||
)
|
||||
|
||||
val payload = fieldAttributePayload(
|
||||
definitions,
|
||||
mapOf("campo_marca" to " algo ", "campo_capacidad" to "37,73", "campo_numero_serie" to " "),
|
||||
)
|
||||
|
||||
assertEquals("algo", payload["id-marca"])
|
||||
assertEquals(37.73, payload["id-capacidad"])
|
||||
assertFalse(payload.containsKey("id-serie"))
|
||||
assertTrue(payload.keys.none { it.startsWith("campo_") })
|
||||
}
|
||||
}
|
||||
+22
-3
@@ -20,8 +20,15 @@ class FinalFieldFlowContractTest {
|
||||
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\""))
|
||||
assertTrue(acts.contains("Cerrar contenido y pasar a firma"))
|
||||
assertTrue(acts.contains("Nombres y apellidos *"))
|
||||
assertTrue(acts.contains("Cargo / función *"))
|
||||
assertTrue(acts.contains("Email *"))
|
||||
assertTrue(acts.contains("En disconformidad"))
|
||||
assertTrue(acts.contains("Motivo de disconformidad *"))
|
||||
assertTrue(acts.contains("urgencia pertenece al Acta completa"))
|
||||
assertTrue(acts.contains("urgencia no se asigna a cada Hallazgo"))
|
||||
assertTrue(labels.contains("\"LOCKED\" -> \"Para firmar\""))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -45,7 +52,9 @@ class FinalFieldFlowContractTest {
|
||||
fun currentFieldUiDoesNotExposeBackendEnglishStates() {
|
||||
assertTrue(home.contains("visitStatusLabelEs(visit.status)"))
|
||||
assertTrue(findings.contains("findingStatusLabelEs(finding.status)"))
|
||||
assertTrue(acts.contains("documentTypeLabelEs(kind)"))
|
||||
assertTrue(acts.contains("DNI *"))
|
||||
assertFalse(acts.contains("PASSPORT"))
|
||||
assertFalse(acts.contains("OTHER"))
|
||||
assertTrue(labels.contains("\"PASSPORT\" -> \"Pasaporte\""))
|
||||
assertTrue(labels.contains("\"OTHER\" -> \"Otro\""))
|
||||
assertFalse(acts.contains("Finalizar y BLOQUEAR Acta"))
|
||||
@@ -54,4 +63,14 @@ class FinalFieldFlowContractTest {
|
||||
assertFalse(acts.contains("Acta SELLADA"))
|
||||
assertFalse(acts.contains("Text(\"Email\")"))
|
||||
}
|
||||
@Test
|
||||
fun findingCreationIsCompactSearchableAndHasNoCorrectionDate() {
|
||||
assertTrue(findings.contains("ExposedDropdownMenuBox"))
|
||||
assertTrue(findings.contains("Tipo de Hallazgo *"))
|
||||
assertTrue(findings.contains("Buscar o seleccionar"))
|
||||
assertTrue(findings.contains("Otro / No está en la lista"))
|
||||
assertFalse(findings.contains("Fecha de corrección"))
|
||||
assertFalse(findings.contains("Hallazgos del modelo autoritativo"))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -8,8 +8,8 @@ class ReleaseMetadataTest {
|
||||
@Test
|
||||
fun debugBuildKeepsSeparateApplicationIdentity() {
|
||||
assertEquals("com.korexlabs.dhinspeccion.debug", BuildConfig.APPLICATION_ID)
|
||||
assertEquals(30, BuildConfig.VERSION_CODE)
|
||||
assertEquals("0.19.2-debug", BuildConfig.VERSION_NAME)
|
||||
assertEquals(37, BuildConfig.VERSION_CODE)
|
||||
assertEquals("0.19.9-debug", BuildConfig.VERSION_NAME)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "dhv2-api",
|
||||
"version": "0.29.0-2",
|
||||
"version": "0.29.0-7",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "dhv2-api",
|
||||
"version": "0.29.0-2",
|
||||
"version": "0.29.0-7",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^11.0.0",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dhv2-api",
|
||||
"version": "0.29.0-2",
|
||||
"version": "0.29.0-7",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
|
||||
@@ -2,13 +2,14 @@ import { Module } from '@nestjs/common';
|
||||
import { AuditModule } from '../audit/audit.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { PhaseADataModule } from '../core-data/phase-a-data.module';
|
||||
import { InspectionReportsModule } from '../inspection-reports/inspection-reports.module';
|
||||
import { RolesController } from './roles/roles.controller';
|
||||
import { RolesService } from './roles/roles.service';
|
||||
import { UsersController } from './users/users.controller';
|
||||
import { UsersService } from './users/users.service';
|
||||
|
||||
@Module({
|
||||
imports: [PhaseADataModule, AuditModule, AuthModule],
|
||||
imports: [PhaseADataModule, AuditModule, AuthModule, InspectionReportsModule],
|
||||
controllers: [UsersController, RolesController],
|
||||
providers: [UsersService, RolesService],
|
||||
})
|
||||
|
||||
@@ -28,10 +28,9 @@ export class CreateUserDto {
|
||||
@Transform(({ value }) =>
|
||||
typeof value === 'string' && value.trim() ? value.trim().toLowerCase() : null,
|
||||
)
|
||||
@IsOptional()
|
||||
@IsEmail()
|
||||
@MaxLength(320)
|
||||
email?: string | null;
|
||||
email!: string;
|
||||
|
||||
@Transform(({ value }) =>
|
||||
typeof value === 'string' && value.trim() ? value.replace(/\D/g, '') : null,
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Transform } from 'class-transformer';
|
||||
import {
|
||||
IsEmail,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MaxLength,
|
||||
MinLength,
|
||||
} from 'class-validator';
|
||||
|
||||
const optionalText = ({ value }: { value: unknown }) =>
|
||||
typeof value === 'string' && value.trim() ? value.trim() : null;
|
||||
|
||||
export class UpdateSelfProfileDto {
|
||||
@Transform(({ value }) => typeof value === 'string' ? value.trim().toLowerCase() : value)
|
||||
@IsEmail()
|
||||
@MaxLength(320)
|
||||
email!: string;
|
||||
|
||||
@Transform(optionalText)
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(40)
|
||||
phone?: string | null;
|
||||
|
||||
@Transform(optionalText)
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(160)
|
||||
jobTitle?: string | null;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { Transform } from 'class-transformer';
|
||||
import {
|
||||
IsBoolean,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Max,
|
||||
MaxLength,
|
||||
Min,
|
||||
MinLength,
|
||||
ValidateIf,
|
||||
} from 'class-validator';
|
||||
import { SmtpSecurityMode } from '../../../database/entities';
|
||||
|
||||
export enum UserSmtpMode {
|
||||
SYSTEM = 'SYSTEM',
|
||||
CUSTOM = 'CUSTOM',
|
||||
}
|
||||
|
||||
const trimmed = ({ value }: { value: unknown }) =>
|
||||
typeof value === 'string' ? value.trim() : value;
|
||||
|
||||
export class UpdateUserSmtpSettingsDto {
|
||||
@IsEnum(UserSmtpMode)
|
||||
mode!: UserSmtpMode;
|
||||
|
||||
@ValidateIf((dto: UpdateUserSmtpSettingsDto) => dto.mode === UserSmtpMode.CUSTOM)
|
||||
@Transform(trimmed)
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
@MaxLength(255)
|
||||
host?: string;
|
||||
|
||||
@ValidateIf((dto: UpdateUserSmtpSettingsDto) => dto.mode === UserSmtpMode.CUSTOM)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(65535)
|
||||
port?: number;
|
||||
|
||||
@ValidateIf((dto: UpdateUserSmtpSettingsDto) => dto.mode === UserSmtpMode.CUSTOM)
|
||||
@IsEnum(SmtpSecurityMode)
|
||||
securityMode?: SmtpSecurityMode;
|
||||
|
||||
@IsOptional()
|
||||
@Transform(trimmed)
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
username?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(512)
|
||||
password?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@Transform(trimmed)
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
fromName?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
enabled = true;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
ParseUUIDPipe,
|
||||
@@ -9,24 +10,43 @@ import {
|
||||
Put,
|
||||
Query,
|
||||
Req,
|
||||
Res,
|
||||
UploadedFile,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import type { Response } from 'express';
|
||||
import { AuditService } from '../../audit/audit.service';
|
||||
import { RequirePermissions } from '../../authorization/decorators/require-permissions.decorator';
|
||||
import { CurrentAuth } from '../../auth/decorators/current-auth.decorator';
|
||||
import type {
|
||||
AuthPrincipal,
|
||||
RequestWithContext,
|
||||
} from '../../common/http/request-context';
|
||||
import { AuditAction } from '../../database/entities';
|
||||
import { SmtpDeliveryService } from '../../inspection-reports/smtp-delivery.service';
|
||||
import {
|
||||
MAX_INSPECTION_SIGNATURE_BYTES,
|
||||
type UploadedInspectionSignatureFile,
|
||||
} from '../../inspection-closing/inspection-signature-file';
|
||||
import { administrationAuditContext } from '../common/administration-audit';
|
||||
import { ChangeUserStatusDto } from './dto/change-user-status.dto';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { ListUsersQueryDto } from './dto/list-users-query.dto';
|
||||
import { ReplaceUserRolesDto } from './dto/replace-user-roles.dto';
|
||||
import { ResetUserPasswordDto } from './dto/reset-user-password.dto';
|
||||
import { UpdateSelfProfileDto } from './dto/update-self-profile.dto';
|
||||
import { UpdateUserSmtpSettingsDto } from './dto/update-user-smtp-settings.dto';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
@Controller('users')
|
||||
export class UsersController {
|
||||
constructor(private readonly users: UsersService) {}
|
||||
constructor(
|
||||
private readonly users: UsersService,
|
||||
private readonly smtp: SmtpDeliveryService,
|
||||
private readonly audit: AuditService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@RequirePermissions('users.read')
|
||||
@@ -34,6 +54,112 @@ export class UsersController {
|
||||
return this.users.list(query);
|
||||
}
|
||||
|
||||
@Get('self/profile')
|
||||
selfProfile(@CurrentAuth() principal: AuthPrincipal) {
|
||||
return this.users.getSelfProfile(principal.userId);
|
||||
}
|
||||
|
||||
@Patch('self/profile')
|
||||
updateSelfProfile(
|
||||
@Body() dto: UpdateSelfProfileDto,
|
||||
@CurrentAuth() principal: AuthPrincipal,
|
||||
@Req() request: RequestWithContext,
|
||||
) {
|
||||
return this.users.updateSelfProfile(dto, principal, request);
|
||||
}
|
||||
|
||||
@Get('self/signature')
|
||||
selfSignature(@CurrentAuth() principal: AuthPrincipal) {
|
||||
return this.users.getSelfSignature(principal.userId);
|
||||
}
|
||||
|
||||
@Get('self/signature/content')
|
||||
async selfSignatureContent(
|
||||
@CurrentAuth() principal: AuthPrincipal,
|
||||
@Res() response: Response,
|
||||
): Promise<void> {
|
||||
const signature = await this.users.getSelfSignatureContent(principal.userId);
|
||||
response.setHeader('Content-Type', 'image/png');
|
||||
response.setHeader('Content-Length', String(signature.buffer.length));
|
||||
response.setHeader('Cache-Control', 'private, no-store');
|
||||
response.setHeader('ETag', `"${signature.sha256}"`);
|
||||
response.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
response.send(signature.buffer);
|
||||
}
|
||||
|
||||
@Put('self/signature')
|
||||
@UseInterceptors(FileInterceptor('file', {
|
||||
limits: { fileSize: MAX_INSPECTION_SIGNATURE_BYTES, files: 1 },
|
||||
}))
|
||||
updateSelfSignature(
|
||||
@UploadedFile() file: UploadedInspectionSignatureFile | undefined,
|
||||
@CurrentAuth() principal: AuthPrincipal,
|
||||
@Req() request: RequestWithContext,
|
||||
) {
|
||||
return this.users.updateSelfSignature(file, principal, request);
|
||||
}
|
||||
|
||||
@Delete('self/signature')
|
||||
deleteSelfSignature(
|
||||
@CurrentAuth() principal: AuthPrincipal,
|
||||
@Req() request: RequestWithContext,
|
||||
) {
|
||||
return this.users.deleteSelfSignature(principal, request);
|
||||
}
|
||||
|
||||
@Get('self/smtp')
|
||||
selfSmtp(@CurrentAuth() principal: AuthPrincipal) {
|
||||
return this.smtp.publicUserSettings(principal.userId);
|
||||
}
|
||||
|
||||
@Put('self/smtp')
|
||||
async updateSelfSmtp(
|
||||
@Body() dto: UpdateUserSmtpSettingsDto,
|
||||
@CurrentAuth() principal: AuthPrincipal,
|
||||
@Req() request: RequestWithContext,
|
||||
) {
|
||||
const before = await this.smtp.publicUserSettings(principal.userId);
|
||||
const after = await this.smtp.saveUserSettings(principal.userId, dto);
|
||||
await this.audit.record({
|
||||
...administrationAuditContext(principal, request),
|
||||
action: AuditAction.USER_SMTP_SETTINGS_UPDATED,
|
||||
entityType: 'user_smtp_settings',
|
||||
entityId: principal.userId,
|
||||
beforeData: before as Record<string, unknown>,
|
||||
afterData: after as Record<string, unknown>,
|
||||
metadata: { passwordNeverReturned: true, scope: 'SELF' },
|
||||
});
|
||||
return after;
|
||||
}
|
||||
|
||||
@Post('self/smtp/test')
|
||||
async testSelfSmtp(
|
||||
@CurrentAuth() principal: AuthPrincipal,
|
||||
@Req() request: RequestWithContext,
|
||||
) {
|
||||
const profile = await this.users.getSelfProfile(principal.userId);
|
||||
if (!profile.email) throw new Error('El usuario no tiene email configurado');
|
||||
const sent = await this.smtp.send({
|
||||
to: profile.email,
|
||||
subject: 'DH Inspección · Prueba de correo personal',
|
||||
text: 'Este correo confirma que tu configuración de correo en DH Inspección funciona correctamente.',
|
||||
attachment: {
|
||||
filename: 'dh-inspeccion-prueba-correo.txt',
|
||||
mimeType: 'text/plain',
|
||||
content: Buffer.from('DH Inspección · Correo personal OK\n', 'utf8'),
|
||||
},
|
||||
}, principal.userId);
|
||||
await this.audit.record({
|
||||
...administrationAuditContext(principal, request),
|
||||
action: AuditAction.USER_SMTP_TEST_SENT,
|
||||
entityType: 'user_smtp_settings',
|
||||
entityId: principal.userId,
|
||||
afterData: { recipient: profile.email, messageId: sent.messageId },
|
||||
metadata: { scope: 'SELF' },
|
||||
});
|
||||
return { ok: true, recipient: profile.email, messageId: sent.messageId };
|
||||
}
|
||||
|
||||
@Post()
|
||||
@RequirePermissions('users.create')
|
||||
create(
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
@@ -29,7 +31,12 @@ import type { CreateUserDto } from './dto/create-user.dto';
|
||||
import type { ListUsersQueryDto } from './dto/list-users-query.dto';
|
||||
import type { ReplaceUserRolesDto } from './dto/replace-user-roles.dto';
|
||||
import type { ResetUserPasswordDto } from './dto/reset-user-password.dto';
|
||||
import type { UpdateSelfProfileDto } from './dto/update-self-profile.dto';
|
||||
import type { UpdateUserDto } from './dto/update-user.dto';
|
||||
import {
|
||||
inspectInspectionSignatureFile,
|
||||
type UploadedInspectionSignatureFile,
|
||||
} from '../../inspection-closing/inspection-signature-file';
|
||||
|
||||
export interface UserRoleView {
|
||||
id: string;
|
||||
@@ -37,6 +44,14 @@ export interface UserRoleView {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface UserReusableSignatureView {
|
||||
configured: boolean;
|
||||
mimeType: 'image/png' | null;
|
||||
sizeBytes: number | null;
|
||||
imageSha256: string | null;
|
||||
updatedAt: Date | null;
|
||||
}
|
||||
|
||||
export interface AdministrativeUserView {
|
||||
id: string;
|
||||
username: string;
|
||||
@@ -56,6 +71,7 @@ export interface AdministrativeUserView {
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
roles: UserRoleView[];
|
||||
smtpMode: 'SYSTEM' | 'CUSTOM';
|
||||
}
|
||||
|
||||
interface UserViewRow extends AdministrativeUserView {
|
||||
@@ -76,10 +92,10 @@ function roleSelectionInvalid(): BadRequestException {
|
||||
});
|
||||
}
|
||||
|
||||
function inspectorEmailRequired(): BadRequestException {
|
||||
function userEmailRequired(): BadRequestException {
|
||||
return new BadRequestException({
|
||||
code: 'INSPECTOR_EMAIL_REQUIRED',
|
||||
message: 'Los usuarios con rol Inspector deben tener un email válido para recibir la documentación de sus inspecciones',
|
||||
code: 'USER_EMAIL_REQUIRED',
|
||||
message: 'Cada usuario de Hidrocarburos debe tener un email válido',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -144,6 +160,7 @@ export class UsersService {
|
||||
user_account.password_changed_at AS "passwordChangedAt",
|
||||
user_account.created_at AS "createdAt",
|
||||
user_account.updated_at AS "updatedAt",
|
||||
COALESCE((SELECT mode FROM user_smtp_settings WHERE user_id=user_account.id),'SYSTEM') AS "smtpMode",
|
||||
COALESCE(
|
||||
JSONB_AGG(
|
||||
JSONB_BUILD_OBJECT(
|
||||
@@ -185,6 +202,105 @@ export class UsersService {
|
||||
);
|
||||
}
|
||||
|
||||
async getSelfProfile(userId: string): Promise<AdministrativeUserView> {
|
||||
return this.getById(userId);
|
||||
}
|
||||
|
||||
async getSelfSignature(userId: string): Promise<UserReusableSignatureView> {
|
||||
const [row] = (await this.dataSource.query(`
|
||||
SELECT mime_type AS "mimeType", size_bytes AS "sizeBytes",
|
||||
image_sha256 AS "imageSha256", updated_at AS "updatedAt"
|
||||
FROM user_signature_profiles WHERE user_id=$1
|
||||
`, [userId])) as Array<{
|
||||
mimeType: 'image/png'; sizeBytes: number; imageSha256: string; updatedAt: Date;
|
||||
}>;
|
||||
return row ? { configured: true, ...row } : {
|
||||
configured: false, mimeType: null, sizeBytes: null, imageSha256: null, updatedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
async getSelfSignatureContent(userId: string): Promise<{ buffer: Buffer; sha256: string }> {
|
||||
const [row] = (await this.dataSource.query(`
|
||||
SELECT image_data AS buffer, image_sha256 AS sha256
|
||||
FROM user_signature_profiles WHERE user_id=$1
|
||||
`, [userId])) as Array<{ buffer: Buffer; sha256: string }>;
|
||||
if (!row) throw new NotFoundException({
|
||||
code: 'USER_SIGNATURE_NOT_CONFIGURED',
|
||||
message: 'Todavía no cargaste tu firma de inspector',
|
||||
});
|
||||
return row;
|
||||
}
|
||||
|
||||
async updateSelfSignature(
|
||||
file: UploadedInspectionSignatureFile | undefined,
|
||||
principal: AuthPrincipal,
|
||||
request: RequestWithContext,
|
||||
): Promise<UserReusableSignatureView> {
|
||||
if (!principal.roles.includes('inspector')) throw new ForbiddenException({
|
||||
code: 'INSPECTOR_SIGNATURE_ROLE_REQUIRED',
|
||||
message: 'La firma reutilizable está disponible para usuarios con rol Inspector',
|
||||
});
|
||||
const inspected = inspectInspectionSignatureFile(file);
|
||||
const imageSha256 = createHash('sha256').update(file!.buffer).digest('hex');
|
||||
const before = await this.getSelfSignature(principal.userId);
|
||||
await this.dataSource.transaction(async (manager) => {
|
||||
await manager.query(`
|
||||
INSERT INTO user_signature_profiles (
|
||||
user_id,original_name,mime_type,size_bytes,image_sha256,image_data,updated_by
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$1)
|
||||
ON CONFLICT (user_id) DO UPDATE SET
|
||||
original_name=EXCLUDED.original_name, mime_type=EXCLUDED.mime_type,
|
||||
size_bytes=EXCLUDED.size_bytes, image_sha256=EXCLUDED.image_sha256,
|
||||
image_data=EXCLUDED.image_data, updated_by=EXCLUDED.updated_by,
|
||||
updated_at=CURRENT_TIMESTAMP
|
||||
`, [principal.userId, inspected.originalName, inspected.mimeType, file!.buffer.length, imageSha256, file!.buffer]);
|
||||
await this.audit.record({
|
||||
...administrationAuditContext(principal, request),
|
||||
action: AuditAction.USER_UPDATED,
|
||||
entityType: 'user_signature_profile',
|
||||
entityId: principal.userId,
|
||||
beforeData: before as unknown as Record<string, unknown>,
|
||||
afterData: { configured: true, imageSha256, sizeBytes: file!.buffer.length },
|
||||
metadata: { scope: 'SELF_SIGNATURE', reusableForActs: true },
|
||||
}, manager);
|
||||
});
|
||||
return this.getSelfSignature(principal.userId);
|
||||
}
|
||||
|
||||
async deleteSelfSignature(
|
||||
principal: AuthPrincipal,
|
||||
request: RequestWithContext,
|
||||
): Promise<UserReusableSignatureView> {
|
||||
const before = await this.getSelfSignature(principal.userId);
|
||||
await this.dataSource.transaction(async (manager) => {
|
||||
await manager.query('DELETE FROM user_signature_profiles WHERE user_id=$1', [principal.userId]);
|
||||
await this.audit.record({
|
||||
...administrationAuditContext(principal, request),
|
||||
action: AuditAction.USER_UPDATED,
|
||||
entityType: 'user_signature_profile',
|
||||
entityId: principal.userId,
|
||||
beforeData: before as unknown as Record<string, unknown>,
|
||||
afterData: { configured: false },
|
||||
metadata: { scope: 'SELF_SIGNATURE', reusableForActs: true },
|
||||
}, manager);
|
||||
});
|
||||
return this.getSelfSignature(principal.userId);
|
||||
}
|
||||
|
||||
async updateSelfProfile(
|
||||
dto: UpdateSelfProfileDto,
|
||||
principal: AuthPrincipal,
|
||||
request: RequestWithContext,
|
||||
): Promise<AdministrativeUserView> {
|
||||
if (!dto.email?.trim()) throw userEmailRequired();
|
||||
return this.update(
|
||||
principal.userId,
|
||||
{ email: dto.email, phone: dto.phone, jobTitle: dto.jobTitle },
|
||||
principal,
|
||||
request,
|
||||
);
|
||||
}
|
||||
|
||||
async create(
|
||||
dto: CreateUserDto,
|
||||
principal: AuthPrincipal,
|
||||
@@ -195,10 +311,10 @@ export class UsersService {
|
||||
try {
|
||||
return await this.dataSource.transaction(async (manager) => {
|
||||
const roles = await this.resolveRoles(manager, dto.roleIds);
|
||||
this.assertInspectorHasEmail(roles, dto.email ?? null);
|
||||
if (!dto.email?.trim()) throw userEmailRequired();
|
||||
const user = manager.getRepository(User).create({
|
||||
username: dto.username.trim().toLowerCase(),
|
||||
email: dto.email?.trim().toLowerCase() || null,
|
||||
email: dto.email.trim().toLowerCase(),
|
||||
dni: dto.dni ?? null,
|
||||
phone: dto.phone ?? null,
|
||||
jobTitle: dto.jobTitle ?? null,
|
||||
@@ -268,15 +384,13 @@ export class UsersService {
|
||||
return await this.dataSource.transaction(async (manager) => {
|
||||
const user = await this.lockUser(manager, id);
|
||||
const before = await this.loadUserView(manager, id);
|
||||
if (dto.email !== undefined && !dto.email && before.roles.some((role) => role.code === 'inspector')) {
|
||||
throw inspectorEmailRequired();
|
||||
}
|
||||
if (dto.email !== undefined && !dto.email) throw userEmailRequired();
|
||||
|
||||
if (dto.username !== undefined) {
|
||||
user.username = dto.username.trim().toLowerCase();
|
||||
}
|
||||
if (dto.email !== undefined) {
|
||||
user.email = dto.email?.trim().toLowerCase() || null;
|
||||
user.email = dto.email!.trim().toLowerCase();
|
||||
}
|
||||
if (dto.dni !== undefined) user.dni = dto.dni ?? null;
|
||||
if (dto.phone !== undefined) user.phone = dto.phone ?? null;
|
||||
@@ -286,6 +400,13 @@ export class UsersService {
|
||||
if (dto.lastName !== undefined) user.lastName = dto.lastName.trim();
|
||||
user.updatedBy = principal.userId;
|
||||
await manager.getRepository(User).save(user);
|
||||
if (dto.email !== undefined && user.email) {
|
||||
await manager.query(`
|
||||
UPDATE user_smtp_settings
|
||||
SET from_email=$2,reply_to=$2,updated_by=$1,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE user_id=$1 AND mode='CUSTOM'
|
||||
`, [id, user.email]);
|
||||
}
|
||||
|
||||
const updated = await this.loadUserView(manager, id);
|
||||
await this.audit.record(
|
||||
@@ -414,7 +535,6 @@ export class UsersService {
|
||||
await this.lockUser(manager, id);
|
||||
const roles = await this.resolveRoles(manager, dto.roleIds);
|
||||
const before = await this.loadUserView(manager, id);
|
||||
this.assertInspectorHasEmail(roles, before.email);
|
||||
const beforeIds = before.roles.map((role) => role.id).sort();
|
||||
const afterIds = roles.map((role) => role.id).sort();
|
||||
if (beforeIds.join(',') === afterIds.join(',')) return before;
|
||||
@@ -453,12 +573,6 @@ export class UsersService {
|
||||
return roles;
|
||||
}
|
||||
|
||||
private assertInspectorHasEmail(roles: Role[], email: string | null | undefined): void {
|
||||
if (roles.some((role) => role.code === 'inspector') && !email?.trim()) {
|
||||
throw inspectorEmailRequired();
|
||||
}
|
||||
}
|
||||
|
||||
private async insertUserRoles(
|
||||
manager: EntityManager,
|
||||
userId: string,
|
||||
@@ -511,6 +625,7 @@ export class UsersService {
|
||||
user_account.password_changed_at AS "passwordChangedAt",
|
||||
user_account.created_at AS "createdAt",
|
||||
user_account.updated_at AS "updatedAt",
|
||||
COALESCE((SELECT mode FROM user_smtp_settings WHERE user_id=user_account.id),'SYSTEM') AS "smtpMode",
|
||||
COALESCE(
|
||||
JSONB_AGG(
|
||||
JSONB_BUILD_OBJECT(
|
||||
|
||||
@@ -760,6 +760,7 @@ export class AssetsService {
|
||||
parentId: dto.parentId,
|
||||
operationalAreaId: dto.operationalAreaId,
|
||||
operatorCompanyId: dto.operatorCompanyId,
|
||||
inventoryFamilyId: dto.inventoryFamilyId ?? null,
|
||||
code: dto.code,
|
||||
name: dto.name,
|
||||
commonName: dto.commonName ?? null,
|
||||
|
||||
@@ -36,6 +36,10 @@ export class CreateFieldDiscoveryDto {
|
||||
@IsUUID('4')
|
||||
operatorCompanyId!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsUUID('4')
|
||||
inventoryFamilyId?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@Transform(({ value }) => typeof value === 'string' && value.trim() ? value.trim() : null)
|
||||
@IsString()
|
||||
|
||||
@@ -118,10 +118,9 @@ async function main(): Promise<void> {
|
||||
);
|
||||
}
|
||||
|
||||
email = (await prompt.question('Email (optional): ')).trim().toLowerCase();
|
||||
email = (await prompt.question('Email: ')).trim().toLowerCase();
|
||||
if (
|
||||
email &&
|
||||
(email.length > 320 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
|
||||
!email || email.length > 320 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
|
||||
) {
|
||||
throw new Error('Email is invalid');
|
||||
}
|
||||
@@ -189,7 +188,7 @@ async function main(): Promise<void> {
|
||||
OR ($2::text IS NOT NULL AND LOWER(email) = $2)
|
||||
LIMIT 1
|
||||
`,
|
||||
[username, email || null],
|
||||
[username, email],
|
||||
)) as unknown[];
|
||||
if (duplicate.length > 0) {
|
||||
throw new Error('Username or email already exists');
|
||||
@@ -202,7 +201,7 @@ async function main(): Promise<void> {
|
||||
|
||||
const user = manager.getRepository(User).create({
|
||||
username,
|
||||
email: email || null,
|
||||
email,
|
||||
passwordHash,
|
||||
firstName,
|
||||
lastName,
|
||||
|
||||
@@ -103,6 +103,8 @@ export enum AuditAction {
|
||||
INSPECTION_BUSINESS_CALENDAR_UPDATED = 'INSPECTION_BUSINESS_CALENDAR_UPDATED',
|
||||
SMTP_SETTINGS_UPDATED = 'SMTP_SETTINGS_UPDATED',
|
||||
SMTP_TEST_SENT = 'SMTP_TEST_SENT',
|
||||
USER_SMTP_SETTINGS_UPDATED = 'USER_SMTP_SETTINGS_UPDATED',
|
||||
USER_SMTP_TEST_SENT = 'USER_SMTP_TEST_SENT',
|
||||
DOCUMENT_DELIVERY_SETTINGS_UPDATED = 'DOCUMENT_DELIVERY_SETTINGS_UPDATED',
|
||||
DOCUMENT_DELIVERY_RETRY_REQUESTED = 'DOCUMENT_DELIVERY_RETRY_REQUESTED',
|
||||
DOCUMENT_DELIVERY_SENT = 'DOCUMENT_DELIVERY_SENT',
|
||||
|
||||
@@ -16,8 +16,8 @@ export class User extends TimestampedEntity {
|
||||
@Column({ type: 'varchar', length: 80 })
|
||||
username!: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 320, nullable: true })
|
||||
email!: string | null;
|
||||
@Column({ type: 'varchar', length: 320 })
|
||||
email!: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 32, nullable: true })
|
||||
dni!: string | null;
|
||||
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
function quoteIdentifier(identifier: string): string {
|
||||
return `"${identifier.replaceAll('"', '""')}"`;
|
||||
}
|
||||
|
||||
export class F62UserSmtpAndActRepresentative1790117400000 implements MigrationInterface {
|
||||
name = 'F62UserSmtpAndActRepresentative1790117400000';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM users WHERE email IS NULL OR btrim(email)='') THEN
|
||||
RAISE EXCEPTION 'USER_EMAIL_REQUIRED_BEFORE_F62';
|
||||
END IF;
|
||||
END $$
|
||||
`);
|
||||
await queryRunner.query(`ALTER TABLE users ALTER COLUMN email SET NOT NULL`);
|
||||
|
||||
await queryRunner.query(`
|
||||
CREATE TABLE user_smtp_settings (
|
||||
user_id uuid PRIMARY KEY,
|
||||
mode varchar(16) NOT NULL DEFAULT 'SYSTEM',
|
||||
host varchar(255),
|
||||
port integer,
|
||||
security_mode varchar(24),
|
||||
username varchar(255),
|
||||
password_enc text,
|
||||
from_name varchar(200),
|
||||
from_email varchar(320),
|
||||
reply_to varchar(320),
|
||||
enabled boolean NOT NULL DEFAULT true,
|
||||
updated_by uuid,
|
||||
created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT chk_user_smtp_mode CHECK (mode IN ('SYSTEM','CUSTOM')),
|
||||
CONSTRAINT chk_user_smtp_security CHECK (security_mode IS NULL OR security_mode IN ('NONE','STARTTLS','TLS')),
|
||||
CONSTRAINT chk_user_smtp_port CHECK (port IS NULL OR (port > 0 AND port <= 65535)),
|
||||
CONSTRAINT chk_user_smtp_custom_complete CHECK (
|
||||
mode='SYSTEM' OR (
|
||||
LENGTH(TRIM(COALESCE(host,''))) > 0
|
||||
AND port IS NOT NULL
|
||||
AND security_mode IS NOT NULL
|
||||
AND LENGTH(TRIM(COALESCE(from_email,''))) > 0
|
||||
)
|
||||
),
|
||||
CONSTRAINT fk_user_smtp_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_user_smtp_updated_by FOREIGN KEY (updated_by) REFERENCES users(id) ON DELETE SET NULL
|
||||
)
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE inspection_act_responsibles
|
||||
DROP CONSTRAINT chk_inspection_act_responsibles_details
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE inspection_act_responsibles
|
||||
ADD CONSTRAINT chk_inspection_act_responsibles_details CHECK (
|
||||
(
|
||||
attendance_status = 'PRESENT'
|
||||
AND LENGTH(TRIM(COALESCE(full_name, ''))) > 0
|
||||
AND document_type IS NOT NULL
|
||||
AND LENGTH(TRIM(COALESCE(document_number, ''))) > 0
|
||||
AND LENGTH(TRIM(COALESCE(position, ''))) > 0
|
||||
AND LENGTH(TRIM(COALESCE(email, ''))) > 0
|
||||
AND absence_reason IS NULL
|
||||
) OR (
|
||||
attendance_status = 'ABSENT'
|
||||
AND LENGTH(TRIM(COALESCE(absence_reason, ''))) >= 10
|
||||
)
|
||||
)
|
||||
`);
|
||||
|
||||
const appRole = process.env.DB_APP_USER;
|
||||
if (!appRole) throw new Error('Missing required environment variable: DB_APP_USER');
|
||||
const applicationRole = quoteIdentifier(appRole);
|
||||
await queryRunner.query(`GRANT SELECT, INSERT, UPDATE ON TABLE user_smtp_settings TO ${applicationRole}`);
|
||||
await queryRunner.query(`REVOKE DELETE ON TABLE user_smtp_settings FROM ${applicationRole}`);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE inspection_act_responsibles
|
||||
DROP CONSTRAINT chk_inspection_act_responsibles_details
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE inspection_act_responsibles
|
||||
ADD CONSTRAINT chk_inspection_act_responsibles_details CHECK (
|
||||
(
|
||||
attendance_status = 'PRESENT'
|
||||
AND LENGTH(TRIM(COALESCE(full_name, ''))) > 0
|
||||
AND document_type IS NOT NULL
|
||||
AND LENGTH(TRIM(COALESCE(document_number, ''))) > 0
|
||||
AND LENGTH(TRIM(COALESCE(position, ''))) > 0
|
||||
AND absence_reason IS NULL
|
||||
) OR (
|
||||
attendance_status = 'ABSENT'
|
||||
AND LENGTH(TRIM(COALESCE(absence_reason, ''))) >= 10
|
||||
)
|
||||
)
|
||||
`);
|
||||
await queryRunner.query(`DROP TABLE IF EXISTS user_smtp_settings`);
|
||||
await queryRunner.query(`ALTER TABLE users ALTER COLUMN email DROP NOT NULL`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
/**
|
||||
* F4 cambió el código visible del Acta a ACT-NNNNN-DD-MM-YY, pero el CHECK
|
||||
* histórico de Hallazgos seguía aceptando sólo ACTA-YYYY-NNNNNN-HNNN.
|
||||
* El servicio genera el Hallazgo a partir del código real del Acta, por lo que
|
||||
* PostgreSQL rechazaba altas válidas de campo con un 500.
|
||||
*/
|
||||
export class F65FieldFindingCodeContract1790121000000 implements MigrationInterface {
|
||||
name = 'F65FieldFindingCodeContract1790121000000';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE inspection_findings
|
||||
DROP CONSTRAINT IF EXISTS chk_inspection_findings_code
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE inspection_findings
|
||||
ADD CONSTRAINT chk_inspection_findings_code CHECK (
|
||||
code ~ '^(ACTA-[0-9]{4}-[0-9]{6}|ACT-[0-9]{5}-[0-9]{2}-[0-9]{2}-[0-9]{2})-H[0-9]{3}$'
|
||||
)
|
||||
`);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
UPDATE inspection_findings finding
|
||||
SET code = 'ACTA-' || act.act_year::text || '-' || LPAD(act.act_number::text, 6, '0')
|
||||
|| '-H' || LPAD(finding.finding_number::text, 3, '0')
|
||||
FROM inspection_acts act
|
||||
WHERE finding.act_id = act.id
|
||||
AND finding.code ~ '^ACT-[0-9]{5}-[0-9]{2}-[0-9]{2}-[0-9]{2}-H[0-9]{3}$'
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE inspection_findings
|
||||
DROP CONSTRAINT IF EXISTS chk_inspection_findings_code
|
||||
`);
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE inspection_findings
|
||||
ADD CONSTRAINT chk_inspection_findings_code CHECK (
|
||||
code ~ '^ACTA-[0-9]{4}-[0-9]{6}-H[0-9]{3}$'
|
||||
)
|
||||
`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
function quoteIdentifier(identifier: string): string {
|
||||
return `"${identifier.replaceAll('"', '""')}"`;
|
||||
}
|
||||
|
||||
export class F67UserReusableSignature1790124600000 implements MigrationInterface {
|
||||
name = 'F67UserReusableSignature1790124600000';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
CREATE TABLE user_signature_profiles (
|
||||
user_id uuid PRIMARY KEY,
|
||||
original_name varchar(255) NOT NULL,
|
||||
mime_type varchar(100) NOT NULL,
|
||||
size_bytes integer NOT NULL,
|
||||
image_sha256 char(64) NOT NULL,
|
||||
image_data bytea NOT NULL,
|
||||
updated_by uuid,
|
||||
created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT chk_user_signature_profiles_png CHECK (mime_type='image/png'),
|
||||
CONSTRAINT chk_user_signature_profiles_size CHECK (
|
||||
size_bytes BETWEEN 1 AND 1048576
|
||||
AND OCTET_LENGTH(image_data)=size_bytes
|
||||
),
|
||||
CONSTRAINT chk_user_signature_profiles_sha CHECK (
|
||||
image_sha256 ~ '^[0-9a-f]{64}$'
|
||||
),
|
||||
CONSTRAINT fk_user_signature_profiles_user FOREIGN KEY (user_id)
|
||||
REFERENCES users(id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_user_signature_profiles_updated_by FOREIGN KEY (updated_by)
|
||||
REFERENCES users(id) ON DELETE SET NULL
|
||||
)
|
||||
`);
|
||||
const appRole = process.env.DB_APP_USER;
|
||||
if (!appRole) throw new Error('Missing required environment variable: DB_APP_USER');
|
||||
const applicationRole = quoteIdentifier(appRole);
|
||||
await queryRunner.query(`
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE
|
||||
ON TABLE user_signature_profiles
|
||||
TO ${applicationRole}
|
||||
`);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query('DROP TABLE user_signature_profiles');
|
||||
}
|
||||
}
|
||||
@@ -728,10 +728,13 @@ export class InspectionActsService {
|
||||
principal: AuthPrincipal,
|
||||
): Promise<number> {
|
||||
const [row] = (await manager.query(`
|
||||
UPDATE inspection_acts
|
||||
SET current_version = current_version + 1
|
||||
WHERE id = $1
|
||||
RETURNING current_version AS "versionNumber"
|
||||
WITH updated AS (
|
||||
UPDATE inspection_acts
|
||||
SET current_version = current_version + 1
|
||||
WHERE id = $1
|
||||
RETURNING current_version
|
||||
)
|
||||
SELECT current_version AS "versionNumber" FROM updated
|
||||
`, [act.id])) as Array<{ versionNumber: number }>;
|
||||
const versionNumber = Number(row.versionNumber);
|
||||
act.currentVersion = versionNumber;
|
||||
|
||||
@@ -213,14 +213,14 @@ export class CompanySignatureInviteService {
|
||||
|
||||
if (!publicUrl) {
|
||||
deliveryError = 'COMPANY_SIGNATURE_PUBLIC_BASE_URL no configurada';
|
||||
} else if (!(await this.smtp.configured())) {
|
||||
} else if (!(await this.smtp.configured(principal.userId))) {
|
||||
deliveryError = 'SMTP no configurado';
|
||||
} else {
|
||||
const body = [
|
||||
`Se solicita revisar y manifestarse sobre el Acta ${created.actCode}.`,
|
||||
`Inspección: ${created.inspectionCode}.`,
|
||||
'',
|
||||
'El enlace permite firmar en conformidad, firmar en disidencia o registrar una negativa a firmar.',
|
||||
'El enlace permite firmar en conformidad, firmar en disconformidad o registrar una negativa a firmar.',
|
||||
'El contenido del Acta está bloqueado y no puede modificarse desde este enlace.',
|
||||
'',
|
||||
`Enlace seguro: ${publicUrl}`,
|
||||
@@ -236,7 +236,7 @@ export class CompanySignatureInviteService {
|
||||
mimeType: 'text/plain',
|
||||
content: Buffer.from(body, 'utf8'),
|
||||
},
|
||||
});
|
||||
}, principal.userId);
|
||||
emailSent = true;
|
||||
await this.dataSource.query(`
|
||||
UPDATE inspection_act_company_signature_invites
|
||||
|
||||
@@ -54,7 +54,9 @@ export class UpsertInspectionResponsibleDto {
|
||||
@MaxLength(200)
|
||||
position?: string;
|
||||
|
||||
@IsOptional()
|
||||
@ValidateIf((dto: UpsertInspectionResponsibleDto) => (
|
||||
dto.attendanceStatus === InspectionResponsibleAttendanceStatus.PRESENT
|
||||
))
|
||||
@Transform(trimOrUndefined)
|
||||
@IsEmail()
|
||||
@MaxLength(320)
|
||||
|
||||
@@ -103,6 +103,14 @@ interface StoredSignature extends SignatureView {
|
||||
storedName: string | null;
|
||||
}
|
||||
|
||||
interface ReusableInspectorSignature {
|
||||
originalName: string;
|
||||
mimeType: 'image/png';
|
||||
sizeBytes: number;
|
||||
imageSha256: string;
|
||||
imageData: Buffer;
|
||||
}
|
||||
|
||||
interface ClosureRecord {
|
||||
actId: string;
|
||||
schemaVersion: string;
|
||||
@@ -152,6 +160,7 @@ export interface InspectionClosureView {
|
||||
actualClosedAt: Date | null;
|
||||
};
|
||||
responsible: ResponsibleView | null;
|
||||
representativeSuggestion: ResponsibleView | null;
|
||||
closure: null | {
|
||||
schemaVersion: string;
|
||||
preparedSha256: string;
|
||||
@@ -305,21 +314,24 @@ export class InspectionClosingService {
|
||||
const lockedAt = new Date();
|
||||
|
||||
const [updated] = (await manager.query(`
|
||||
UPDATE inspection_acts
|
||||
SET status='LOCKED',
|
||||
urgency=$2,
|
||||
deadline_days=$3,
|
||||
deadline_day_type=$4,
|
||||
deadline_basis=$5,
|
||||
deadline_base_at=$6,
|
||||
deadline_at=$7,
|
||||
locked_at=$8,
|
||||
locked_by=$9,
|
||||
current_version=current_version+1,
|
||||
updated_by=$9,
|
||||
updated_at=$8
|
||||
WHERE id=$1
|
||||
RETURNING current_version AS "versionNumber"
|
||||
WITH updated AS (
|
||||
UPDATE inspection_acts
|
||||
SET status='LOCKED',
|
||||
urgency=$2,
|
||||
deadline_days=$3,
|
||||
deadline_day_type=$4,
|
||||
deadline_basis=$5,
|
||||
deadline_base_at=$6,
|
||||
deadline_at=$7,
|
||||
locked_at=$8,
|
||||
locked_by=$9,
|
||||
current_version=current_version+1,
|
||||
updated_by=$9,
|
||||
updated_at=$8
|
||||
WHERE id=$1
|
||||
RETURNING current_version
|
||||
)
|
||||
SELECT current_version AS "versionNumber" FROM updated
|
||||
`, [
|
||||
actId,
|
||||
dto.urgency,
|
||||
@@ -376,7 +388,7 @@ export class InspectionClosingService {
|
||||
afterData: {
|
||||
status: InspectionActStatus.LOCKED,
|
||||
lockedSha256: preparedSha256,
|
||||
urgency: act.urgency,
|
||||
urgency: dto.urgency,
|
||||
deadlineDays,
|
||||
deadlineDayType,
|
||||
deadlineBasis,
|
||||
@@ -460,6 +472,13 @@ export class InspectionClosingService {
|
||||
message: 'La negativa a firmar requiere identificar al responsable que se negó',
|
||||
});
|
||||
}
|
||||
if (dto.status === InspectionActSignatureStatus.ABSENT
|
||||
&& responsible.attendanceStatus !== InspectionResponsibleAttendanceStatus.ABSENT) {
|
||||
throw new BadRequestException({
|
||||
code: 'INSPECTION_COMPANY_ABSENCE_REQUIRES_ABSENT_RESPONSIBLE',
|
||||
message: 'La ausencia sólo puede confirmarse cuando el representante fue registrado como ausente',
|
||||
});
|
||||
}
|
||||
if (await this.hasCompanyOutcome(manager, actId)) {
|
||||
throw new ConflictException({
|
||||
code: 'INSPECTION_ACT_COMPANY_OUTCOME_ALREADY_RECORDED',
|
||||
@@ -531,22 +550,15 @@ export class InspectionClosingService {
|
||||
request: RequestWithContext,
|
||||
): Promise<InspectionClosureView> {
|
||||
assertMobileInspector(principal);
|
||||
const sealed = await this.dataSource.transaction(async (manager) => {
|
||||
let generatedInspectorSignaturePath: string | null = null;
|
||||
let sealed: InspectionClosureView;
|
||||
try {
|
||||
sealed = await this.dataSource.transaction(async (manager) => {
|
||||
const { act, visit } = await this.lockContext(manager, actId);
|
||||
this.assertLockedForManifestation(act);
|
||||
await this.assertActorAssigned(manager, visit.id, principal, true);
|
||||
const closure = await this.requireClosure(manager, actId);
|
||||
const signatures = await this.loadSignatures(manager, actId);
|
||||
const inspectorSigned = signatures.some((item) =>
|
||||
item.signerType === InspectionActSignerType.INSPECTOR
|
||||
&& item.status === InspectionActSignatureStatus.SIGNED,
|
||||
);
|
||||
if (!inspectorSigned) {
|
||||
throw new ConflictException({
|
||||
code: 'INSPECTION_ACT_INSPECTOR_SIGNATURE_REQUIRED',
|
||||
message: 'Se requiere la firma del inspector para sellar el acta',
|
||||
});
|
||||
}
|
||||
let signatures = await this.loadSignatures(manager, actId);
|
||||
const companyOutcomes = signatures.filter((item) =>
|
||||
item.signerType === InspectionActSignerType.COMPANY_RESPONSIBLE,
|
||||
);
|
||||
@@ -556,6 +568,17 @@ export class InspectionClosingService {
|
||||
message: 'Debe existir exactamente una firma, disidencia, negativa o ausencia documentada del responsable de la empresa',
|
||||
});
|
||||
}
|
||||
const inspectorSigned = signatures.some((item) =>
|
||||
item.signerType === InspectionActSignerType.INSPECTOR
|
||||
&& item.status === InspectionActSignatureStatus.SIGNED,
|
||||
);
|
||||
if (!inspectorSigned) {
|
||||
const created = await this.createInspectorSignatureFromProfile(
|
||||
manager, actId, closure.preparedSha256, principal, request,
|
||||
);
|
||||
generatedInspectorSignaturePath = created.filePath;
|
||||
signatures = await this.loadSignatures(manager, actId);
|
||||
}
|
||||
|
||||
const serverSealedAt = new Date();
|
||||
const deviceSealedAt = new Date(dto.clientClosedAt);
|
||||
@@ -618,18 +641,21 @@ export class InspectionClosingService {
|
||||
WHERE act_id=$1
|
||||
`, [actId, finalSnapshot, finalSha256, deviceSealedAt, serverSealedAt, dto.uploadMode, principal.userId]);
|
||||
const [updated] = (await manager.query(`
|
||||
UPDATE inspection_acts
|
||||
SET status='SEALED',
|
||||
sealed_at=$2,
|
||||
sealed_by=$3,
|
||||
closed_at=$2,
|
||||
closed_by=$3,
|
||||
closure_sha256=$4,
|
||||
current_version=current_version+1,
|
||||
updated_by=$3,
|
||||
updated_at=$2
|
||||
WHERE id=$1
|
||||
RETURNING current_version AS "versionNumber"
|
||||
WITH updated AS (
|
||||
UPDATE inspection_acts
|
||||
SET status='SEALED',
|
||||
sealed_at=$2,
|
||||
sealed_by=$3,
|
||||
closed_at=$2,
|
||||
closed_by=$3,
|
||||
closure_sha256=$4,
|
||||
current_version=current_version+1,
|
||||
updated_by=$3,
|
||||
updated_at=$2
|
||||
WHERE id=$1
|
||||
RETURNING current_version
|
||||
)
|
||||
SELECT current_version AS "versionNumber" FROM updated
|
||||
`, [actId, serverSealedAt, principal.userId, finalSha256])) as Array<{ versionNumber: number }>;
|
||||
await manager.query(`
|
||||
INSERT INTO inspection_act_versions (
|
||||
@@ -663,7 +689,11 @@ export class InspectionClosingService {
|
||||
}, manager);
|
||||
await this.reports.ensureFrozenReport(manager, actId, principal, request);
|
||||
return this.loadView(manager, actId);
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
if (generatedInspectorSignaturePath) await unlink(generatedInspectorSignaturePath).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
await this.reports.ensureWordForAct(actId);
|
||||
return sealed;
|
||||
}
|
||||
@@ -1022,6 +1052,7 @@ export class InspectionClosingService {
|
||||
}>;
|
||||
if (!context) throw actNotFound();
|
||||
const responsible = await this.loadResponsible(manager, actId);
|
||||
const representativeSuggestion = responsible ? null : await this.loadResponsibleSuggestion(manager, actId);
|
||||
const closure = await this.loadClosure(manager, actId);
|
||||
const signatures = await this.loadSignatures(manager, actId);
|
||||
return {
|
||||
@@ -1051,6 +1082,7 @@ export class InspectionClosingService {
|
||||
actualClosedAt: context.visitActualClosedAt,
|
||||
},
|
||||
responsible,
|
||||
representativeSuggestion,
|
||||
closure: closure ? {
|
||||
schemaVersion: closure.schemaVersion,
|
||||
preparedSha256: closure.preparedSha256,
|
||||
@@ -1083,12 +1115,30 @@ export class InspectionClosingService {
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
private async loadResponsibleSuggestion(manager: EntityManager, actId: string): Promise<ResponsibleView | null> {
|
||||
const [row] = await manager.query(`
|
||||
SELECT responsible.act_id AS "actId",responsible.attendance_status AS "attendanceStatus",
|
||||
responsible.full_name AS "fullName",responsible.document_type AS "documentType",
|
||||
responsible.document_number AS "documentNumber",responsible.position,responsible.email,responsible.phone,
|
||||
responsible.absence_reason AS "absenceReason",responsible.updated_by AS "updatedBy",
|
||||
responsible.created_at AS "createdAt",responsible.updated_at AS "updatedAt"
|
||||
FROM inspection_acts current_act
|
||||
JOIN inspection_acts previous_act
|
||||
ON previous_act.visit_id=current_act.visit_id AND previous_act.id<>current_act.id
|
||||
JOIN inspection_act_responsibles responsible ON responsible.act_id=previous_act.id
|
||||
WHERE current_act.id=$1 AND responsible.attendance_status='PRESENT'
|
||||
ORDER BY responsible.updated_at DESC,previous_act.created_at DESC
|
||||
LIMIT 1
|
||||
`, [actId]) as ResponsibleView[];
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
private async requireResponsible(manager: EntityManager, actId: string): Promise<ResponsibleView> {
|
||||
const responsible = await this.loadResponsible(manager, actId);
|
||||
if (!responsible) {
|
||||
throw new ConflictException({
|
||||
code: 'INSPECTION_ACT_RESPONSIBLE_REQUIRED',
|
||||
message: 'Debe identificarse al responsable o documentar su ausencia antes de finalizar el acta',
|
||||
message: 'Debe identificarse al representante de la empresa o documentar su ausencia antes de cerrar el Acta',
|
||||
});
|
||||
}
|
||||
return responsible;
|
||||
@@ -1150,6 +1200,82 @@ export class InspectionClosingService {
|
||||
return rows.map(({ storedName: _storedName, originalName: _originalName, ...row }) => row);
|
||||
}
|
||||
|
||||
private async requireReusableInspectorSignature(
|
||||
manager: EntityManager,
|
||||
userId: string,
|
||||
): Promise<ReusableInspectorSignature> {
|
||||
const [row] = await manager.query(`
|
||||
SELECT original_name AS "originalName", mime_type AS "mimeType",
|
||||
size_bytes AS "sizeBytes", image_sha256 AS "imageSha256",
|
||||
image_data AS "imageData"
|
||||
FROM user_signature_profiles
|
||||
WHERE user_id=$1
|
||||
`, [userId]) as ReusableInspectorSignature[];
|
||||
if (!row) {
|
||||
throw new ConflictException({
|
||||
code: 'INSPECTION_INSPECTOR_PROFILE_SIGNATURE_REQUIRED',
|
||||
message: 'Para cerrar definitivamente el Acta, cargá tu firma de inspector desde Mi perfil en el Dashboard',
|
||||
});
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
private async createInspectorSignatureFromProfile(
|
||||
manager: EntityManager,
|
||||
actId: string,
|
||||
preparedSha256: string,
|
||||
principal: AuthPrincipal,
|
||||
request: RequestWithContext,
|
||||
): Promise<{ filePath: string }> {
|
||||
const profile = await this.requireReusableInspectorSignature(manager, principal.userId);
|
||||
const id = randomUUID();
|
||||
const storedName = `${id}.png`;
|
||||
const filePath = resolve(this.signatureRoot, storedName);
|
||||
await mkdir(this.signatureRoot, { recursive: true, mode: 0o700 });
|
||||
await writeFile(filePath, profile.imageData, { flag: 'wx', mode: 0o600 });
|
||||
const signedAt = new Date();
|
||||
const source = this.signatureSource(principal);
|
||||
const signerName = `${principal.firstName} ${principal.lastName}`.trim();
|
||||
const payload = {
|
||||
actId, lockedSha256: preparedSha256, signerType: InspectionActSignerType.INSPECTOR,
|
||||
signerUserId: principal.userId, signerName, position: 'Inspector/a',
|
||||
status: InspectionActSignatureStatus.SIGNED, imageSha256: profile.imageSha256,
|
||||
consentText: INSPECTOR_CONSENT, consentVersion: CONSENT_VERSION,
|
||||
consentAcceptedAt: signedAt.toISOString(), signedAt: signedAt.toISOString(),
|
||||
source, signatureMode: 'PROFILE_REUSABLE', uploadedBy: principal.userId,
|
||||
};
|
||||
const signaturePayloadSha256 = sha256CanonicalJson(payload);
|
||||
try {
|
||||
await manager.query(`
|
||||
INSERT INTO inspection_act_signatures (
|
||||
id,act_id,signer_type,signer_user_id,signer_name,document_type,document_number,position,status,
|
||||
original_name,stored_name,mime_type,size_bytes,image_sha256,consent_text,consent_version,
|
||||
consent_accepted_at,client_signed_at,signed_at,latitude,longitude,accuracy_m,device_label,source,
|
||||
prepared_sha256,signature_payload_sha256,uploaded_by,created_at
|
||||
) VALUES (
|
||||
$1,$2,'INSPECTOR',$3,$4,NULL,NULL,'Inspector/a','SIGNED',
|
||||
$5,$6,$7,$8,$9,$10,$11,$12,NULL,$12,NULL,NULL,NULL,$13,$14,$15,$16,$3,$12
|
||||
)
|
||||
`, [
|
||||
id, actId, principal.userId, signerName, profile.originalName, storedName, profile.mimeType,
|
||||
profile.sizeBytes, profile.imageSha256, INSPECTOR_CONSENT, CONSENT_VERSION, signedAt,
|
||||
'Firma guardada en Mi perfil', source, preparedSha256, signaturePayloadSha256,
|
||||
]);
|
||||
await this.audit.record({
|
||||
...administrationAuditContext(principal, request),
|
||||
action: AuditAction.INSPECTION_ACT_SIGNATURE_RECORDED,
|
||||
entityType: 'inspection_act_signature',
|
||||
entityId: id,
|
||||
afterData: payload,
|
||||
metadata: { actId, immutable: true, signatureMode: 'PROFILE_REUSABLE' },
|
||||
}, manager);
|
||||
return { filePath };
|
||||
} catch (error) {
|
||||
await unlink(filePath).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async loadStoredSignature(manager: EntityManager, id: string): Promise<StoredSignature> {
|
||||
const [row] = await manager.query(`${this.signatureSelect()} WHERE signature.id=$1`, [id]) as StoredSignature[];
|
||||
if (!row) throw signatureNotFound();
|
||||
|
||||
@@ -1166,10 +1166,13 @@ export class InspectionFindingsService {
|
||||
principal: AuthPrincipal,
|
||||
): Promise<number> {
|
||||
const [row] = await manager.query(`
|
||||
UPDATE inspection_findings
|
||||
SET current_version = current_version + 1
|
||||
WHERE id = $1
|
||||
RETURNING current_version AS "versionNumber"
|
||||
WITH updated AS (
|
||||
UPDATE inspection_findings
|
||||
SET current_version = current_version + 1
|
||||
WHERE id = $1
|
||||
RETURNING current_version
|
||||
)
|
||||
SELECT current_version AS "versionNumber" FROM updated
|
||||
`, [finding.id]) as Array<{ versionNumber: number }>;
|
||||
const versionNumber = Number(row.versionNumber);
|
||||
finding.currentVersion = versionNumber;
|
||||
|
||||
@@ -99,8 +99,10 @@ function lines(snapshot: Record<string, unknown>): string[] {
|
||||
`Fecha: ${date(act.occurredAt)}`,
|
||||
`Urgencia: ${urgencyLabel(act.urgency)}`,
|
||||
`Plazo: ${deadlineText}`,
|
||||
`Responsable empresa: ${text(responsible.fullName)}`,
|
||||
`Cargo: ${text(responsible.position)}`,
|
||||
`Representante de la empresa: ${text(responsible.fullName)}`,
|
||||
`DNI: ${text(responsible.documentNumber)}`,
|
||||
`Cargo / funcion: ${text(responsible.position)}`,
|
||||
`Email: ${text(responsible.email)}`,
|
||||
'',
|
||||
'RESUMEN',
|
||||
...wrap(text(act.summary)),
|
||||
@@ -136,7 +138,7 @@ function lines(snapshot: Record<string, unknown>): string[] {
|
||||
out.push('Manifestacion de empresa: pendiente.');
|
||||
} else if (text(companySignature.status, '') === 'SIGNED') {
|
||||
const manifestation = text(companySignature.companyManifestation, 'CONFORMITY');
|
||||
out.push(manifestation === 'DISSENT' ? 'Empresa: firma en disidencia' : 'Empresa: firma en conformidad');
|
||||
out.push(manifestation === 'DISSENT' ? 'Empresa: firma en disconformidad' : 'Empresa: firma en conformidad');
|
||||
if (manifestation === 'DISSENT') out.push(...wrap(text(companySignature.companyStatement)));
|
||||
} else {
|
||||
out.push(...wrap(`Empresa: ${text(companySignature.status)} - ${text(companySignature.reason)}`));
|
||||
|
||||
@@ -281,7 +281,7 @@ export class InspectionDocumentDeliveryService {
|
||||
email = company?.email ?? null;
|
||||
} else if (row.recipientKind === 'INSPECTOR' && row.recipientUserId) {
|
||||
const [inspector] = await this.dataSource.query(`
|
||||
SELECT email FROM users WHERE id=$1 AND is_active=true
|
||||
SELECT email FROM users WHERE id=$1 AND status='ACTIVE'
|
||||
`, [row.recipientUserId]) as Array<{ email: string | null }>;
|
||||
email = inspector?.email ?? null;
|
||||
} else {
|
||||
@@ -305,7 +305,14 @@ export class InspectionDocumentDeliveryService {
|
||||
await this.setStatus(row.id,'WAITING_RECIPIENT','Destinatario no configurado');
|
||||
return;
|
||||
}
|
||||
if (!await this.smtp.configured()) {
|
||||
const [sender] = await this.dataSource.query(`
|
||||
SELECT visit.lead_inspector_user_id AS "userId"
|
||||
FROM inspection_acts act
|
||||
JOIN inspection_visits visit ON visit.id=act.visit_id
|
||||
WHERE act.id=$1
|
||||
`, [row.actId]) as Array<{ userId: string | null }>;
|
||||
const senderUserId = sender?.userId ?? undefined;
|
||||
if (!await this.smtp.configured(senderUserId)) {
|
||||
await this.setStatus(row.id,'WAITING_TRANSPORT','SMTP no configurado');
|
||||
return;
|
||||
}
|
||||
@@ -348,7 +355,7 @@ export class InspectionDocumentDeliveryService {
|
||||
: `Se adjunta el acta sellada e inmutable ${row.actCode}.`;
|
||||
const sent = await this.smtp.send({
|
||||
to:row.recipientEmail,subject:`DH Inspección · ${label}`,text,attachment,
|
||||
});
|
||||
}, senderUserId);
|
||||
await this.dataSource.query(`
|
||||
UPDATE inspection_document_deliveries
|
||||
SET status='SENT',sent_at=CURRENT_TIMESTAMP,provider_message_id=$2,
|
||||
|
||||
@@ -147,8 +147,10 @@ function documentXml(input: ReportWordInput): string {
|
||||
paragraph('El bloque siguiente reproduce información proveniente del Acta sellada. Debe conservarse sin alterar su sentido ni sustituir los Hallazgos originales.'),
|
||||
labelValue('Resumen del Acta', text(snapshot.act.summary)),
|
||||
labelValue('Observaciones del Acta', text(snapshot.act.observations)),
|
||||
labelValue('Responsable de empresa', text(snapshot.responsible.fullName)),
|
||||
labelValue('Cargo', text(snapshot.responsible.position)),
|
||||
labelValue('Representante de la empresa', text(snapshot.responsible.fullName)),
|
||||
labelValue('DNI', text(snapshot.responsible.documentNumber)),
|
||||
labelValue('Cargo / función', text(snapshot.responsible.position)),
|
||||
labelValue('Email', text(snapshot.responsible.email)),
|
||||
paragraph('Inventario inspeccionado', 'Heading1'),
|
||||
inventoryRows.length
|
||||
? table(['Código', 'Nombre', 'Tipo'], inventoryRows)
|
||||
|
||||
@@ -11,7 +11,7 @@ interface MailInput { to:string; subject:string; text:string; attachment:MailAtt
|
||||
interface Reply { code:number; text:string; }
|
||||
|
||||
export interface EffectiveSmtpSettings {
|
||||
source: 'DATABASE' | 'ENVIRONMENT';
|
||||
source: 'USER' | 'DATABASE' | 'ENVIRONMENT';
|
||||
host: string;
|
||||
port: number;
|
||||
securityMode: SmtpSecurityMode;
|
||||
@@ -47,10 +47,10 @@ export class SmtpDeliveryService {
|
||||
private readonly config:ConfigService,
|
||||
){}
|
||||
|
||||
async configured():Promise<boolean>{return Boolean(await this.resolveSettings());}
|
||||
async configured(userId?:string):Promise<boolean>{return Boolean(await this.resolveSettings(userId));}
|
||||
|
||||
async fromAddress():Promise<string|null>{
|
||||
const settings=await this.resolveSettings();
|
||||
async fromAddress(userId?:string):Promise<string|null>{
|
||||
const settings=await this.resolveSettings(userId);
|
||||
if(!settings)return null;
|
||||
return settings.fromName?`${settings.fromName} <${settings.fromEmail}>`:settings.fromEmail;
|
||||
}
|
||||
@@ -73,6 +73,56 @@ export class SmtpDeliveryService {
|
||||
}:{source:'NONE',enabled:false};
|
||||
}
|
||||
|
||||
async publicUserSettings(userId:string){
|
||||
const [user]=await this.dataSource.query(`
|
||||
SELECT email,first_name AS "firstName",last_name AS "lastName" FROM users WHERE id=$1
|
||||
`,[userId]) as Array<{email:string;firstName:string;lastName:string}>;
|
||||
if(!user)throw new Error('Usuario no encontrado');
|
||||
const [row]=await this.dataSource.query(`
|
||||
SELECT mode,host,port,security_mode AS "securityMode",username,
|
||||
(password_enc IS NOT NULL) AS "hasPassword",from_name AS "fromName",
|
||||
from_email AS "fromEmail",enabled,updated_at AS "updatedAt"
|
||||
FROM user_smtp_settings WHERE user_id=$1
|
||||
`,[userId]) as Array<Record<string,unknown>>;
|
||||
return {
|
||||
mode:row?.mode??'SYSTEM',email:user.email,generalConfigured:Boolean(await this.resolveSystemSettings()),
|
||||
custom:row?{
|
||||
host:row.host??'',port:row.port??587,securityMode:row.securityMode??'STARTTLS',
|
||||
username:row.username??'',hasPassword:Boolean(row.hasPassword),
|
||||
fromName:row.fromName??`${user.firstName} ${user.lastName}`,fromEmail:row.fromEmail??user.email,
|
||||
enabled:row.enabled!==false,updatedAt:row.updatedAt??null,
|
||||
}:null,
|
||||
};
|
||||
}
|
||||
|
||||
async saveUserSettings(userId:string,input:{
|
||||
mode:'SYSTEM'|'CUSTOM';host?:string;port?:number;securityMode?:SmtpSecurityMode;
|
||||
username?:string|null;password?:string|null;fromName?:string|null;enabled?:boolean;
|
||||
}){
|
||||
const [user]=await this.dataSource.query(`SELECT email,first_name AS "firstName",last_name AS "lastName" FROM users WHERE id=$1`,[userId]) as Array<{email:string;firstName:string;lastName:string}>;
|
||||
if(!user?.email)throw new Error('El usuario debe tener un email configurado');
|
||||
const [existing]=await this.dataSource.query(`SELECT password_enc AS "passwordEnc" FROM user_smtp_settings WHERE user_id=$1`,[userId]) as Array<{passwordEnc:string|null}>;
|
||||
if(input.mode==='SYSTEM'){
|
||||
await this.dataSource.query(`
|
||||
INSERT INTO user_smtp_settings(user_id,mode,updated_by) VALUES($1,'SYSTEM',$1)
|
||||
ON CONFLICT(user_id) DO UPDATE SET mode='SYSTEM',updated_by=$1,updated_at=CURRENT_TIMESTAMP
|
||||
`,[userId]);
|
||||
return this.publicUserSettings(userId);
|
||||
}
|
||||
if(!input.host||!input.port||!input.securityMode)throw new Error('La configuración SMTP propia está incompleta');
|
||||
const passwordEnc=input.password===undefined?existing?.passwordEnc??null:input.password?this.encryptSecret(input.password):null;
|
||||
const fromName=input.fromName?.trim()||`${user.firstName} ${user.lastName}`.trim();
|
||||
await this.dataSource.query(`
|
||||
INSERT INTO user_smtp_settings(user_id,mode,host,port,security_mode,username,password_enc,from_name,from_email,reply_to,enabled,updated_by)
|
||||
VALUES($1,'CUSTOM',$2,$3,$4,$5,$6,$7,$8,$8,$9,$1)
|
||||
ON CONFLICT(user_id) DO UPDATE SET mode='CUSTOM',host=EXCLUDED.host,port=EXCLUDED.port,
|
||||
security_mode=EXCLUDED.security_mode,username=EXCLUDED.username,password_enc=EXCLUDED.password_enc,
|
||||
from_name=EXCLUDED.from_name,from_email=EXCLUDED.from_email,reply_to=EXCLUDED.reply_to,
|
||||
enabled=EXCLUDED.enabled,updated_by=$1,updated_at=CURRENT_TIMESTAMP
|
||||
`,[userId,input.host,input.port,input.securityMode,input.username?.trim()||null,passwordEnc,fromName,user.email,input.enabled!==false]);
|
||||
return this.publicUserSettings(userId);
|
||||
}
|
||||
|
||||
async saveSettings(input:{
|
||||
host:string;port:number;securityMode:SmtpSecurityMode;username?:string|null;
|
||||
password?:string|null;fromName:string;fromEmail:string;replyTo?:string|null;enabled:boolean;
|
||||
@@ -96,8 +146,8 @@ export class SmtpDeliveryService {
|
||||
return this.publicSettings();
|
||||
}
|
||||
|
||||
async send(input:MailInput):Promise<{messageId:string}>{
|
||||
const settings=await this.resolveSettings();
|
||||
async send(input:MailInput,userId?:string):Promise<{messageId:string}>{
|
||||
const settings=await this.resolveSettings(userId);
|
||||
if(!settings)throw new Error('SMTP no configurado');
|
||||
const {host,port,securityMode,userName,password}= {
|
||||
host:settings.host,port:settings.port,securityMode:settings.securityMode,
|
||||
@@ -137,7 +187,33 @@ export class SmtpDeliveryService {
|
||||
return {messageId:match?.[1]??randomUUID()};
|
||||
}
|
||||
|
||||
private async resolveSettings():Promise<EffectiveSmtpSettings|null>{
|
||||
private async resolveSettings(userId?:string):Promise<EffectiveSmtpSettings|null>{
|
||||
if(userId){
|
||||
const [row]=await this.dataSource.query(`
|
||||
SELECT settings.mode,settings.host,settings.port,settings.security_mode AS "securityMode",
|
||||
settings.username,settings.password_enc AS "passwordEnc",settings.from_name AS "fromName",
|
||||
settings.enabled,user_account.email AS "userEmail"
|
||||
FROM users user_account
|
||||
LEFT JOIN user_smtp_settings settings ON settings.user_id=user_account.id
|
||||
WHERE user_account.id=$1
|
||||
`,[userId]) as Array<{
|
||||
mode:'SYSTEM'|'CUSTOM'|null;host:string|null;port:number|null;securityMode:SmtpSecurityMode|null;
|
||||
username:string|null;passwordEnc:string|null;fromName:string|null;enabled:boolean|null;userEmail:string;
|
||||
}>;
|
||||
if(row?.mode==='CUSTOM'&&row.enabled!==false&&row.host&&row.port&&row.securityMode&&row.userEmail){
|
||||
return {
|
||||
source:'USER',host:row.host,port:Number(row.port),securityMode:row.securityMode,
|
||||
username:row.username,password:row.passwordEnc?this.decryptSecret(row.passwordEnc):'',
|
||||
fromName:row.fromName,fromEmail:row.userEmail,replyTo:row.userEmail,
|
||||
};
|
||||
}
|
||||
const general=await this.resolveSystemSettings();
|
||||
return general&&row?.userEmail?{...general,replyTo:row.userEmail}:general;
|
||||
}
|
||||
return this.resolveSystemSettings();
|
||||
}
|
||||
|
||||
private async resolveSystemSettings():Promise<EffectiveSmtpSettings|null>{
|
||||
const [row]=await this.dataSource.query(`
|
||||
SELECT host,port,security_mode AS "securityMode",username,password_enc AS "passwordEnc",
|
||||
from_name AS "fromName",from_email AS "fromEmail",reply_to AS "replyTo",enabled
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
Matches,
|
||||
Max,
|
||||
MaxLength,
|
||||
Min,
|
||||
@@ -56,8 +55,4 @@ export class CreateFieldFindingDto {
|
||||
@Max(10)
|
||||
severity?: number;
|
||||
|
||||
@IsOptional()
|
||||
@Transform(optionalText)
|
||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||
correctionDueOn?: string | null;
|
||||
}
|
||||
|
||||
@@ -105,7 +105,7 @@ export class FieldFindingsService {
|
||||
customLegalBasis: dto.customLegalBasis ?? null,
|
||||
description: dto.description,
|
||||
severity: dto.severity,
|
||||
correctionDueOn: dto.correctionDueOn ?? null,
|
||||
correctionDueOn: null,
|
||||
};
|
||||
const finding = await this.findings.create(act.id, payload, principal, request);
|
||||
return {
|
||||
|
||||
@@ -295,6 +295,7 @@ export class FieldInventoryService {
|
||||
operationalAreaId: context.areaId,
|
||||
// Compatibility-only creation snapshot. Membership never depends on it.
|
||||
operatorCompanyId: context.companyId,
|
||||
inventoryFamilyId: dto.familyId ?? null,
|
||||
description: dto.description ?? null,
|
||||
discoveryNotes: dto.discoveryNotes ?? null,
|
||||
attributes: dto.attributes,
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export const API_VERSION = '0.29.0-1';
|
||||
export const API_PHASE = 'F6.1';
|
||||
export const API_VERSION = '0.29.0-7';
|
||||
export const API_PHASE = 'F6.7';
|
||||
|
||||
@@ -25,11 +25,11 @@ test('F3.1 amplía el perfil personal y protege email del Inspector también en
|
||||
assert.match(userMigration, /trg_users_inspector_email/);
|
||||
});
|
||||
|
||||
test('F3.1 exige email al crear o asignar el rol Inspector', () => {
|
||||
assert.match(usersService, /assertInspectorHasEmail\(roles, dto\.email/);
|
||||
assert.match(usersService, /assertInspectorHasEmail\(roles, before\.email\)/);
|
||||
assert.match(usersService, /Los usuarios con rol Inspector deben tener un email válido/);
|
||||
assert.match(usersService, /dto\.email !== undefined && !dto\.email && before\.roles\.some/);
|
||||
test('F3.1 email del Inspector sigue protegido y F6.2 endurece email para todo usuario', () => {
|
||||
assert.match(usersService, /USER_EMAIL_REQUIRED/);
|
||||
assert.match(usersService, /Cada usuario de Hidrocarburos debe tener un email válido/);
|
||||
assert.match(usersService, /if \(!dto\.email\?\.trim\(\)\) throw userEmailRequired\(\)/);
|
||||
assert.match(usersService, /dto\.email !== undefined && !dto\.email/);
|
||||
});
|
||||
|
||||
test('F3.1 dossier canónico agrega alias sin borrar identidad histórica', () => {
|
||||
|
||||
@@ -28,7 +28,8 @@ test('F3.2/F4 exige seleccionar el Acta explícitamente al crear Hallazgos desde
|
||||
test('F4 conserva el cierre documental inmutable de cada Acta como LOCKED y luego SEALED', () => {
|
||||
const closing = read('src/inspection-closing/inspection-closing.service.ts');
|
||||
assert.match(closing, /status='LOCKED'/);
|
||||
assert.match(closing, /INSPECTION_ACT_INSPECTOR_SIGNATURE_REQUIRED/);
|
||||
assert.match(closing, /INSPECTION_INSPECTOR_PROFILE_SIGNATURE_REQUIRED/);
|
||||
assert.match(closing, /createInspectorSignatureFromProfile/);
|
||||
assert.match(closing, /INSPECTION_ACT_COMPANY_OUTCOME_REQUIRED/);
|
||||
assert.match(closing, /finalSha256 = sha256CanonicalJson\(finalSnapshot\)/);
|
||||
assert.match(closing, /status='SEALED'/);
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { API_PHASE, API_VERSION } from '../../src/version';
|
||||
|
||||
test('health metadata reports the current F6.1 release', () => {
|
||||
assert.equal(API_PHASE, 'F6.1');
|
||||
assert.equal(API_VERSION, '0.29.0-1');
|
||||
test('health metadata reports the current F6.7 release', () => {
|
||||
assert.equal(API_PHASE, 'F6.7');
|
||||
const pkg = JSON.parse(readFileSync(resolve(process.cwd(), 'package.json'), 'utf8')) as { version: string };
|
||||
assert.equal(API_VERSION, pkg.version);
|
||||
assert.equal(API_VERSION, '0.29.0-7');
|
||||
});
|
||||
@@ -80,9 +80,10 @@ test('F4 field finding flow only targets a draft act of the same in-progress ins
|
||||
assert.match(draftGuard, /WHERE visit_id = \$1::uuid[\s\S]*AND status = 'DRAFT'/);
|
||||
});
|
||||
|
||||
test('F4 sealing requires inspector signature and exactly one terminal company outcome', () => {
|
||||
test('F6.7 sealing copies the stored inspector signature and requires exactly one terminal company outcome', () => {
|
||||
const closeBody = closing.slice(closing.indexOf(' async close('), closing.indexOf(' async signatureContent('));
|
||||
assert.match(closeBody, /INSPECTION_ACT_INSPECTOR_SIGNATURE_REQUIRED/);
|
||||
assert.match(closeBody, /createInspectorSignatureFromProfile/);
|
||||
assert.match(closing, /INSPECTION_INSPECTOR_PROFILE_SIGNATURE_REQUIRED/);
|
||||
assert.match(closeBody, /companyOutcomes\.length !== 1/);
|
||||
assert.match(closeBody, /INSPECTION_ACT_COMPANY_OUTCOME_REQUIRED/);
|
||||
assert.match(closeBody, /ausencia documentada/);
|
||||
|
||||
@@ -10,8 +10,8 @@ function mountedRepoFile(path: string): string {
|
||||
test('F6.3 Android test cut targets production API and has a distinct installable debug version', () => {
|
||||
const gradle = mountedRepoFile('android-app/app/build.gradle.kts');
|
||||
|
||||
assert.match(gradle, /versionCode = 30/);
|
||||
assert.match(gradle, /versionName = "0\.19\.2"/);
|
||||
assert.match(gradle, /versionCode = 37/);
|
||||
assert.match(gradle, /versionName = "0\.19\.9"/);
|
||||
assert.match(gradle, /https:\/\/dhv2\.korexlabs\.com\/api\/v3\//);
|
||||
assert.match(gradle, /applicationIdSuffix = "\.debug"/);
|
||||
});
|
||||
@@ -26,3 +26,18 @@ test('F5/F6.3 field inventory exposes Other families as reviewable choices to An
|
||||
assert.match(service, /AS "isOther"/);
|
||||
assert.match(service, /isOtherFamily: family\.isOther/);
|
||||
});
|
||||
|
||||
|
||||
test('field inventory persists the validated Tipo de instalación in the initial asset insert', () => {
|
||||
const fieldService = readFileSync(
|
||||
resolve(process.cwd(), 'src/inspection-visits/field-inventory.service.ts'),
|
||||
'utf8',
|
||||
);
|
||||
const assetsService = readFileSync(
|
||||
resolve(process.cwd(), 'src/asset-master/assets.service.ts'),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
assert.match(fieldService, /inventoryFamilyId: dto\.familyId \?\? null/);
|
||||
assert.match(assetsService, /inventoryFamilyId: dto\.inventoryFamilyId \?\? null/);
|
||||
});
|
||||
|
||||
@@ -31,7 +31,8 @@ test('F6.1 uses contextual type catalog for Yacimiento and keeps OTROS/add-anoth
|
||||
assert.match(catalog, /finding_catalog_asset_overrides override/);
|
||||
assert.match(resolver, /code: 'OTHER'/);
|
||||
assert.match(resolver, /label: 'OTROS'/);
|
||||
assert.match(androidFinding, /OTROS · No está en el catálogo/);
|
||||
assert.match(androidFinding, /ExposedDropdownMenuBox/);
|
||||
assert.match(androidFinding, /Otro \/ No está en la lista/);
|
||||
assert.match(androidFinding, /También podés registrar otro Hallazgo sobre el mismo Inventario/);
|
||||
});
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ test('F6.1 presentation metadata keeps the visible WEB version aligned with pack
|
||||
const visibleVersion = version.match(/APP_VERSION\s*=\s*'([^']+)'/)?.[1];
|
||||
|
||||
assert.equal(visibleVersion, pkg.version);
|
||||
assert.match(version, /APP_PHASE\s*=\s*'F6\.1 · Contexto operativo Área–Operadora consolidado'/);
|
||||
assert.match(version, /APP_PHASE\s*=\s*'F6\.7 · Cierre y firma por Acta'/);
|
||||
});
|
||||
|
||||
test('F6.1 presentation keeps Relevamientos retired from WEB navigation and routes', () => {
|
||||
@@ -33,7 +33,7 @@ test('F6.1 presentation keeps the complete Inspector profile and documentary-cop
|
||||
for (const field of ['dni', 'phone', 'jobTitle', 'employeeNumber']) {
|
||||
assert.match(user, new RegExp(`name="${field}"`));
|
||||
}
|
||||
assert.match(user, /email es obligatorio para un Inspector/i);
|
||||
assert.match(user, /email es obligatorio para todos los usuarios de Hidrocarburos/i);
|
||||
assert.match(user, /la documentación se enviará también/i);
|
||||
assert.match(delivery, /recipientKind:'INSPECTOR'/);
|
||||
assert.match(delivery, /documentKind:'ACT_PDF'/);
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
const read = (path: string) => readFileSync(resolve(process.cwd(), path), 'utf8');
|
||||
const migration = read('src/database/migrations/1790117400000-f6-2-user-smtp-and-act-representative.ts');
|
||||
const closing = read('src/inspection-closing/inspection-closing.service.ts');
|
||||
const responsibleDto = read('src/inspection-closing/dto/upsert-inspection-responsible.dto.ts');
|
||||
const prepareDto = read('src/inspection-closing/dto/prepare-inspection-act.dto.ts');
|
||||
const findingEntity = read('src/database/entities/inspection-finding.entity.ts');
|
||||
const smtp = read('src/inspection-reports/smtp-delivery.service.ts');
|
||||
const users = read('src/administration/users/users.controller.ts');
|
||||
const delivery = read('src/inspection-reports/inspection-document-delivery.service.ts');
|
||||
|
||||
const android = read('../android-app/app/src/main/java/com/korexlabs/dhinspeccion/ui/ModernMobileActsScreen.kt');
|
||||
const androidModel = read('../android-app/app/src/main/java/com/korexlabs/dhinspeccion/data/MobileActs.kt');
|
||||
const profilePage = read('../web-v2/src/pages/MyProfilePage.tsx');
|
||||
|
||||
test('F6.2 keeps urgency exclusively at Act close, never on individual findings', () => {
|
||||
assert.match(prepareDto, /InspectionActUrgency/);
|
||||
assert.match(prepareDto, /urgency!/);
|
||||
assert.doesNotMatch(findingEntity, /\burgency\b/i);
|
||||
assert.match(android, /Urgencia del Acta/);
|
||||
assert.match(android, /urgencia no se asigna a cada Hallazgo/i);
|
||||
});
|
||||
|
||||
test('F6.2 requires the company representative identity and email on every Act', () => {
|
||||
assert.match(responsibleDto, /attendanceStatus === InspectionResponsibleAttendanceStatus\.PRESENT/);
|
||||
assert.match(responsibleDto, /@IsEmail\(\)/);
|
||||
assert.match(migration, /LENGTH\(TRIM\(COALESCE\(email, ''\)\)\) > 0/);
|
||||
assert.match(closing, /representativeSuggestion/);
|
||||
assert.match(closing, /previous_act\.visit_id=current_act\.visit_id/);
|
||||
assert.match(androidModel, /representativeSuggestion/);
|
||||
assert.match(android, /Nombres y apellidos \*/);
|
||||
assert.match(android, /DNI \*/);
|
||||
assert.match(android, /Cargo \/ función \*/);
|
||||
assert.match(android, /Email \*/);
|
||||
assert.match(android, /Firma del representante de la empresa/);
|
||||
assert.match(android, /En disconformidad/);
|
||||
assert.match(android, /Motivo de disconformidad \*/);
|
||||
});
|
||||
|
||||
test('F6.2 gives every authenticated user a general SMTP default and encrypted custom override', () => {
|
||||
assert.match(migration, /CREATE TABLE user_smtp_settings/);
|
||||
assert.match(migration, /ALTER COLUMN email SET NOT NULL/);
|
||||
assert.match(migration, /mode IN \('SYSTEM','CUSTOM'\)/);
|
||||
assert.match(smtp, /publicUserSettings/);
|
||||
assert.match(smtp, /saveUserSettings/);
|
||||
assert.match(smtp, /source:\s*["']USER["']/);
|
||||
assert.match(smtp, /encryptSecret/);
|
||||
assert.match(smtp, /password_enc/);
|
||||
});
|
||||
|
||||
test('F6.2 exposes personal mail settings in Mi perfil without granting administration permissions', () => {
|
||||
assert.match(users, /@Get\('self\/profile'\)/);
|
||||
assert.match(users, /@Patch\('self\/profile'\)/);
|
||||
assert.match(users, /@Get\('self\/smtp'\)/);
|
||||
assert.match(users, /@Put\('self\/smtp'\)/);
|
||||
assert.match(users, /@Post\('self\/smtp\/test'\)/);
|
||||
assert.match(profilePage, /MI PERFIL/);
|
||||
assert.match(profilePage, /Usar SMTP general/);
|
||||
assert.match(profilePage, /Usar SMTP propio/);
|
||||
assert.match(profilePage, /Enviar correo de prueba/);
|
||||
assert.doesNotMatch(profilePage, /document_delivery\.manage/);
|
||||
});
|
||||
|
||||
test('F6.2 sends Act-related mail through the lead inspector transport selection', () => {
|
||||
assert.match(delivery, /lead_inspector_user_id AS "userId"/);
|
||||
assert.match(delivery, /configured\(senderUserId\)/);
|
||||
assert.match(delivery, /}, senderUserId\);/);
|
||||
});
|
||||
@@ -63,3 +63,12 @@ test('F6.1 Acta urgency is null while drafting and is persisted atomically at lo
|
||||
assert.match(migration, /ALTER COLUMN urgency DROP NOT NULL/);
|
||||
assert.match(migration, /SET urgency=NULL WHERE status='DRAFT'/);
|
||||
});
|
||||
|
||||
test('F6.3 Acta version capture uses a SELECT-shaped CTE so TypeORM never turns the version into NaN', () => {
|
||||
const service = source('src/inspection-acts/inspection-acts.service.ts');
|
||||
|
||||
assert.match(service, /WITH updated AS \(/);
|
||||
assert.match(service, /RETURNING current_version/);
|
||||
assert.match(service, /SELECT current_version AS "versionNumber" FROM updated/);
|
||||
assert.match(service, /const versionNumber = Number\(row\.versionNumber\)/);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import test from 'node:test';
|
||||
|
||||
function source(path: string): string {
|
||||
return readFileSync(resolve(process.cwd(), path), 'utf8');
|
||||
}
|
||||
|
||||
test('F6.5 finding code CHECK accepts the current visible Acta code', () => {
|
||||
const migration = source('src/database/migrations/1790121000000-f6-5-field-finding-code-contract.ts');
|
||||
const service = source('src/inspection-findings/inspection-findings.service.ts');
|
||||
|
||||
assert.match(migration, /ACT-\[0-9\]\{5\}-\[0-9\]\{2\}-\[0-9\]\{2\}-\[0-9\]\{2\}/);
|
||||
assert.match(migration, /-H\[0-9\]\{3\}/);
|
||||
assert.match(service, /code: `\$\{act\.code\}-H\$\{String\(findingNumber\)\.padStart\(3, '0'\)\}`/);
|
||||
});
|
||||
|
||||
test('F6.5 mobile finding creation never asks the inspector for a correction date', () => {
|
||||
const dto = source('src/inspection-visits/dto/create-field-finding.dto.ts');
|
||||
const adapter = source('src/inspection-visits/field-findings.service.ts');
|
||||
const androidRequest = source('../android-app/app/src/main/java/com/korexlabs/dhinspeccion/data/FieldFindingsMobile.kt');
|
||||
const androidScreen = source('../android-app/app/src/main/java/com/korexlabs/dhinspeccion/ui/FieldFindingScreen.kt');
|
||||
|
||||
assert.doesNotMatch(dto, /correctionDueOn/);
|
||||
assert.match(adapter, /correctionDueOn: null/);
|
||||
assert.doesNotMatch(androidRequest.match(/data class CreateFieldFindingRequest\([\s\S]*?\n\)/)?.[0] ?? '', /correctionDueOn/);
|
||||
assert.doesNotMatch(androidScreen, /Fecha de corrección/);
|
||||
assert.match(androidScreen, /ExposedDropdownMenuBox/);
|
||||
assert.match(androidScreen, /Tipo de Hallazgo \*/);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import test from 'node:test';
|
||||
|
||||
function source(path: string): string {
|
||||
return readFileSync(resolve(process.cwd(), path), 'utf8');
|
||||
}
|
||||
|
||||
test('F6.6 Hallazgo version capture uses a SELECT-shaped CTE so TypeORM never turns the version into NaN', () => {
|
||||
const service = source('src/inspection-findings/inspection-findings.service.ts');
|
||||
|
||||
assert.match(service, /WITH updated AS \(/);
|
||||
assert.match(service, /UPDATE inspection_findings/);
|
||||
assert.match(service, /RETURNING current_version/);
|
||||
assert.match(service, /SELECT current_version AS "versionNumber" FROM updated/);
|
||||
assert.match(service, /const versionNumber = Number\(row\.versionNumber\)/);
|
||||
});
|
||||
|
||||
test('F6.6 mobile home keeps Salir readable on narrow screens', () => {
|
||||
const home = source('../android-app/app/src/main/java/com/korexlabs/dhinspeccion/ui/MobileHomeScreen.kt');
|
||||
|
||||
assert.match(home, /Text\("Actualizar", maxLines = 1\)/);
|
||||
assert.match(home, /Text\("Salir", maxLines = 1\)/);
|
||||
assert.match(home, /modifier = Modifier\.weight\(1f\)/);
|
||||
});
|
||||
|
||||
test('F6.6 Hallazgos can receive as many field photos as needed', () => {
|
||||
const screen = source('../android-app/app/src/main/java/com/korexlabs/dhinspeccion/ui/FieldFindingScreen.kt');
|
||||
const model = source('../android-app/app/src/main/java/com/korexlabs/dhinspeccion/MainViewModel.kt');
|
||||
|
||||
assert.match(screen, /Agregar foto con GPS/);
|
||||
assert.match(screen, /Agregar otra foto con GPS/);
|
||||
assert.match(screen, /Podés adjuntar todas las fotos que necesites/);
|
||||
assert.match(model, /loadEvidenceInternal\(findingId\)/);
|
||||
assert.doesNotMatch(screen, /máximo de 1 foto|solo una foto/i);
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import test from 'node:test';
|
||||
|
||||
function source(path: string): string {
|
||||
return readFileSync(resolve(process.cwd(), path), 'utf8');
|
||||
}
|
||||
|
||||
const closing = source('src/inspection-closing/inspection-closing.service.ts');
|
||||
const users = source('src/administration/users/users.controller.ts');
|
||||
const userService = source('src/administration/users/users.service.ts');
|
||||
const migration = source('src/database/migrations/1790124600000-f6-7-user-reusable-signature.ts');
|
||||
const android = source('../android-app/app/src/main/java/com/korexlabs/dhinspeccion/ui/ModernMobileActsScreen.kt');
|
||||
const labels = source('../android-app/app/src/main/java/com/korexlabs/dhinspeccion/ui/UiSpanishLabels.kt');
|
||||
const profile = source('../web-v2/src/pages/MyProfilePage.tsx');
|
||||
|
||||
test('F6.7 Acta lock and seal use SELECT-shaped version CTEs', () => {
|
||||
assert.doesNotMatch(closing, /RETURNING current_version AS "versionNumber"/);
|
||||
assert.equal((closing.match(/WITH updated AS \(/g) ?? []).length >= 2, true);
|
||||
assert.equal((closing.match(/SELECT current_version AS "versionNumber" FROM updated/g) ?? []).length >= 2, true);
|
||||
});
|
||||
test('F6.7 inspector signature is stored once in profile and copied into each sealed Acta', () => {
|
||||
assert.match(migration, /CREATE TABLE user_signature_profiles/);
|
||||
assert.match(migration, /image_data bytea NOT NULL/);
|
||||
assert.match(migration, /image_sha256 char\(64\) NOT NULL/);
|
||||
assert.match(users, /@Put\('self\/signature'\)/);
|
||||
assert.match(users, /@Get\('self\/signature\/content'\)/);
|
||||
assert.match(userService, /inspectInspectionSignatureFile/);
|
||||
assert.match(closing, /requireReusableInspectorSignature/);
|
||||
assert.match(closing, /createInspectorSignatureFromProfile/);
|
||||
assert.match(closing, /signatureMode: 'PROFILE_REUSABLE'/);
|
||||
});
|
||||
|
||||
test('F6.7 Android goes Draft to Para firmar to company manifestation without inspector drawing', () => {
|
||||
assert.match(labels, /"LOCKED" -> "Para firmar"/);
|
||||
assert.match(android, /Cerrar contenido y pasar a firma/);
|
||||
assert.match(android, /Firma del representante de la empresa \(acompañante\)/);
|
||||
assert.match(android, /Aplicar mi firma y cerrar Acta/);
|
||||
assert.doesNotMatch(android, /Firmá como inspector\/a/);
|
||||
assert.doesNotMatch(android, /inspectorSigned/);
|
||||
assert.doesNotMatch(android, /Text\(selected\.code/);
|
||||
assert.match(android, /companyOutcome\?\.status == "ABSENT"/);
|
||||
});
|
||||
test('F6.7 Dashboard exposes the reusable inspector signature clearly', () => {
|
||||
assert.match(profile, /FIRMA DEL INSPECTOR/);
|
||||
assert.match(profile, /Firma guardada para Actas/);
|
||||
assert.match(profile, /saveSelfSignature/);
|
||||
assert.match(profile, /Cada Acta conserva una copia propia de la firma/);
|
||||
});
|
||||
@@ -3,6 +3,7 @@ WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
COPY tsconfig*.json vite.config.ts index.html ./
|
||||
COPY public ./public
|
||||
COPY src ./src
|
||||
RUN npm run build
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="referrer" content="strict-origin-when-cross-origin" />
|
||||
<link rel="icon" type="image/webp" href="/favicon.webp" />
|
||||
<title>DH Inspección V2</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "dhv2-web",
|
||||
"version": "0.23.0-2",
|
||||
"version": "0.23.0-4",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "dhv2-web",
|
||||
"version": "0.23.0-2",
|
||||
"version": "0.23.0-4",
|
||||
"dependencies": {
|
||||
"maplibre-gl": "6.4.1",
|
||||
"react": "^19.0.0",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dhv2-web",
|
||||
"version": "0.23.0-2",
|
||||
"version": "0.23.0-4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 8.2 KiB |
@@ -9,6 +9,7 @@ import { CompanySignaturePage } from '../pages/CompanySignaturePage';
|
||||
import { DashboardPage } from '../pages/DashboardPage';
|
||||
import { LoginPage } from '../pages/LoginPage';
|
||||
import { NewUserPage } from '../pages/NewUserPage';
|
||||
import { MyProfilePage } from '../pages/MyProfilePage';
|
||||
import { RolesPage } from '../pages/RolesPage';
|
||||
import { AccessDeniedPage, NotFoundPage } from '../pages/SystemPages';
|
||||
import { UserDetailPage } from '../pages/UserDetailPage';
|
||||
@@ -45,6 +46,7 @@ export function App() {
|
||||
<Route element={<ProtectedRoute />}>
|
||||
<Route path="/change-password" element={<ChangePasswordPage />} />
|
||||
<Route element={<OperationalContextProvider><AppLayout /></OperationalContextProvider>}>
|
||||
<Route path="/mi-perfil" element={<MyProfilePage />} />
|
||||
<Route element={<PermissionRoute permission="dashboard.read" />}><Route index element={<DashboardPage />} /></Route>
|
||||
<Route element={<PermissionRoute permission="assets.read" />}><Route path="/mapa" element={<MapPage />} /></Route>
|
||||
<Route element={<PermissionRoute permission="assets.read" />}>
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export const APP_VERSION = '0.23.0-1';
|
||||
export const APP_PHASE = 'F6.1 · Contexto operativo Área–Operadora consolidado';
|
||||
export const APP_VERSION = '0.23.0-4';
|
||||
export const APP_PHASE = 'F6.7 · Cierre y firma por Acta';
|
||||
|
||||
@@ -100,11 +100,13 @@ export function AppLayout() {
|
||||
</nav>
|
||||
|
||||
<div className="sidebar-user">
|
||||
<div className="user-avatar">{user?.firstName?.[0]}{user?.lastName?.[0]}</div>
|
||||
<div className="user-copy">
|
||||
<strong>{user?.firstName} {user?.lastName}</strong>
|
||||
<small>{user?.roles.join(' · ') || user?.username}</small>
|
||||
</div>
|
||||
<NavLink to="/mi-perfil" onClick={close} className="sidebar-user-profile" title="Abrir Mi perfil">
|
||||
<div className="user-avatar">{user?.firstName?.[0]}{user?.lastName?.[0]}</div>
|
||||
<div className="user-copy">
|
||||
<strong>{user?.firstName} {user?.lastName}</strong>
|
||||
<small>Mi perfil · {user?.roles.join(' · ') || user?.username}</small>
|
||||
</div>
|
||||
</NavLink>
|
||||
<button className="icon-button dark" onClick={handleLogout} title="Cerrar sesión" aria-label="Cerrar sesión">
|
||||
<Icon name="logout" />
|
||||
</button>
|
||||
|
||||
@@ -98,6 +98,7 @@ export interface AdministrativeUser {
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
roles: RoleSummary[];
|
||||
smtpMode: 'SYSTEM' | 'CUSTOM';
|
||||
}
|
||||
|
||||
export interface Permission { id: string; code: string; description: string }
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { apiRequest } from './api';
|
||||
import type { AdministrativeUserProfile } from './userProfileApi';
|
||||
|
||||
export type UserSmtpMode = 'SYSTEM' | 'CUSTOM';
|
||||
export type UserSmtpSecurityMode = 'NONE' | 'STARTTLS' | 'TLS';
|
||||
|
||||
export interface UserSmtpCustomSettings {
|
||||
host: string;
|
||||
port: number;
|
||||
securityMode: UserSmtpSecurityMode;
|
||||
username: string;
|
||||
hasPassword: boolean;
|
||||
fromName: string;
|
||||
fromEmail: string;
|
||||
enabled: boolean;
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
export interface UserSmtpSettings {
|
||||
mode: UserSmtpMode;
|
||||
email: string;
|
||||
generalConfigured: boolean;
|
||||
custom: UserSmtpCustomSettings | null;
|
||||
}
|
||||
|
||||
|
||||
export interface UserReusableSignature {
|
||||
configured: boolean;
|
||||
mimeType: 'image/png' | null;
|
||||
sizeBytes: number | null;
|
||||
imageSha256: string | null;
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
export interface UserSmtpSettingsInput {
|
||||
mode: UserSmtpMode;
|
||||
host?: string;
|
||||
port?: number;
|
||||
securityMode?: UserSmtpSecurityMode;
|
||||
username?: string | null;
|
||||
password?: string | null;
|
||||
fromName?: string | null;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export function getSelfProfile() {
|
||||
return apiRequest<AdministrativeUserProfile>('/users/self/profile');
|
||||
}
|
||||
|
||||
export function updateSelfProfile(input: {
|
||||
email: string;
|
||||
phone?: string | null;
|
||||
jobTitle?: string | null;
|
||||
}) {
|
||||
return apiRequest<AdministrativeUserProfile>('/users/self/profile', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function getSelfSmtpSettings() {
|
||||
return apiRequest<UserSmtpSettings>('/users/self/smtp');
|
||||
}
|
||||
|
||||
export function saveSelfSmtpSettings(input: UserSmtpSettingsInput) {
|
||||
return apiRequest<UserSmtpSettings>('/users/self/smtp', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
}
|
||||
|
||||
export function testSelfSmtpSettings() {
|
||||
return apiRequest<{ ok: boolean; recipient: string; messageId: string }>('/users/self/smtp/test', {
|
||||
method: 'POST',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
export function getSelfSignature() {
|
||||
return apiRequest<UserReusableSignature>('/users/self/signature');
|
||||
}
|
||||
|
||||
export function saveSelfSignature(file: File) {
|
||||
const body = new FormData();
|
||||
body.append('file', file);
|
||||
return apiRequest<UserReusableSignature>('/users/self/signature', {
|
||||
method: 'PUT',
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
export function deleteSelfSignature() {
|
||||
return apiRequest<UserReusableSignature>('/users/self/signature', { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function selfSignatureContentUrl(signature: UserReusableSignature) {
|
||||
const version = signature.imageSha256 ? `?v=${encodeURIComponent(signature.imageSha256)}` : '';
|
||||
return `/api/v3/users/self/signature/content${version}`;
|
||||
}
|
||||
@@ -21,6 +21,7 @@ export interface UserProfileInput {
|
||||
|
||||
export interface CreateUserProfileInput extends UserProfileInput {
|
||||
username: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
password: string;
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { FormEvent } from 'react';
|
||||
import { Alert, LoadingBlock, errorMessage } from '../components/Feedback';
|
||||
import { useAuth } from '../auth/AuthContext';
|
||||
import { initials } from '../lib/format';
|
||||
import {
|
||||
deleteSelfSignature,
|
||||
getSelfProfile,
|
||||
getSelfSignature,
|
||||
getSelfSmtpSettings,
|
||||
saveSelfSignature,
|
||||
saveSelfSmtpSettings,
|
||||
selfSignatureContentUrl,
|
||||
testSelfSmtpSettings,
|
||||
updateSelfProfile,
|
||||
} from '../lib/myProfileApi';
|
||||
import type {
|
||||
UserReusableSignature,
|
||||
UserSmtpMode,
|
||||
UserSmtpSecurityMode,
|
||||
UserSmtpSettings,
|
||||
} from '../lib/myProfileApi';
|
||||
import type { AdministrativeUserProfile } from '../lib/userProfileApi';
|
||||
|
||||
export function MyProfilePage() {
|
||||
const { user } = useAuth();
|
||||
const [profile, setProfile] = useState<AdministrativeUserProfile | null>(null);
|
||||
const [smtp, setSmtp] = useState<UserSmtpSettings | null>(null);
|
||||
const [signature, setSignature] = useState<UserReusableSignature | null>(null);
|
||||
const [signatureFile, setSignatureFile] = useState<File | null>(null);
|
||||
const [mode, setMode] = useState<UserSmtpMode>('SYSTEM');
|
||||
const [host, setHost] = useState('');
|
||||
const [port, setPort] = useState(587);
|
||||
const [securityMode, setSecurityMode] = useState<UserSmtpSecurityMode>('STARTTLS');
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [fromName, setFromName] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [success, setSuccess] = useState('');
|
||||
|
||||
const applySmtp = (settings: UserSmtpSettings) => {
|
||||
setSmtp(settings);
|
||||
setMode(settings.mode);
|
||||
setHost(settings.custom?.host ?? '');
|
||||
setPort(settings.custom?.port ?? 587);
|
||||
setSecurityMode(settings.custom?.securityMode ?? 'STARTTLS');
|
||||
setUsername(settings.custom?.username ?? '');
|
||||
setFromName(settings.custom?.fromName ?? '');
|
||||
setPassword('');
|
||||
};
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [loadedProfile, loadedSmtp, loadedSignature] = await Promise.all([
|
||||
getSelfProfile(),
|
||||
getSelfSmtpSettings(),
|
||||
getSelfSignature(),
|
||||
]);
|
||||
setProfile(loadedProfile);
|
||||
applySmtp(loadedSmtp);
|
||||
setSignature(loadedSignature);
|
||||
} catch (requestError) {
|
||||
setError(errorMessage(requestError));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => { void load(); }, []);
|
||||
|
||||
const saveProfile = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (!profile) return;
|
||||
setError(''); setSuccess(''); setSaving('profile');
|
||||
try {
|
||||
const form = new FormData(event.currentTarget);
|
||||
const updated = await updateSelfProfile({
|
||||
email: String(form.get('email') ?? '').trim(),
|
||||
phone: String(form.get('phone') ?? '').trim() || null,
|
||||
jobTitle: String(form.get('jobTitle') ?? '').trim() || null,
|
||||
});
|
||||
setProfile(updated);
|
||||
setSuccess('Perfil actualizado correctamente.');
|
||||
} catch (requestError) {
|
||||
setError(errorMessage(requestError));
|
||||
} finally {
|
||||
setSaving('');
|
||||
}
|
||||
};
|
||||
|
||||
const saveSignature = async () => {
|
||||
if (!signatureFile) return;
|
||||
setError(''); setSuccess(''); setSaving('signature');
|
||||
try {
|
||||
const updated = await saveSelfSignature(signatureFile);
|
||||
setSignature(updated);
|
||||
setSignatureFile(null);
|
||||
setSuccess('Firma del inspector guardada. Se aplicará automáticamente al cerrar cada Acta.');
|
||||
} catch (requestError) {
|
||||
setError(errorMessage(requestError));
|
||||
} finally {
|
||||
setSaving('');
|
||||
}
|
||||
};
|
||||
|
||||
const clearSignature = async () => {
|
||||
setError(''); setSuccess(''); setSaving('signature-delete');
|
||||
try {
|
||||
const updated = await deleteSelfSignature();
|
||||
setSignature(updated);
|
||||
setSignatureFile(null);
|
||||
setSuccess('Firma guardada eliminada.');
|
||||
} catch (requestError) {
|
||||
setError(errorMessage(requestError));
|
||||
} finally {
|
||||
setSaving('');
|
||||
}
|
||||
};
|
||||
|
||||
const saveSmtp = async () => {
|
||||
setError(''); setSuccess(''); setSaving('smtp');
|
||||
try {
|
||||
const updated = await saveSelfSmtpSettings(mode === 'SYSTEM' ? {
|
||||
mode: 'SYSTEM',
|
||||
} : {
|
||||
mode: 'CUSTOM', host: host.trim(), port, securityMode,
|
||||
username: username.trim() || null,
|
||||
password: password || undefined,
|
||||
fromName: fromName.trim() || null,
|
||||
enabled: true,
|
||||
});
|
||||
applySmtp(updated);
|
||||
setSuccess(mode === 'SYSTEM' ? 'Usarás el SMTP general.' : 'SMTP propio guardado.');
|
||||
} catch (requestError) {
|
||||
setError(errorMessage(requestError));
|
||||
} finally {
|
||||
setSaving('');
|
||||
}
|
||||
};
|
||||
|
||||
const testSmtp = async () => {
|
||||
setError(''); setSuccess(''); setSaving('test');
|
||||
try {
|
||||
const result = await testSelfSmtpSettings();
|
||||
setSuccess(`Correo de prueba enviado a ${result.recipient}.`);
|
||||
} catch (requestError) {
|
||||
setError(errorMessage(requestError));
|
||||
} finally {
|
||||
setSaving('');
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <LoadingBlock label="Cargando tu perfil…" />;
|
||||
if (!profile || !smtp || !signature) return <Alert>{error || 'No se pudo cargar el perfil.'}</Alert>;
|
||||
|
||||
const isInspector = profile.roles.some((role) => role.code === 'inspector');
|
||||
|
||||
return <section>
|
||||
<div className="page-heading user-heading">
|
||||
<div className="profile-title">
|
||||
<span className="profile-avatar">{initials(profile.firstName, profile.lastName)}</span>
|
||||
<div>
|
||||
<span className="eyebrow">MI PERFIL</span>
|
||||
<h1>{profile.firstName} {profile.lastName}</h1>
|
||||
<p>@{profile.username} · {profile.jobTitle || 'Función sin informar'}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{error && <Alert>{error}</Alert>}
|
||||
{success && <Alert type="success">{success}</Alert>}
|
||||
|
||||
<div className="detail-grid">
|
||||
<form className="panel form-panel" onSubmit={saveProfile}>
|
||||
<div className="panel-heading">
|
||||
<div><span className="eyebrow">CONTACTO</span><h2>Datos del usuario</h2></div>
|
||||
</div>
|
||||
<div className="form-grid">
|
||||
<label className="field"><span>Nombres y apellidos</span><input value={`${profile.firstName} ${profile.lastName}`} disabled /></label>
|
||||
<label className="field"><span>Email institucional *</span><input name="email" type="email" defaultValue={profile.email ?? ''} required /></label>
|
||||
<label className="field"><span>Teléfono</span><input name="phone" type="tel" defaultValue={profile.phone ?? ''} /></label>
|
||||
<label className="field"><span>Cargo / función</span><input name="jobTitle" defaultValue={profile.jobTitle ?? ''} /></label>
|
||||
</div>
|
||||
<div className="form-actions">
|
||||
<button className="button primary" type="submit" disabled={saving === 'profile'}>
|
||||
{saving === 'profile' ? 'Guardando…' : 'Guardar perfil'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div className="panel form-panel">
|
||||
<div className="panel-heading">
|
||||
<div><span className="eyebrow">CORREO SALIENTE</span><h2>SMTP personal</h2></div>
|
||||
</div>
|
||||
<p className="muted-copy">Por defecto, tus correos salen mediante el SMTP general. Podés cambiar a una cuenta SMTP propia con un clic.</p>
|
||||
<div className="choice-grid">
|
||||
<label className={`choice-card ${mode === 'SYSTEM' ? 'selected' : ''}`}>
|
||||
<input type="radio" name="smtpMode" checked={mode === 'SYSTEM'} onChange={() => setMode('SYSTEM')} />
|
||||
<span><strong>Usar SMTP general</strong><small>{smtp.generalConfigured ? 'Configurado y disponible' : 'Todavía no configurado por el administrador'}</small></span>
|
||||
<span className="icon">✓</span>
|
||||
</label>
|
||||
<label className={`choice-card ${mode === 'CUSTOM' ? 'selected' : ''}`}>
|
||||
<input type="radio" name="smtpMode" checked={mode === 'CUSTOM'} onChange={() => setMode('CUSTOM')} />
|
||||
<span><strong>Usar SMTP propio</strong><small>Los envíos saldrán con tu cuenta {profile.email}</small></span>
|
||||
<span className="icon">✓</span>
|
||||
</label>
|
||||
</div>
|
||||
{mode === 'CUSTOM' && <>
|
||||
<div className="form-grid" style={{ marginTop: 16 }}>
|
||||
<label className="field"><span>Servidor SMTP *</span><input value={host} onChange={(event) => setHost(event.target.value)} placeholder="smtp.ejemplo.com" /></label>
|
||||
<label className="field"><span>Puerto *</span><input type="number" min={1} max={65535} value={port} onChange={(event) => setPort(Number(event.target.value))} /></label>
|
||||
<label className="field"><span>Seguridad *</span><select value={securityMode} onChange={(event) => setSecurityMode(event.target.value as UserSmtpSecurityMode)}><option value="STARTTLS">STARTTLS</option><option value="TLS">TLS</option><option value="NONE">Sin cifrado</option></select></label>
|
||||
<label className="field"><span>Usuario SMTP</span><input value={username} onChange={(event) => setUsername(event.target.value)} autoComplete="username" /></label>
|
||||
<label className="field"><span>Contraseña SMTP</span><input type="password" value={password} onChange={(event) => setPassword(event.target.value)} autoComplete="new-password" placeholder={smtp.custom?.hasPassword ? 'Dejar vacío para conservarla' : 'Contraseña SMTP'} /></label>
|
||||
<label className="field"><span>Nombre del remitente</span><input value={fromName} onChange={(event) => setFromName(event.target.value)} placeholder={`${profile.firstName} ${profile.lastName}`} /></label>
|
||||
</div>
|
||||
<p className="muted-copy">La contraseña se cifra en el servidor y nunca vuelve a mostrarse. El remitente será <strong>{profile.email}</strong>.</p>
|
||||
</>}
|
||||
<div className="form-actions wrap-actions">
|
||||
<button className="button primary" type="button" onClick={saveSmtp} disabled={saving === 'smtp' || (mode === 'CUSTOM' && (!host.trim() || !port))}>{saving === 'smtp' ? 'Guardando…' : 'Guardar configuración'}</button>
|
||||
<button className="button secondary" type="button" onClick={testSmtp} disabled={Boolean(saving)}>{saving === 'test' ? 'Enviando…' : 'Enviar correo de prueba'}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{isInspector && <div className="panel form-panel" style={{ marginTop: 16 }}>
|
||||
<div className="panel-heading">
|
||||
<div><span className="eyebrow">FIRMA DEL INSPECTOR</span><h2>Firma guardada para Actas</h2></div>
|
||||
</div>
|
||||
<p className="muted-copy">Cargala una sola vez. Cuando cierres un Acta desde la APK, el contenido quedará en estado <strong>Para firmar</strong>; después firma el acompañante y, al finalizar, el sistema incorpora automáticamente esta firma del inspector al ejemplar inmutable.</p>
|
||||
{signature.configured && <div className="signature-profile-preview">
|
||||
<img src={selfSignatureContentUrl(signature)} alt="Firma guardada del inspector" />
|
||||
<div><strong>Firma configurada</strong><small>PNG · {Math.max(1, Math.round((signature.sizeBytes ?? 0) / 1024))} KB</small></div>
|
||||
</div>}
|
||||
<div className="form-grid" style={{ marginTop: 14 }}>
|
||||
<label className="field"><span>{signature.configured ? 'Reemplazar firma PNG' : 'Firma PNG *'}</span><input type="file" accept="image/png" onChange={(event) => setSignatureFile(event.target.files?.[0] ?? null)} /></label>
|
||||
</div>
|
||||
<p className="muted-copy">La imagen debe ser PNG y pesar como máximo 1 MB. Cada Acta conserva una copia propia de la firma y su SHA-256; cambiar la firma del perfil no altera Actas ya cerradas.</p>
|
||||
<div className="form-actions wrap-actions">
|
||||
<button className="button primary" type="button" onClick={saveSignature} disabled={!signatureFile || saving === 'signature'}>{saving === 'signature' ? 'Guardando…' : signature.configured ? 'Reemplazar firma' : 'Guardar firma'}</button>
|
||||
{signature.configured && <button className="button secondary" type="button" onClick={clearSignature} disabled={saving === 'signature-delete'}>{saving === 'signature-delete' ? 'Eliminando…' : 'Eliminar firma guardada'}</button>}
|
||||
</div>
|
||||
</div>}
|
||||
<div className="panel" style={{ marginTop: 16 }}>
|
||||
<div className="panel-heading"><div><span className="eyebrow">SEGURIDAD</span><h2>Cuenta</h2></div></div>
|
||||
<p>Tu email es obligatorio para operar en DH Inspección. La contraseña SMTP nunca se muestra ni se incluye en auditorías.</p>
|
||||
<p className="muted-copy">Usuario autenticado: @{user?.username ?? profile.username}</p>
|
||||
</div>
|
||||
</section>;
|
||||
}
|
||||
@@ -30,15 +30,15 @@ export function NewUserPage() {
|
||||
setError('');
|
||||
const data = new FormData(event.currentTarget);
|
||||
const email = String(data.get('email') ?? '').trim();
|
||||
if (inspectorSelected && !email) {
|
||||
setError('El email es obligatorio para usuarios con rol Inspector porque allí recibirán la documentación de sus inspecciones.');
|
||||
if (!email) {
|
||||
setError('El email es obligatorio para todos los usuarios de Hidrocarburos.');
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const created = await createUserProfile({
|
||||
username: String(data.get('username')),
|
||||
email: email || null,
|
||||
email,
|
||||
dni: String(data.get('dni') ?? '').trim() || null,
|
||||
phone: String(data.get('phone') ?? '').trim() || null,
|
||||
jobTitle: String(data.get('jobTitle') ?? '').trim() || null,
|
||||
@@ -75,10 +75,10 @@ export function NewUserPage() {
|
||||
</div>
|
||||
|
||||
<div className="form-section">
|
||||
<div><h2>Acceso y contacto</h2><p className="section-copy">El email del Inspector se utiliza también como destinatario de la documentación al cerrar la inspección.</p></div>
|
||||
<div><h2>Acceso y contacto</h2><p className="section-copy">Cada usuario debe tener un email institucional. Los Inspectores también lo utilizan en la entrega documental de sus Actas.</p></div>
|
||||
<div className="form-grid">
|
||||
<label className="field"><span>Usuario <em>obligatorio</em></span><input name="username" required minLength={3} maxLength={80} pattern="[a-zA-Z][a-zA-Z0-9._-]+" /></label>
|
||||
<label className="field"><span>Email {inspectorSelected ? <em>obligatorio para Inspector</em> : <em>recomendado</em>}</span><input name="email" type="email" maxLength={320} required={inspectorSelected} /></label>
|
||||
<label className="field"><span>Email <em>obligatorio</em></span><input name="email" type="email" maxLength={320} required /></label>
|
||||
</div>
|
||||
{inspectorSelected && <div className="temporal-notice"><Icon name="mail" /><p><strong>Inspector:</strong> este email recibirá copia de las Actas/Informe correspondientes al cierre de la inspección.</p></div>}
|
||||
</div>
|
||||
|
||||
@@ -57,8 +57,8 @@ export function UserDetailPage() {
|
||||
setError(''); setSuccess('');
|
||||
const data = new FormData(event.currentTarget);
|
||||
const email = String(data.get('email') ?? '').trim();
|
||||
if (inspectorSelected && !email) {
|
||||
setError('El email es obligatorio para un Inspector porque allí recibe la documentación de sus inspecciones.');
|
||||
if (!email) {
|
||||
setError('El email es obligatorio para todos los usuarios de Hidrocarburos.');
|
||||
return;
|
||||
}
|
||||
setSaving('profile');
|
||||
@@ -139,6 +139,7 @@ export function UserDetailPage() {
|
||||
<div className="detail-grid">
|
||||
<form className="panel form-panel" onSubmit={saveProfile}>
|
||||
<div className="panel-heading"><div><span className="eyebrow">PERFIL</span><h2>Datos personales y contacto</h2></div><span className={`status-badge ${user.status.toLowerCase()}`}>{user.status === 'ACTIVE' ? 'Activo' : 'Inactivo'}</span></div>
|
||||
<p className="muted-copy">Correo saliente: <strong>{user.smtpMode === 'CUSTOM' ? 'SMTP propio' : 'SMTP general'}</strong>. Cada usuario administra su modalidad desde Mi perfil.</p>
|
||||
<div className="form-grid">
|
||||
<label className="field"><span>Nombre</span><input name="firstName" defaultValue={user.firstName} required disabled={!canUpdate} /></label>
|
||||
<label className="field"><span>Apellido</span><input name="lastName" defaultValue={user.lastName} required disabled={!canUpdate} /></label>
|
||||
@@ -147,7 +148,7 @@ export function UserDetailPage() {
|
||||
<label className="field"><span>Cargo / función</span><input name="jobTitle" defaultValue={user.jobTitle ?? ''} maxLength={160} disabled={!canUpdate} /></label>
|
||||
<label className="field"><span>Legajo / matrícula</span><input name="employeeNumber" defaultValue={user.employeeNumber ?? ''} maxLength={80} disabled={!canUpdate} /></label>
|
||||
<label className="field"><span>Usuario</span><input name="username" defaultValue={user.username} required disabled={!canUpdate} /></label>
|
||||
<label className="field"><span>Email {inspectorSelected && <em>obligatorio para Inspector</em>}</span><input name="email" type="email" defaultValue={user.email ?? ''} required={inspectorSelected} disabled={!canUpdate} /></label>
|
||||
<label className="field"><span>Email <em>obligatorio</em></span><input name="email" type="email" defaultValue={user.email ?? ''} required disabled={!canUpdate} /></label>
|
||||
</div>
|
||||
{inspectorSelected && <div className="temporal-notice"><Icon name="mail" /><p><strong>Destinatario del Inspector:</strong> al finalizar una inspección, la documentación se enviará también a <strong>{user.email || 'este email cuando lo completes'}</strong>.</p></div>}
|
||||
<div className="metadata-grid"><div><small>Último acceso</small><strong>{formatDate(user.lastLoginAt)}</strong></div><div><small>Último cambio de clave</small><strong>{formatDate(user.passwordChangedAt)}</strong></div><div><small>Intentos fallidos</small><strong>{user.failedLoginAttempts}</strong></div><div><small>Bloqueado hasta</small><strong>{formatDate(user.lockedUntil)}</strong></div></div>
|
||||
|
||||
@@ -46,6 +46,8 @@ a { color: inherit; }
|
||||
.nav-link.active .icon { color: #73a0ff; }
|
||||
|
||||
.sidebar-user { display: grid; grid-template-columns: auto minmax(0,1fr) auto; gap: 10px; align-items: center; margin-top: auto; padding: 16px 6px 0; border-top: 1px solid rgba(255,255,255,.09); }
|
||||
.sidebar-user-profile { display:grid; grid-template-columns:auto minmax(0,1fr); gap:10px; align-items:center; min-width:0; color:inherit; text-decoration:none; border-radius:10px; padding:4px; }
|
||||
.sidebar-user-profile:hover { background:rgba(255,255,255,.06); }
|
||||
.user-avatar, .mini-avatar, .profile-avatar { display: grid; place-items: center; color: #2759c3; background: #dce8ff; font-weight: 800; }
|
||||
.user-avatar { width: 34px; height: 34px; border-radius: 50%; font-size: 11px; }
|
||||
.user-copy { min-width: 0; }
|
||||
@@ -1348,3 +1350,30 @@ code { color: #5e6677; font-family: ui-monospace, monospace; font-size: 9px; }
|
||||
cursor: default;
|
||||
opacity: .65;
|
||||
}
|
||||
|
||||
/* F6.7 · firma reutilizable del inspector */
|
||||
.signature-profile-preview {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
max-width: 620px;
|
||||
padding: 14px 16px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
background: #f7faf9;
|
||||
}
|
||||
.signature-profile-preview img {
|
||||
width: min(240px, 46%);
|
||||
height: 88px;
|
||||
object-fit: contain;
|
||||
border-radius: 10px;
|
||||
background: #fff;
|
||||
border: 1px solid #e3e7e5;
|
||||
}
|
||||
.signature-profile-preview strong,
|
||||
.signature-profile-preview small { display: block; }
|
||||
.signature-profile-preview small { margin-top: 4px; color: var(--muted); }
|
||||
@media (max-width: 640px) {
|
||||
.signature-profile-preview { align-items: flex-start; flex-direction: column; }
|
||||
.signature-profile-preview img { width: 100%; }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user