592 lines
17 KiB
TypeScript
592 lines
17 KiB
TypeScript
"use client";
|
|
|
|
import { useState, useEffect } from "react";
|
|
import { useSearchParams } from "next/navigation";
|
|
import axios from "axios";
|
|
import Cookies from "js-cookie";
|
|
import toast from "react-hot-toast";
|
|
|
|
import { SO_POR_EQUIPO } from "@/data/so_por_equipo";
|
|
import { PROCESADORES_POR_EQUIPO } from "@/data/procesadores";
|
|
import { useRouter } from "next/navigation";
|
|
import "../app/styles/layout/agregarEquipo.scss";
|
|
|
|
export default function Page() {
|
|
const searchParams = useSearchParams();
|
|
const inventario = searchParams.get("equipoId");
|
|
|
|
const router = useRouter();
|
|
|
|
const [formData, setFormData] = useState({
|
|
inventario: "",
|
|
serie: "",
|
|
lugar: "",
|
|
fechaFactura: new Date(),
|
|
antiguedad: "MENORES DE 2",
|
|
modelo: "",
|
|
id_estado: 0,
|
|
id_adscripcion: 0,
|
|
id_tipo_equipo: 0,
|
|
id_sistema_operativo: 0,
|
|
id_procesador: 0,
|
|
id_uso: 0,
|
|
id_marca: 0,
|
|
id_periferico: 0,
|
|
isImpresora: false,
|
|
});
|
|
|
|
useEffect(() => {
|
|
if (inventario) {
|
|
setFormData((prev) => ({ ...prev, inventario }));
|
|
}
|
|
}, [inventario]);
|
|
|
|
interface TipoUso {
|
|
id_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;
|
|
marca: string;
|
|
}
|
|
|
|
interface Adscripcion {
|
|
id_adscripcion: number;
|
|
adscripcion: string;
|
|
}
|
|
|
|
interface Perifericos {
|
|
id_periferico: number;
|
|
periferico: string;
|
|
}
|
|
|
|
// Estados
|
|
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[]>([]);
|
|
const [perifericos, setPerifericos] = useState<Perifericos[]>([]);
|
|
const [adscripcionLabel, setAdscripcionLabel] = useState("");
|
|
|
|
const [suggestions, setSuggestions] = useState({
|
|
adscripcion: [] as string[],
|
|
});
|
|
|
|
const mostrarCamposComputadora = Number(formData.id_tipo_equipo) !== 9;
|
|
const tableta =
|
|
Number(formData.id_tipo_equipo) !== 7 &&
|
|
Number(formData.id_tipo_equipo) !== 8;
|
|
const api_url = process.env.NEXT_PUBLIC_API_URL;
|
|
|
|
useEffect(() => {
|
|
const fetchData = async () => {
|
|
const token = Cookies.get("token");
|
|
const headers = { Authorization: `Bearer ${token}` };
|
|
|
|
try {
|
|
const [
|
|
usosRes,
|
|
marcasRes,
|
|
estadosRes,
|
|
adscripcionesRes,
|
|
tiposEquipoRes,
|
|
sistemasOperativosRes,
|
|
] = 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 }),
|
|
]);
|
|
|
|
setTiposUso(usosRes.data);
|
|
setMarcas(marcasRes.data);
|
|
setEstados(estadosRes.data);
|
|
setAdscripciones(adscripcionesRes.data);
|
|
setTiposEquipo(tiposEquipoRes.data);
|
|
setSistemasOperativos(sistemasOperativosRes.data);
|
|
} catch (err) {
|
|
if (axios.isAxiosError(err)) {
|
|
if (err.response) {
|
|
toast.error(
|
|
err.response.data?.message || "No se pudo conectar con el API"
|
|
);
|
|
} else if (err.request) {
|
|
toast.error("No se pudo conectar con el servidor");
|
|
} else {
|
|
toast.error("Ocurrió un error inesperado");
|
|
}
|
|
} else {
|
|
toast.error("Ocurrió un error inesperado");
|
|
}
|
|
}
|
|
};
|
|
|
|
fetchData();
|
|
}, [api_url]);
|
|
|
|
useEffect(() => {
|
|
const fetchProcesador = async () => {
|
|
const token = Cookies.get("token");
|
|
const headers = { Authorization: `Bearer ${token}` };
|
|
|
|
const response = await axios.get(
|
|
`${api_url}/equipos/procesador-tipo-equipos`,
|
|
{
|
|
headers,
|
|
}
|
|
);
|
|
|
|
setProcesadores(response.data);
|
|
};
|
|
fetchProcesador();
|
|
}, [tiposEquipo]);
|
|
|
|
useEffect(() => {
|
|
const fetchPerifericos = async () => {
|
|
if (Number(formData.id_tipo_equipo) != 9) return;
|
|
|
|
const token = Cookies.get("token");
|
|
const headers = { Authorization: `Bearer ${token}` };
|
|
|
|
try {
|
|
const response = await axios.get(`${api_url}/equipos/perifericos`, {
|
|
headers,
|
|
});
|
|
setPerifericos(response.data);
|
|
} catch (err) {
|
|
console.error(err);
|
|
toast.error("No se pudieron cargar los periféricos");
|
|
}
|
|
};
|
|
|
|
fetchPerifericos();
|
|
}, [formData.id_tipo_equipo]);
|
|
|
|
const handleInputChange = (
|
|
field: string,
|
|
value: string | number | boolean
|
|
) => {
|
|
if (field === "adscripcionLabel") {
|
|
const textValue = value as string;
|
|
setAdscripcionLabel(textValue);
|
|
|
|
const normalize = (str: string) =>
|
|
str
|
|
.normalize("NFD")
|
|
.replace(/[\u0300-\u036f]/g, "")
|
|
.toLowerCase();
|
|
|
|
const matches = adscripciones
|
|
.filter((a) => normalize(a.adscripcion).includes(normalize(textValue)))
|
|
.map((a) => a.adscripcion);
|
|
|
|
setSuggestions((prev) => ({
|
|
...prev,
|
|
adscripcion: matches.slice(0, 5),
|
|
}));
|
|
return;
|
|
}
|
|
|
|
setFormData((prev) => {
|
|
const newValue =
|
|
field.startsWith("id_") && value !== "" ? Number(value) : value;
|
|
|
|
if (field === "id_tipo_equipo") {
|
|
const idTipoEquipo = Number(value);
|
|
const tipoSeleccionado = tiposEquipo.find(
|
|
(t) => t.id_tipo_de_equipo === idTipoEquipo
|
|
);
|
|
const esPeriferico = tipoSeleccionado?.tipo_equipo === "PERIFÉRICO";
|
|
|
|
return {
|
|
...prev,
|
|
id_tipo_equipo: idTipoEquipo,
|
|
isImpresora: esPeriferico,
|
|
};
|
|
}
|
|
|
|
return { ...prev, [field]: newValue };
|
|
});
|
|
};
|
|
|
|
const handleGuardar = async () => {
|
|
if (!formData.inventario) {
|
|
toast.error("Inventario no encontrado");
|
|
return;
|
|
}
|
|
|
|
if (!formData.id_marca) {
|
|
toast.error("marca no encontrada");
|
|
return;
|
|
}
|
|
|
|
if (!formData.id_tipo_equipo) {
|
|
toast.error("Tipo de equipo no encontrado");
|
|
return;
|
|
}
|
|
|
|
if (!formData.id_estado) {
|
|
toast.error("estado no encontrado");
|
|
return;
|
|
}
|
|
|
|
if (!formData.id_uso) {
|
|
toast.error("tipo de uso no encontrado");
|
|
return;
|
|
}
|
|
|
|
if (!formData.id_adscripcion) {
|
|
toast.error("adscripcion no encontrado");
|
|
return;
|
|
}
|
|
|
|
if (formData.id_tipo_equipo == 9) {
|
|
if (!formData.id_periferico) {
|
|
toast.error("Periferico no encontrado");
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (
|
|
formData.id_tipo_equipo != 8 &&
|
|
formData.id_tipo_equipo != 7 &&
|
|
formData.id_tipo_equipo != 9
|
|
) {
|
|
if (!formData.id_sistema_operativo) {
|
|
toast.error("Sistema operativo no encontrado ");
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (formData.id_tipo_equipo != 9) {
|
|
if (!formData.id_procesador) {
|
|
toast.error("Procesador no encontrado");
|
|
return;
|
|
}
|
|
}
|
|
|
|
try {
|
|
const token = Cookies.get("token");
|
|
const headers = { Authorization: `Bearer ${token}` };
|
|
|
|
const dataToSend = {
|
|
...formData,
|
|
fechaFactura: new Date(formData.fechaFactura)
|
|
.toISOString()
|
|
.split("T")[0], // "YYYY-MM-DD"
|
|
antiguedad: formData.antiguedad || "0 años",
|
|
};
|
|
|
|
await axios.post(`${api_url}/equipos/crear`, dataToSend, { headers });
|
|
toast.success("Equipo guardado correctamente");
|
|
} catch (err) {
|
|
toast.error("Error al guardar el equipo");
|
|
}
|
|
};
|
|
|
|
const handleCancelar = () => {
|
|
router.push("/escaner");
|
|
};
|
|
|
|
return (
|
|
<div className="agregarEquipoContainer">
|
|
<div className="innerContainer">
|
|
<h2 className="information">Agregar Nuevo Equipo</h2>
|
|
<form className="equipoForm">
|
|
{/* Columna Izquierda */}
|
|
<div className="column">
|
|
<div className="formGroup">
|
|
<label>Numero de Inventario</label>
|
|
<input
|
|
required
|
|
type="text"
|
|
placeholder="Ingresa Inventario"
|
|
value={formData.inventario}
|
|
onChange={(e) =>
|
|
handleInputChange("inventario", e.target.value)
|
|
}
|
|
/>
|
|
</div>
|
|
<div className="formGroup">
|
|
<label>Serie</label>
|
|
<input
|
|
required
|
|
type="text"
|
|
placeholder="Ingresa serie"
|
|
value={formData.serie}
|
|
onChange={(e) => handleInputChange("serie", e.target.value)}
|
|
/>
|
|
</div>
|
|
|
|
<div className="formGroup">
|
|
<label>Marca</label>
|
|
<select
|
|
required
|
|
value={formData.id_marca}
|
|
onChange={(e) => handleInputChange("id_marca", e.target.value)}
|
|
>
|
|
<option value="">Selecciona una marca</option>
|
|
{marcas.map((m) => (
|
|
<option key={m.id_marca} value={m.id_marca}>
|
|
{m.marca}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
|
|
<div className="formGroup">
|
|
<label>Modelo</label>
|
|
<input
|
|
type="text"
|
|
placeholder="Ingresa modelo"
|
|
value={formData.modelo}
|
|
onChange={(e) => handleInputChange("modelo", e.target.value)}
|
|
/>
|
|
</div>
|
|
|
|
<div className="formGroup">
|
|
<label>Tipo de equipo</label>
|
|
<select
|
|
required
|
|
value={formData.id_tipo_equipo}
|
|
onChange={(e) =>
|
|
handleInputChange("id_tipo_equipo", e.target.value)
|
|
}
|
|
>
|
|
<option value="">Selecciona tipo de equipo</option>
|
|
{tiposEquipo.map((t) => (
|
|
<option key={t.id_tipo_de_equipo} value={t.id_tipo_de_equipo}>
|
|
{t.tipo_equipo}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="column">
|
|
<div className="formGroup">
|
|
<label>Estado</label>
|
|
<select
|
|
required
|
|
value={formData.id_estado}
|
|
onChange={(e) => handleInputChange("id_estado", e.target.value)}
|
|
>
|
|
<option value="">Selecciona estado</option>
|
|
{estados.map((e) => (
|
|
<option key={e.id_estado} value={e.id_estado}>
|
|
{e.estado}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
|
|
<div className="formGroup">
|
|
<label>Tipo de uso</label>
|
|
<select
|
|
required
|
|
value={formData.id_uso}
|
|
onChange={(e) => handleInputChange("id_uso", e.target.value)}
|
|
>
|
|
<option value="">Selecciona tipo de uso</option>
|
|
{tiposUso.map((t) => (
|
|
<option key={t.id_uso} value={t.id_uso}>
|
|
{t.tipo_uso}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
|
|
{mostrarCamposComputadora && (
|
|
<>
|
|
<div className="formGroup">
|
|
<label>Procesador</label>
|
|
<select
|
|
disabled={formData.id_tipo_equipo == 0}
|
|
value={formData.id_procesador}
|
|
onChange={(e) =>
|
|
handleInputChange("id_procesador", e.target.value)
|
|
}
|
|
>
|
|
<option value="">
|
|
{formData.id_tipo_equipo
|
|
? "Selecciona procesador"
|
|
: "Selecciona primero el tipo de equipo"}
|
|
</option>
|
|
{PROCESADORES_POR_EQUIPO[formData.id_tipo_equipo]?.map(
|
|
(p) => (
|
|
<option key={p.id_procesador} value={p.id_procesador}>
|
|
{p.procesador}
|
|
</option>
|
|
)
|
|
)}
|
|
</select>
|
|
</div>
|
|
{tableta && (
|
|
<div className="formGroup">
|
|
<label>Sistema operativo</label>
|
|
<select
|
|
disabled={formData.id_tipo_equipo == 0}
|
|
value={formData.id_sistema_operativo}
|
|
onChange={(e) =>
|
|
handleInputChange(
|
|
"id_sistema_operativo",
|
|
e.target.value
|
|
)
|
|
}
|
|
>
|
|
<option value="">
|
|
{formData.id_tipo_equipo
|
|
? "Selecciona sistema operativo"
|
|
: "Selecciona primero el tipo de equipo"}
|
|
</option>
|
|
{SO_POR_EQUIPO[formData.id_tipo_equipo]?.map((so) => (
|
|
<option
|
|
key={so.id_sistema_operativo}
|
|
value={so.id_sistema_operativo}
|
|
>
|
|
{so.sistema_operativo}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
)}
|
|
</>
|
|
)}
|
|
|
|
{!mostrarCamposComputadora && (
|
|
<div className="formGroup">
|
|
<label>Tipos de Periféricos</label>
|
|
<select
|
|
value={formData.id_periferico}
|
|
onChange={(e) =>
|
|
handleInputChange("id_periferico", e.target.value)
|
|
}
|
|
>
|
|
<option value="">Selecciona periférico</option>
|
|
{perifericos.map((p) => (
|
|
<option key={p.id_periferico} value={p.id_periferico}>
|
|
{p.periferico}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
)}
|
|
|
|
<div className="formGroup" style={{ position: "relative" }}>
|
|
<label>Adscripción</label>
|
|
<input
|
|
required
|
|
type="text"
|
|
placeholder="Ingresa adscripción"
|
|
value={adscripcionLabel}
|
|
onChange={(e) =>
|
|
handleInputChange("adscripcionLabel", e.target.value)
|
|
}
|
|
/>
|
|
{suggestions.adscripcion.length > 0 && (
|
|
<ul className="suggestions">
|
|
{suggestions.adscripcion.map((s) => (
|
|
<li
|
|
key={s}
|
|
onClick={() => {
|
|
const selected = adscripciones.find(
|
|
(a) => a.adscripcion === s
|
|
);
|
|
if (selected) {
|
|
setFormData((prev) => ({
|
|
...prev,
|
|
id_adscripcion: selected.id_adscripcion,
|
|
}));
|
|
setAdscripcionLabel(selected.adscripcion);
|
|
setSuggestions((prev) => ({
|
|
...prev,
|
|
adscripcion: [],
|
|
}));
|
|
}
|
|
}}
|
|
>
|
|
{s}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="column">
|
|
<div className="formGroup">
|
|
<label>Lugar</label>
|
|
<textarea
|
|
placeholder="Ingresa lugar"
|
|
value={formData.lugar}
|
|
onChange={(e) => handleInputChange("lugar", e.target.value)}
|
|
rows={5}
|
|
className="textAreaLarge"
|
|
/>
|
|
</div>
|
|
|
|
{/* <div className="formGroup">
|
|
<label>Observaciones</label>
|
|
<textarea
|
|
placeholder="Ingresa observaciones"
|
|
value={formData.observaciones}
|
|
onChange={(e) =>
|
|
handleInputChange("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>
|
|
);
|
|
}
|
|
//IO
|