Files
front-Censo/src/components/Editar.tsx
T

468 lines
14 KiB
TypeScript
Raw Normal View History

2025-10-29 13:41:03 -06:00
"use client";
2025-10-29 13:59:44 -06:00
2025-10-29 13:41:03 -06:00
import { useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import axios from "axios";
2025-10-29 13:59:44 -06:00
import Cookies from "js-cookie";
import toast from "react-hot-toast";
2025-11-03 19:07:01 -06:00
import { SO_POR_EQUIPO } from "@/data/so_por_equipo";
import { AREAS } from "@/data/areas";
2025-10-29 13:41:03 -06:00
2025-10-31 20:41:33 -06:00
import "../app/styles/layout/agregarEquipo.scss";
import "./editar.css";
2025-11-03 16:33:07 -06:00
import { PROCESADORES_POR_EQUIPO } from "@/data/procesadores";
2025-11-03 19:07:01 -06:00
import { useRouter } from "next/navigation";
2025-10-31 20:41:33 -06:00
2025-10-29 13:41:03 -06:00
export default function Editar() {
const searchParams = useSearchParams();
2025-10-31 14:10:00 -06:00
const inventario = searchParams.get("equipoId");
2025-10-29 13:41:03 -06:00
2025-11-03 19:07:01 -06:00
const router = useRouter();
2025-10-29 13:41:03 -06:00
const [formData, setFormData] = useState({
2025-10-31 14:10:00 -06:00
inventario: "",
2025-10-29 13:41:03 -06:00
serie: "",
marca: "",
modelo: "",
tipoEquipo: "",
estado: "",
sistemaOperativo: "",
procesador: "",
tipoUso: "",
observaciones: "",
adscripcion: "",
lugar: "",
responsable: "",
});
2025-10-31 18:28:42 -06:00
interface TipoUso {
id_tipo_uso: number;
tipo_uso: string;
}
interface Estado {
id_estado: number;
estado: string;
}
interface TipoEquipo {
id_tipo_de_equipo: number;
tipo_equipo: string;
}
interface SistemaOperativo {
id_sistema_operativo: number;
sistema_operativo: string;
}
interface Procesador {
id_procesador: number;
procesador: string;
}
interface Marca {
id_marca: number;
2025-11-03 16:33:07 -06:00
marca: string;
2025-10-31 18:28:42 -06:00
}
interface Adscripcion {
id_adscripcion: number;
adscripcion: string;
}
const [tiposUso, setTiposUso] = useState<TipoUso[]>([]);
const [marcas, setMarcas] = useState<Marca[]>([]);
const [estados, setEstados] = useState<Estado[]>([]);
const [adscripciones, setAdscripciones] = useState<Adscripcion[]>([]);
const [tiposEquipo, setTiposEquipo] = useState<TipoEquipo[]>([]);
const [sistemasOperativos, setSistemasOperativos] = useState<
SistemaOperativo[]
>([]);
const [procesadores, setProcesadores] = useState<Procesador[]>([]);
2025-10-29 13:59:44 -06:00
2025-11-03 19:07:01 -06:00
const [suggestions, setSuggestions] = useState({
adscripcion: [] as string[],
});
2025-10-29 13:59:44 -06:00
const api_url = process.env.NEXT_PUBLIC_API_URL;
2025-11-03 16:33:07 -06:00
const mostrarCamposComputadora = formData.tipoEquipo !== "PERIFÉRICO";
2025-10-29 13:59:44 -06:00
2025-10-31 14:10:00 -06:00
// 🔹 Cargar catálogos
2025-10-29 13:41:03 -06:00
useEffect(() => {
2025-10-29 13:59:44 -06:00
const fetchCatalogos = async () => {
const token = Cookies.get("token");
const headers = { Authorization: `Bearer ${token}` };
2025-10-29 13:41:03 -06:00
try {
2025-10-29 13:59:44 -06:00
const [
usosRes,
marcasRes,
estadosRes,
adscripcionesRes,
tiposEquipoRes,
sistemasOperativosRes,
procesadoresRes,
] = await Promise.all([
axios.get(`${api_url}/equipos/usos`, { headers }),
axios.get(`${api_url}/equipos/marcas`, { headers }),
axios.get(`${api_url}/equipos/estados`, { headers }),
axios.get(`${api_url}/equipos/adscripciones`, { headers }),
axios.get(`${api_url}/equipos/tipos-equipo`, { headers }),
axios.get(`${api_url}/equipos/sistemas-operativos`, { headers }),
axios.get(`${api_url}/equipos/procesadores`, { headers }),
]);
setTiposUso(usosRes.data);
setMarcas(marcasRes.data);
setEstados(estadosRes.data);
setAdscripciones(adscripcionesRes.data);
setTiposEquipo(tiposEquipoRes.data);
setSistemasOperativos(sistemasOperativosRes.data);
setProcesadores(procesadoresRes.data);
} catch (error) {
console.error("Error cargando catálogos:", error);
toast.error("No se pudieron cargar los catálogos de datos");
}
};
2025-10-29 13:41:03 -06:00
2025-10-29 13:59:44 -06:00
fetchCatalogos();
}, []);
useEffect(() => {
const fetchEquipo = async () => {
2025-10-31 14:10:00 -06:00
if (!inventario) return;
2025-10-29 14:34:12 -06:00
const token = Cookies.get("token");
const headers = { Authorization: `Bearer ${token}` };
2025-10-29 13:59:44 -06:00
try {
2025-10-31 14:10:00 -06:00
const response = await axios.get(
`${api_url}/equipos/buscar/${inventario}`,
{
headers,
}
);
const equipo = response.data;
setFormData({
inventario: equipo.inventario || "",
serie: equipo.serie || "",
marca: equipo.marca?.marca || "", // <- relación
modelo: equipo.modelo || "",
tipoEquipo: equipo.tipoEquipo?.tipo || "",
estado: equipo.estado?.estado || "",
sistemaOperativo: equipo.sistemaOperativo?.nombre || "",
procesador: equipo.procesador?.nombre || "",
tipoUso: equipo.tipoUso?.tipo || "",
observaciones: equipo.observaciones || "",
adscripcion: equipo.adscripcion?.adscripcion || "",
lugar: equipo.lugar || "",
responsable: equipo.responsable || "", // <- devuelto por searchResponsable
2025-10-29 14:34:12 -06:00
});
2025-10-29 13:41:03 -06:00
} catch (error) {
console.error("Error al obtener el equipo:", error);
2025-10-29 13:59:44 -06:00
toast.error("No se pudo cargar la información del equipo.");
2025-10-29 13:41:03 -06:00
}
};
2025-10-31 14:10:00 -06:00
fetchEquipo();
}, [inventario]);
2025-10-29 13:41:03 -06:00
2025-10-31 14:10:00 -06:00
// 🔹 Guardar cambios
2025-10-29 13:41:03 -06:00
const handleGuardar = async () => {
2025-10-31 14:10:00 -06:00
const token = Cookies.get("token");
const headers = { Authorization: `Bearer ${token}` };
2025-10-29 13:41:03 -06:00
try {
2025-10-31 14:10:00 -06:00
await axios.patch(
`${api_url}/equipos/update/${formData.inventario}`,
formData,
{ headers }
);
2025-10-29 13:59:44 -06:00
toast.success("Equipo actualizado correctamente");
2025-10-29 13:41:03 -06:00
} catch (error) {
console.error("Error al guardar:", error);
2025-10-29 13:59:44 -06:00
toast.error("Hubo un error al guardar el equipo.");
2025-10-29 13:41:03 -06:00
}
};
2025-11-03 19:07:01 -06:00
const handleInputChange = (field: string, value: string) => {
setFormData((prev) => ({ ...prev, [field]: value }));
if (field === "adscripcion") {
if (value.length < 3) {
// Si no hay al menos 3 letras, no mostrar sugerencias
setSuggestions((prev) => ({ ...prev, adscripcion: [] }));
return;
}
// Normaliza para quitar acentos y poner en minúsculas
const normalize = (str: string) =>
str
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.trim();
const searchValue = normalize(value);
// Busca coincidencias
const matches = AREAS.map((a) => a.label)
.filter((label) => normalize(label).includes(searchValue))
.slice(0, 10); // máximo 10 sugerencias
setSuggestions((prev) => ({ ...prev, adscripcion: matches }));
}
};
const handleSelectSuggestion = (field: string, value: string) => {
setFormData((prev) => ({ ...prev, [field]: value }));
setSuggestions((prev) => ({ ...prev, [field]: [] }));
};
2025-10-29 13:41:03 -06:00
const handleCancelar = () => {
2025-11-06 12:55:12 -06:00
router.push("/escaner");
2025-10-29 13:41:03 -06:00
};
return (
<div className="agregarEquipoContainer">
<div className="innerContainer">
<h2 className="information">
2025-10-31 18:57:21 -06:00
<span>{formData.tipoEquipo}</span>
<span>Inventario:{formData.inventario}</span>
<span>Fecha de censo:</span>
2025-10-29 13:41:03 -06:00
</h2>
<form className="equipoForm">
{/* Columna 1 */}
<div className="column">
<div className="formGroup">
<label>Serie</label>
<input
type="text"
value={formData.serie}
2025-10-31 20:41:33 -06:00
placeholder="Ingresa serie"
2025-10-29 13:41:03 -06:00
onChange={(e) =>
setFormData({ ...formData, serie: e.target.value })
}
/>
</div>
2025-10-29 13:59:44 -06:00
2025-10-29 13:41:03 -06:00
<div className="formGroup">
<label>Marca</label>
<select
value={formData.marca}
onChange={(e) =>
setFormData({ ...formData, marca: e.target.value })
}
>
2025-10-29 13:59:44 -06:00
<option value="">Selecciona marca</option>
{marcas.map((m) => (
2025-11-03 16:33:07 -06:00
<option key={m.id_marca} value={m.marca}>
{m.marca}
2025-10-29 13:59:44 -06:00
</option>
))}
2025-10-29 13:41:03 -06:00
</select>
</div>
2025-10-29 13:59:44 -06:00
2025-10-29 13:41:03 -06:00
<div className="formGroup">
<label>Modelo</label>
2025-10-29 13:59:44 -06:00
<input
type="text"
2025-10-29 13:41:03 -06:00
value={formData.modelo}
2025-10-31 20:41:33 -06:00
placeholder="Ingresa modelo"
2025-10-29 13:41:03 -06:00
onChange={(e) =>
setFormData({ ...formData, modelo: e.target.value })
}
2025-10-29 13:59:44 -06:00
/>
</div>
<div className="formGroup">
<label>Tipo de equipo</label>
<select
value={formData.tipoEquipo}
onChange={(e) =>
setFormData({ ...formData, tipoEquipo: e.target.value })
}
2025-10-29 13:41:03 -06:00
>
2025-10-31 14:10:00 -06:00
<option value="">Selecciona tipo</option>
2025-10-29 13:59:44 -06:00
{tiposEquipo.map((t) => (
2025-10-31 18:28:42 -06:00
<option key={t.id_tipo_de_equipo} value={t.tipo_equipo}>
{t.tipo_equipo}
2025-10-29 13:59:44 -06:00
</option>
))}
2025-10-29 13:41:03 -06:00
</select>
</div>
2025-10-29 13:59:44 -06:00
2025-10-29 13:41:03 -06:00
<div className="formGroup">
<label>Estado</label>
<select
value={formData.estado}
onChange={(e) =>
setFormData({ ...formData, estado: e.target.value })
}
>
<option value="">Selecciona estado</option>
2025-10-29 13:59:44 -06:00
{estados.map((e) => (
2025-10-31 18:28:42 -06:00
<option key={e.id_estado} value={e.estado}>
{e.estado}
2025-10-29 13:59:44 -06:00
</option>
))}
2025-10-29 13:41:03 -06:00
</select>
</div>
2025-10-29 13:59:44 -06:00
</div>
2025-10-29 13:41:03 -06:00
2025-10-29 13:59:44 -06:00
{/* Columna 2 */}
<div className="column">
2025-10-29 13:41:03 -06:00
<div className="formGroup">
2025-10-29 13:59:44 -06:00
<label>Tipo de uso</label>
2025-10-29 13:41:03 -06:00
<select
value={formData.tipoUso}
onChange={(e) =>
setFormData({ ...formData, tipoUso: e.target.value })
}
>
2025-10-31 14:10:00 -06:00
<option value="">Selecciona uso</option>
2025-10-29 13:59:44 -06:00
{tiposUso.map((t) => (
2025-10-31 18:28:42 -06:00
<option key={t.id_tipo_uso} value={t.tipo_uso}>
{t.tipo_uso}
2025-10-29 13:59:44 -06:00
</option>
))}
2025-10-29 13:41:03 -06:00
</select>
</div>
{mostrarCamposComputadora && (
<>
<div className="formGroup">
<label>Procesador</label>
<select
value={formData.procesador}
onChange={(e) =>
setFormData({ ...formData, procesador: e.target.value })
}
>
<option value="">Selecciona procesador</option>
2025-11-03 16:33:07 -06:00
{PROCESADORES_POR_EQUIPO[formData.tipoEquipo]?.map((p) => (
<option key={p} value={p}>
{p}
2025-10-29 13:59:44 -06:00
</option>
))}
2025-10-29 13:41:03 -06:00
</select>
</div>
<div className="formGroup">
<label>Sistema operativo</label>
<select
value={formData.sistemaOperativo}
onChange={(e) =>
setFormData({
...formData,
sistemaOperativo: e.target.value,
})
}
>
<option value="">Selecciona sistema operativo</option>
2025-11-03 16:33:07 -06:00
{SO_POR_EQUIPO[formData.tipoEquipo]?.map((so) => (
<option key={so} value={so}>
{so}
2025-10-29 13:59:44 -06:00
</option>
))}
2025-10-29 13:41:03 -06:00
</select>
</div>
</>
)}
2025-11-03 16:33:07 -06:00
{!mostrarCamposComputadora && (
<div className="formGroup">
<label>Tipos de Perifericos</label>
<select>
<option value="">Selecciona periferico</option>
</select>
</div>
)}
2025-11-03 19:07:01 -06:00
<div className="formGroup" style={{ position: "relative" }}>
2025-10-29 13:41:03 -06:00
<label>Adscripción</label>
2025-11-03 19:07:01 -06:00
<input
required
type="text"
placeholder="Ingresa adscripción"
2025-10-29 13:41:03 -06:00
value={formData.adscripcion}
onChange={(e) =>
2025-11-03 19:07:01 -06:00
handleInputChange("adscripcion", e.target.value)
2025-10-29 13:41:03 -06:00
}
2025-11-03 19:07:01 -06:00
/>
{suggestions.adscripcion.length > 0 && (
<ul className="suggestions">
{suggestions.adscripcion.map((s) => (
<li
key={s}
onClick={() => handleSelectSuggestion("adscripcion", s)}
>
{s}
</li>
))}
</ul>
)}
2025-10-29 13:41:03 -06:00
</div>
<div className="formGroup">
<label>Responsable</label>
2025-10-31 20:26:32 -06:00
<input
type="text"
value={formData.responsable}
disabled
placeholder="Selecciona una Adscripcion"
/>
2025-10-29 13:41:03 -06:00
</div>
</div>
{/* Columna 3 */}
<div className="column">
<div className="formGroup">
<label>Lugar</label>
<textarea
value={formData.lugar}
onChange={(e) =>
setFormData({ ...formData, lugar: e.target.value })
}
rows={5}
className="textAreaLarge"
/>
</div>
<div className="formGroup">
<label>Observaciones</label>
<textarea
value={formData.observaciones}
onChange={(e) =>
setFormData({ ...formData, observaciones: e.target.value })
}
rows={5}
className="textAreaLarge"
/>
</div>
<div className="formActions">
<button
type="button"
className="btnGuardar"
onClick={handleGuardar}
>
Guardar
</button>
<button
type="button"
className="btnCancelar"
onClick={handleCancelar}
>
Cancelar
</button>
</div>
</div>
</form>
</div>
</div>
);
}