110 lines
3.0 KiB
TypeScript
110 lines
3.0 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useState } from "react";
|
|
import { envConfig } from "@/app/lib/config";
|
|
import { Alumno, AlumnoSancion, Sancion } from "@/app/types/sanction";
|
|
import TableSanction from "./TableSanction";
|
|
import axios from "axios";
|
|
import toast from "react-hot-toast";
|
|
|
|
if (!envConfig.apiUrl) {
|
|
console.error("API URL is not defined in envConfig");
|
|
}
|
|
|
|
export default function ApplySanction({ idCuenta }: { idCuenta: number }) {
|
|
const [sanciones, setSanciones] = useState<Sancion[]>([]);
|
|
const [alumno, setAlumno] = useState<Alumno >();
|
|
const [alumnoSanciones, setAlumnoSanciones] = useState<AlumnoSancion[]>([]);
|
|
const [selectedSancion, setSelectedSancion] = useState("");
|
|
const [loading, setLoading] = useState(false);
|
|
const [loadingTable, setLoadingTable] = useState(false);
|
|
|
|
const fetchAlumnoSanciones = async () => {
|
|
try {
|
|
const res = await axios.get(
|
|
`${envConfig.apiUrl}/alumno-sancion/${idCuenta}`
|
|
);
|
|
|
|
setAlumno(res.data.student ?? null);
|
|
setAlumnoSanciones(res.data.alusancion ?? []);
|
|
} catch {
|
|
}finally{
|
|
setLoadingTable(true)
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (!idCuenta) return;
|
|
|
|
fetchAlumnoSanciones();
|
|
|
|
axios
|
|
.get(`${envConfig.apiUrl}/sancion`)
|
|
.then((res) => setSanciones(res.data))
|
|
.catch(() =>
|
|
toast.error("Error al obtener el catálogo de sanciones")
|
|
);
|
|
}, [idCuenta]);
|
|
|
|
const handleButton = async (e: React.MouseEvent<HTMLButtonElement>) => {
|
|
e.preventDefault();
|
|
|
|
if (!selectedSancion) {
|
|
toast.error("Selecciona una sanción");
|
|
return;
|
|
}
|
|
|
|
try {
|
|
setLoading(true);
|
|
|
|
await axios.post(`${envConfig.apiUrl}/alumno-sancion/`, {
|
|
id_sancion: Number(selectedSancion),
|
|
id_cuenta: idCuenta,
|
|
});
|
|
|
|
await fetchAlumnoSanciones();
|
|
setSelectedSancion("");
|
|
toast.success("Sanción aplicada correctamente");
|
|
} catch {
|
|
toast.error("Error al aplicar la sanción");
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<>
|
|
<TableSanction alumnoSanciones={alumnoSanciones} alumno={alumno} />
|
|
|
|
{loadingTable && alumnoSanciones.length === 0 && (
|
|
<>
|
|
<form className="containerForm">
|
|
<div className="groupInput">
|
|
<select
|
|
value={selectedSancion}
|
|
onChange={(e) => setSelectedSancion(e.target.value)}
|
|
>
|
|
<option value="">-- Selecciona una sanción --</option>
|
|
{sanciones.map((sancion) => (
|
|
<option key={sancion.id_sancion} value={sancion.id_sancion}>
|
|
{sancion.sancion} ({sancion.duracion} semana/s)
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
</form>
|
|
|
|
<button
|
|
className="button buttonSearch"
|
|
style={{ margin: "1rem 0" }}
|
|
onClick={handleButton}
|
|
disabled={loading}
|
|
>
|
|
{loading ? "Aplicando..." : "Aplicar sanción"}
|
|
</button>
|
|
</>
|
|
)}
|
|
</>
|
|
);
|
|
}
|