untitled

Pasted Nov 15, 2026, 3:34 AM1 file673 lines

Scan to open on your phone

Point a camera at the QR code - it opens this exact paste, no app needed.

https://codepastes.com/zzgs4w9pgdsgs0yh
untitled

package com.negocio.desinfectantes

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Apps
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.PersonAdd
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.text.selection.SelectionContainer
import kotlinx.coroutines.launch
import com.negocio.desinfectantes.data.CuentaService
import com.negocio.desinfectantes.data.CrearUsuarioResultado
import com.negocio.desinfectantes.data.UsuarioAdministrado

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CrearUsuarioScreen(
    modifier: Modifier = Modifier,
    idAdministrador: String,
    rolAdministrador: String,
    onVolver: () -> Unit
) {
    var nombreCompleto by remember { mutableStateOf("") }
    var nombreUsuario by remember { mutableStateOf("") }
    var rolSeleccionado by remember { mutableStateOf("vendedor") }

    val modulosDisponibles = listOf(
        "Inicio",
        "Ventas",
        "Productos",
        "Clientes",
        "Reportes",
        "Producción",
        "Inventario",
        "Lotes"
    )

    var modulosSeleccionados by remember {
        mutableStateOf(setOf("Inicio"))
    }

    var menuRoles by remember { mutableStateOf(false) }
    var cargando by remember { mutableStateOf(false) }
    var mensajeError by remember { mutableStateOf<String?>(null) }

    var resultadoCreacion: CrearUsuarioResultado? by remember {
        mutableStateOf(null)
    }

    var usuarios by remember {
        mutableStateOf<List<UsuarioAdministrado>>(emptyList())
    }

    var cargandoUsuarios by remember {
        mutableStateOf(false)
    }

    var errorUsuarios by remember {
        mutableStateOf<String?>(null)
    }

    var actualizarLista by remember {
        mutableIntStateOf(0)
    }

    val scope = rememberCoroutineScope()

    LaunchedEffect(actualizarLista) {
        cargandoUsuarios = true
        errorUsuarios = null

        try {
            usuarios = CuentaService().listarUsuarios()
        } catch (e: Exception) {
            errorUsuarios = e.message
                ?: "No se pudieron cargar los usuarios."
        } finally {
            cargandoUsuarios = false
        }
    }

    Column(
        modifier = modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.surface)
            .verticalScroll(rememberScrollState())
            .padding(horizontal = 20.dp, vertical = 16.dp),
        verticalArrangement = Arrangement.spacedBy(20.dp)
    ) {

        // ENCABEZADO
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            IconButton(onClick = onVolver) {
                Icon(
                    imageVector = Icons.Default.ArrowBack,
                    contentDescription = "Volver"
                )
            }

            Spacer(modifier = Modifier.width(8.dp))

            Column {
                Text(
                    text = "PRESTIGE CLEAN",
                    style = MaterialTheme.typography.labelMedium,
                    color = MaterialTheme.colorScheme.primary,
                    fontWeight = FontWeight.Bold
                )

                Text(
                    text = "Administración de cuentas",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }

        // PRESENTACIÓN
        Card(
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(26.dp),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer
            )
        ) {
            Row(
                modifier = Modifier.padding(20.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Surface(
                    shape = RoundedCornerShape(18.dp),
                    color = MaterialTheme.colorScheme.primary,
                    modifier = Modifier.size(58.dp)
                ) {
                    Box(contentAlignment = Alignment.Center) {
                        Icon(
                            imageVector = Icons.Default.PersonAdd,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.onPrimary,
                            modifier = Modifier.size(30.dp)
                        )
                    }
                }

                Spacer(modifier = Modifier.width(16.dp))

                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = "Crear usuario",
                        style = MaterialTheme.typography.headlineSmall,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.onPrimaryContainer
                    )

                    Spacer(modifier = Modifier.height(4.dp))

                    Text(
                        text = "Registra una nueva cuenta y configura sus accesos a Prestige Clean.",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onPrimaryContainer
                    )
                }
            }
        }

        // SECCIÓN DATOS PERSONALES
        Column(
            verticalArrangement = Arrangement.spacedBy(10.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "01",
                    color = MaterialTheme.colorScheme.primary,
                    fontWeight = FontWeight.Bold,
                    style = MaterialTheme.typography.titleMedium
                )

                Spacer(modifier = Modifier.width(10.dp))

                Column {
                    Text(
                        text = "Información personal",
                        style = MaterialTheme.typography.titleLarge,
                        fontWeight = FontWeight.Bold
                    )

                    Text(
                        text = "Datos básicos de la nueva cuenta",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

            Card(
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(22.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceContainerLow
                )
            ) {
                Column(
                    modifier = Modifier.padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(14.dp)
                ) {
                    OutlinedTextField(
                        value = nombreCompleto,
                        onValueChange = { nombreCompleto = it },
                        label = { Text("Nombre completo") },
                        leadingIcon = {
                            Icon(
                                imageVector = Icons.Default.Person,
                                contentDescription = null
                            )
                        },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        enabled = !cargando,
                        shape = RoundedCornerShape(14.dp)
                    )

                    OutlinedTextField(
                        value = nombreUsuario,
                        onValueChange = {
                            nombreUsuario = it.lowercase().filter { caracter ->
                                caracter.isLetterOrDigit() ||
                                        caracter == '.' ||
                                        caracter == '_' ||
                                        caracter == '-'
                            }
                        },
                        label = { Text("Nombre de usuario") },
                        placeholder = { Text("Ej. juan.perez") },
                        leadingIcon = {
                            Icon(
                                imageVector = Icons.Default.Apps,
                                contentDescription = null
                            )
                        },
                        supportingText = {
                            Text("Mínimo 3 caracteres. Sin espacios.")
                        },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        enabled = !cargando,
                        shape = RoundedCornerShape(14.dp)
                    )

                    ExposedDropdownMenuBox(
                        expanded = menuRoles,
                        onExpandedChange = {
                            if (!cargando) menuRoles = !menuRoles
                        }
                    ) {
                        OutlinedTextField(
                            value = if (rolSeleccionado == "vendedor") {
                                "Vendedor"
                            } else {
                                "Administrador secundario"
                            },
                            onValueChange = {},
                            readOnly = true,
                            label = { Text("Rol del usuario") },
                            leadingIcon = {
                                Icon(
                                    imageVector = Icons.Default.Person,
                                    contentDescription = null
                                )
                            },
                            trailingIcon = {
                                ExposedDropdownMenuDefaults.TrailingIcon(
                                    expanded = menuRoles
                                )
                            },
                            modifier = Modifier
                                .menuAnchor()
                                .fillMaxWidth(),
                            enabled = !cargando,
                            shape = RoundedCornerShape(14.dp)
                        )

                        ExposedDropdownMenu(
                            expanded = menuRoles,
                            onDismissRequest = { menuRoles = false }
                        ) {
                            DropdownMenuItem(
                                text = { Text("Vendedor") },
                                onClick = {
                                    rolSeleccionado = "vendedor"
                                    menuRoles = false
                                }
                            )

                            DropdownMenuItem(
                                text = { Text("Administrador secundario") },
                                onClick = {
                                    rolSeleccionado = "administrador_secundario"
                                    menuRoles = false
                                }
                            )
                        }
                    }
                }
            }
        }

        // SECCIÓN PERMISOS
        Column(
            verticalArrangement = Arrangement.spacedBy(10.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "02",
                    color = MaterialTheme.colorScheme.primary,
                    fontWeight = FontWeight.Bold,
                    style = MaterialTheme.typography.titleMedium
                )

                Spacer(modifier = Modifier.width(10.dp))

                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = "Permisos de acceso",
                        style = MaterialTheme.typography.titleLarge,
                        fontWeight = FontWeight.Bold
                    )

                    Text(
                        text = "Selecciona qué partes de la aplicación podrá utilizar.",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

            Card(
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(22.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceContainerLow
                )
            ) {
                Column(
                    modifier = Modifier.padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Column {
                            Text(
                                text = "Módulos disponibles",
                                fontWeight = FontWeight.Bold,
                                style = MaterialTheme.typography.titleMedium
                            )

                            Text(
                                text = "${modulosSeleccionados.size} de ${modulosDisponibles.size} seleccionados",
                                color = MaterialTheme.colorScheme.primary,
                                style = MaterialTheme.typography.bodySmall
                            )
                        }

                        Surface(
                            shape = CircleShape,
                            color = MaterialTheme.colorScheme.primaryContainer
                        ) {
                            Icon(
                                imageVector = Icons.Default.Apps,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.onPrimaryContainer,
                                modifier = Modifier.padding(10.dp)
                            )
                        }
                    }

                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        TextButton(
                            onClick = {
                                modulosSeleccionados = modulosDisponibles.toSet()
                            },
                            enabled = !cargando
                        ) {
                            Text("Seleccionar todos")
                        }

                        TextButton(
                            onClick = {
                                modulosSeleccionados = emptySet()
                            },
                            enabled = !cargando
                        ) {
                            Text("Quitar todos")
                        }
                    }

                    HorizontalDivider()

                    modulosDisponibles.forEach { modulo ->
                        val seleccionado = modulo in modulosSeleccionados

                        Surface(
                            modifier = Modifier.fillMaxWidth(),
                            shape = RoundedCornerShape(14.dp),
                            color = if (seleccionado) {
                                MaterialTheme.colorScheme.primaryContainer.copy(
                                    alpha = 0.55f
                                )
                            } else {
                                MaterialTheme.colorScheme.surface
                            }
                        ) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(horizontal = 12.dp, vertical = 5.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    imageVector = Icons.Default.Apps,
                                    contentDescription = null,
                                    tint = if (seleccionado) {
                                        MaterialTheme.colorScheme.primary
                                    } else {
                                        MaterialTheme.colorScheme.onSurfaceVariant
                                    },
                                    modifier = Modifier.size(21.dp)
                                )

                                Spacer(modifier = Modifier.width(12.dp))

                                Text(
                                    text = modulo,
                                    modifier = Modifier.weight(1f),
                                    fontWeight = if (seleccionado) {
                                        FontWeight.SemiBold
                                    } else {
                                        FontWeight.Normal
                                    }
                                )

                                Checkbox(
                                    checked = seleccionado,
                                    enabled = !cargando,
                                    onCheckedChange = { marcado ->
                                        modulosSeleccionados =
                                            if (marcado) {
                                                modulosSeleccionados + modulo
                                            } else {
                                                modulosSeleccionados - modulo
                                            }
                                    }
                                )
                            }
                        }
                    }
                }
            }
        }

        // MENSAJE DE ERROR
        if (mensajeError != null) {
            Surface(
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(14.dp),
                color = MaterialTheme.colorScheme.errorContainer
            ) {
                Text(
                    text = mensajeError!!,
                    modifier = Modifier.padding(14.dp),
                    color = MaterialTheme.colorScheme.onErrorContainer,
                    style = MaterialTheme.typography.bodyMedium
                )
            }
        }

        // BOTÓN CREAR
        Button(
            onClick = {
                mensajeError = null

                scope.launch {
                    cargando = true

                    try {
                        resultadoCreacion = CuentaService().crearUsuario(
                            nombreCompleto = nombreCompleto.trim(),
                            nombreUsuario = nombreUsuario.trim(),
                            rol = rolSeleccionado,
                            modulos = modulosSeleccionados.toList()
                        )

                        actualizarLista++

                    } catch (e: Exception) {
                        mensajeError = e.message
                            ?: "No se pudo crear el usuario."
                    } finally {
                        cargando = false
                    }
                }
            },
            modifier = Modifier
                .fillMaxWidth()
                .height(58.dp),
            enabled = !cargando &&
                    modulosSeleccionados.isNotEmpty() &&
                    nombreCompleto.isNotBlank() &&
                    nombreUsuario.length >= 3,
            shape = RoundedCornerShape(16.dp)
        ) {
            if (cargando) {
                CircularProgressIndicator(
                    modifier = Modifier.size(23.dp),
                    color = MaterialTheme.colorScheme.onPrimary,
                    strokeWidth = 2.dp
                )
            } else {
                Icon(
                    imageVector = Icons.Default.PersonAdd,
                    contentDescription = null
                )

                Spacer(modifier = Modifier.width(10.dp))

                Text(
                    text = "Crear usuario",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold
                )
            }
        }

        // INFORMACIÓN DE CONTRASEÑA
        Surface(
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(16.dp),
            color = MaterialTheme.colorScheme.secondaryContainer.copy(
                alpha = 0.55f
            )
        ) {
            Row(
                modifier = Modifier.padding(14.dp),
                verticalAlignment = Alignment.Top
            ) {
                Icon(
                    imageVector = Icons.Default.CheckCircle,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.onSecondaryContainer
                )

                Spacer(modifier = Modifier.width(10.dp))

                Text(
                    text = "La contraseña temporal se generará automáticamente. El usuario deberá cambiarla cuando inicie sesión por primera vez.",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSecondaryContainer
                )
            }
        }

        Spacer(modifier = Modifier.height(8.dp))
    }

    // VENTANA DE CONFIRMACIÓN
    resultadoCreacion?.let { resultado ->
        AlertDialog(
            onDismissRequest = {},
            shape = RoundedCornerShape(24.dp),
            title = {
                Column(
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Surface(
                        shape = CircleShape,
                        color = MaterialTheme.colorScheme.primaryContainer
                    ) {
                        Icon(
                            imageVector = Icons.Default.CheckCircle,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.padding(12.dp).size(30.dp)
                        )
                    }

                    Text(
                        text = "¡Usuario creado!",
                        fontWeight = FontWeight.Bold
                    )
                }
            },
            text = {
                Column(
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Text(
                        text = "La cuenta se ha registrado correctamente."
                    )

                    Text("Nombre: ${resultado.nombreCompleto}")
                    Text("Usuario: ${resultado.usuario}")
                    Text("Rol: ${resultado.rol}")

                    HorizontalDivider()

                    Text(
                        text = "Contraseña temporal",
                        fontWeight = FontWeight.Bold
                    )

                    Surface(
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(12.dp),
                        color = MaterialTheme.colorScheme.surfaceContainerHigh
                    ) {
                        SelectionContainer {
                            Text(
                                text = resultado.contrasenaTemporal,
                                modifier = Modifier.padding(14.dp),
                                style = MaterialTheme.typography.titleLarge,
                                fontWeight = FontWeight.Bold
                            )
                        }
                    }

                    Text(
                        text = "Guarda esta contraseña y entrégasela al usuario. No volverá a mostrarse después de cerrar esta ventana.",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            },
            confirmButton = {
                Button(
                    onClick = {
                        resultadoCreacion = null
                        nombreCompleto = ""
                        nombreUsuario = ""
                        rolSeleccionado = "vendedor"
                    }
                ) {
                    Text("Entendido")
                }
            }
        )
    }
}

25,546 chars · codepastes.com