This commit is contained in:
2023-08-08 17:04:21 +00:00
parent 31ecda89b2
commit ec382e989a
147 changed files with 18206 additions and 18063 deletions

View File

@@ -1,160 +1,189 @@
import { createApp, reactive } from 'https://unpkg.com/petite-vue?module';
const store = reactive({
loading: false,
current: {
comentario: '',
clase_vista: null,
empty: '',
},
facultades: {
data: [],
async fetch() {
this.data = [];
const res = await fetch('action/action_facultad.php');
this.data = await res.json();
},
},
filters: {
facultad_id: null,
fecha: null,
fecha_inicio: null,
fecha_fin: null,
profesor: null,
estados: [],
switchFecha: false,
switchFechas() {
$(function () {
store.filters.fecha_inicio = store.filters.fecha_fin = store.filters.fecha = null;
$("#fecha, #fecha_inicio, #fecha_fin").datepicker({
minDate: -3,
maxDate: new Date(),
dateFormat: "yy-mm-dd",
showAnim: "slide",
});
const fecha = $("#fecha"), inicio = $("#fecha_inicio"), fin = $("#fecha_fin");
inicio.on("change", function () {
store.filters.fecha_inicio = inicio.val();
fin.datepicker("option", "minDate", inicio.val());
});
fin.on("change", function () {
store.filters.fecha_fin = fin.val();
inicio.datepicker("option", "maxDate", fin.val());
});
fecha.on("change", function () {
store.filters.fecha = fecha.val();
});
});
}
},
estados: {
data: [],
async fetch() {
this.data = [];
const res = await fetch('action/action_estado_supervisor.php');
this.data = await res.json();
},
getEstado(id) {
return this.data.find((estado) => estado.estado_supervisor_id === id);
},
printEstados() {
if (store.filters.estados.length > 0)
document.querySelector('#estados').innerHTML = store.filters.estados.map((estado) => `<span class="mx-2 badge badge-${store.estados.getEstado(estado).estado_color}">
<i class="${store.estados.getEstado(estado).estado_icon}"></i> ${store.estados.getEstado(estado).nombre}
</span>`).join('');
else
document.querySelector('#estados').innerHTML = `Todos los registros`;
}
},
toggle(arr, element) {
const newArray = arr.includes(element) ? arr.filter((item) => item !== element) : [...arr, element];
// if all are selected, then unselect all
if (newArray.length === this.estados.data.length)
return [];
return newArray;
},
});
createApp({
store,
get clase_vista() {
return store.current.clase_vista;
},
registros: {
data: [],
async fetch() {
this.loading = true;
this.data = [];
const res = await fetch('action/action_auditoria.php');
this.data = await res.json();
this.loading = false;
},
invertir() {
this.data = this.data.reverse();
},
mostrarComentario(registro_id) {
const registro = this.data.find((registro) => registro.registro_id === registro_id);
store.current.comentario = registro.comentario;
$('#ver-comentario').modal('show');
},
get relevant() {
/*
facultad_id: null,
fecha: null,
fecha_inicio: null,
fecha_fin: null,
profesor: null,
asistencia: null,
estado_id: null,
if one of the filters is null, then it is not relevant
*/
const filters = Object.keys(store.filters).filter((filtro) => store.filters[filtro] || store.filters[filtro]?.length > 0);
return this.data.filter((registro) => {
return filters.every((filtro) => {
switch (filtro) {
case 'fecha':
return registro.registro_fecha_ideal === store.filters[filtro];
case 'fecha_inicio':
return registro.registro_fecha_ideal >= store.filters[filtro];
case 'fecha_fin':
return registro.registro_fecha_ideal <= store.filters[filtro];
case 'profesor':
const textoFiltro = store.filters[filtro].toLowerCase();
if (/^\([^)]+\)\s[\s\S]+$/.test(textoFiltro)) {
const clave = registro.profesor_clave.toLowerCase();
const filtroClave = textoFiltro.match(/\((.*?)\)/)?.[1];
console.log(clave, filtroClave);
return clave.includes(filtroClave);
}
else {
const nombre = registro.profesor_nombre.toLowerCase();
return nombre.includes(textoFiltro);
}
case 'facultad_id':
return registro.facultad_id === store.filters[filtro];
case 'estados':
if (store.filters[filtro].length === 0)
return true;
return store.filters[filtro].includes(registro.estado_supervisor_id);
default:
return true;
}
});
});
},
},
get profesores() {
return this.registros.data.map((registro) => ({
profesor_id: registro.profesor_id,
profesor_nombre: registro.profesor_nombre,
profesor_correo: registro.profesor_correo,
profesor_clave: registro.profesor_clave,
profesor_grado: registro.profesor_grado,
})).sort((a, b) => a.profesor_nombre.localeCompare(b.profesor_nombre));
},
async mounted() {
await this.registros.fetch();
await store.facultades.fetch();
await store.estados.fetch();
store.filters.switchFechas();
}
}).mount('#app');
import { createApp, reactive } from 'https://unpkg.com/petite-vue?module';
const store = reactive({
loading: false,
current: {
comentario: '',
clase_vista: null,
empty: '',
},
facultades: {
data: [],
async fetch() {
this.data = [];
const res = await fetch('action/action_facultad.php');
this.data = await res.json();
},
},
filters: {
facultad_id: null,
fecha: null,
fecha_inicio: null,
fecha_fin: null,
profesor: null,
bloque_horario: null,
estados: [],
switchFecha: false,
switchFechas() {
$(function () {
store.filters.fecha_inicio = store.filters.fecha_fin = store.filters.fecha = null;
$("#fecha, #fecha_inicio, #fecha_fin").datepicker({
minDate: -3,
maxDate: new Date(),
dateFormat: "yy-mm-dd",
showAnim: "slide",
});
const fecha = $("#fecha"), inicio = $("#fecha_inicio"), fin = $("#fecha_fin");
inicio.on("change", function () {
store.filters.fecha_inicio = inicio.val();
fin.datepicker("option", "minDate", inicio.val());
});
fin.on("change", function () {
store.filters.fecha_fin = fin.val();
inicio.datepicker("option", "maxDate", fin.val());
});
fecha.on("change", function () {
store.filters.fecha = fecha.val();
});
});
}
},
estados: {
data: [],
async fetch() {
this.data = [];
const res = await fetch('action/action_estado_supervisor.php');
this.data = await res.json();
},
getEstado(id) {
return this.data.find((estado) => estado.estado_supervisor_id === id);
},
printEstados() {
if (store.filters.estados.length > 0)
document.querySelector('#estados').innerHTML = store.filters.estados.map((estado) => `<span class="mx-2 badge badge-${store.estados.getEstado(estado).estado_color}">
<i class="${store.estados.getEstado(estado).estado_icon}"></i> ${store.estados.getEstado(estado).nombre}
</span>`).join('');
else
document.querySelector('#estados').innerHTML = `Todos los registros`;
}
},
bloques_horario: {
data: [],
async fetch() {
this.data = [];
const res = await fetch('action/action_grupo_horario.php');
this.data = await res.json();
if (this.data.every((bloque) => !bloque.selected))
this.data[0].selected = true;
},
},
toggle(arr, element) {
const newArray = arr.includes(element) ? arr.filter((item) => item !== element) : [...arr, element];
// if all are selected, then unselect all
if (newArray.length === this.estados.data.length)
return [];
return newArray;
},
});
createApp({
store,
get clase_vista() {
return store.current.clase_vista;
},
registros: {
data: [],
async fetch() {
this.loading = true;
this.data = [];
const res = await fetch('action/action_auditoria.php');
this.data = await res.json();
this.loading = false;
},
invertir() {
this.data = this.data.reverse();
},
mostrarComentario(registro_id) {
const registro = this.data.find((registro) => registro.registro_id === registro_id);
store.current.comentario = registro.comentario;
$('#ver-comentario').modal('show');
},
get relevant() {
/*
facultad_id: null,
fecha: null,
fecha_inicio: null,
fecha_fin: null,
profesor: null,
asistencia: null,
estado_id: null,
if one of the filters is null, then it is not relevant
*/
const filters = Object.keys(store.filters).filter((filtro) => store.filters[filtro] || store.filters[filtro]?.length > 0);
return this.data.filter((registro) => {
return filters.every((filtro) => {
switch (filtro) {
case 'fecha':
return registro.registro_fecha_ideal === store.filters[filtro];
case 'fecha_inicio':
return registro.registro_fecha_ideal >= store.filters[filtro];
case 'fecha_fin':
return registro.registro_fecha_ideal <= store.filters[filtro];
case 'profesor':
const textoFiltro = store.filters[filtro].toLowerCase();
if (/^\([^)]+\)\s[\s\S]+$/.test(textoFiltro)) {
const clave = registro.profesor_clave.toLowerCase();
const filtroClave = textoFiltro.match(/\((.*?)\)/)?.[1];
console.log(clave, filtroClave);
return clave.includes(filtroClave);
}
else {
const nombre = registro.profesor_nombre.toLowerCase();
return nombre.includes(textoFiltro);
}
case 'facultad_id':
return registro.facultad_id === store.filters[filtro];
case 'estados':
if (store.filters[filtro].length === 0)
return true;
return store.filters[filtro].includes(registro.estado_supervisor_id);
case 'bloque_horario':
const bloque = store.bloques_horario.data.find((bloque) => bloque.id === store.filters[filtro]);
return registro.horario_hora <= bloque.hora_fin && registro.horario_fin >= bloque.hora_inicio;
default:
return true;
}
});
});
},
async descargar() {
if (this.relevant.length === 0)
return;
const res = await fetch('export/supervisor_excel.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(this.relevant)
});
const blob = await res.blob();
window.saveAs(blob, `auditoria_${new Date().toISOString().slice(0, 10)}.xlsx`);
}
},
get profesores() {
return this.registros.data.map((registro) => ({
profesor_id: registro.profesor_id,
profesor_nombre: registro.profesor_nombre,
profesor_correo: registro.profesor_correo,
profesor_clave: registro.profesor_clave,
profesor_grado: registro.profesor_grado,
})).sort((a, b) => a.profesor_nombre.localeCompare(b.profesor_nombre));
},
async mounted() {
await this.registros.fetch();
await store.facultades.fetch();
await store.estados.fetch();
await store.bloques_horario.fetch();
store.filters.bloque_horario = store.bloques_horario.data.find((bloque) => bloque.selected)?.id;
store.filters.switchFechas();
}
}).mount('#app');

View File

@@ -1,41 +1,41 @@
function barra(profesor, retardos) {
profesor.faltas = profesor.total - profesor.asistencias - profesor.retardos - profesor.justificaciones;
if (profesor.total != 0)
var porcentajes = {
"asistencias": profesor.asistencias / profesor.total * 100,
"retardos": profesor.retardos / profesor.total * 100,
"justificaciones": profesor.justificaciones / profesor.total * 100,
"faltas": 100 * profesor.faltas / profesor.total
}
else
var porcentajes = {
"asistencias": 0,
"retardos": 0,
"justificaciones": 0,
"faltas": 0
}
var html = `
<section id="profesor-${profesor.id}">
<div class="row">
<div class="col-12">
<div class="progress">
<div class="progress-bar bg-success" role="progressbar" style="width: ${porcentajes.asistencias}%" aria-valuenow="${porcentajes.asistencias}" aria-valuemin="0" aria-valuemax="100"></div>
<!-- Show retardos only if it's set to true -->
${retardos ? `<div class="progress-bar bg-warning" role="progressbar" style="width: ${porcentajes.retardos}%" aria-valuenow="${porcentajes.retardos}" aria-valuemin="0" aria-valuemax="100"></div>` : ``}
<div class="progress-bar bg-azul" role="progressbar" style="width: ${porcentajes.justificaciones}%" aria-valuenow="${porcentajes.justificaciones}" aria-valuemin="0" aria-valuemax="100"></div>
<div class="progress-bar bg-info" role="progressbar" style="width: ${porcentajes.faltas}%" aria-valuenow="${porcentajes.faltas}" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</div>
</div>
<!-- Span Asistencias: # Retardos: # Faltas: # -->
<div class="row justify-content-center">
<span class="mx-3 mt-1">Asistencias: ${profesor.asistencias}</span>
${retardos ? `<span class="mx-3 mt-1">Retardos: ${profesor.retardos}</span>` : `` }
<span class="mx-3 mt-1">Justificaciones: ${profesor.justificaciones}</span>
<span class="mx-3 mt-1">Faltas: ${profesor.faltas}</span>
</div>
</div>
`;
return html;
function barra(profesor, retardos) {
profesor.faltas = profesor.total - profesor.asistencias - profesor.retardos - profesor.justificaciones;
if (profesor.total != 0)
var porcentajes = {
"asistencias": profesor.asistencias / profesor.total * 100,
"retardos": profesor.retardos / profesor.total * 100,
"justificaciones": profesor.justificaciones / profesor.total * 100,
"faltas": 100 * profesor.faltas / profesor.total
}
else
var porcentajes = {
"asistencias": 0,
"retardos": 0,
"justificaciones": 0,
"faltas": 0
}
var html = `
<section id="profesor-${profesor.id}">
<div class="row">
<div class="col-12">
<div class="progress">
<div class="progress-bar bg-success" role="progressbar" style="width: ${porcentajes.asistencias}%" aria-valuenow="${porcentajes.asistencias}" aria-valuemin="0" aria-valuemax="100"></div>
<!-- Show retardos only if it's set to true -->
${retardos ? `<div class="progress-bar bg-warning" role="progressbar" style="width: ${porcentajes.retardos}%" aria-valuenow="${porcentajes.retardos}" aria-valuemin="0" aria-valuemax="100"></div>` : ``}
<div class="progress-bar bg-azul" role="progressbar" style="width: ${porcentajes.justificaciones}%" aria-valuenow="${porcentajes.justificaciones}" aria-valuemin="0" aria-valuemax="100"></div>
<div class="progress-bar bg-info" role="progressbar" style="width: ${porcentajes.faltas}%" aria-valuenow="${porcentajes.faltas}" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</div>
</div>
<!-- Span Asistencias: # Retardos: # Faltas: # -->
<div class="row justify-content-center">
<span class="mx-3 mt-1">Asistencias: ${profesor.asistencias}</span>
${retardos ? `<span class="mx-3 mt-1">Retardos: ${profesor.retardos}</span>` : `` }
<span class="mx-3 mt-1">Justificaciones: ${profesor.justificaciones}</span>
<span class="mx-3 mt-1">Faltas: ${profesor.faltas}</span>
</div>
</div>
`;
return html;
}

View File

@@ -1,120 +1,120 @@
// @ts-ignore Import module
import { createApp, reactive } from 'https://unpkg.com/petite-vue?module';
const webServices = {
getPeriodosV1: async () => {
try {
const response = await fetch('periodos.v1.php');
return await response.json();
}
catch (error) {
console.log(error);
return [];
}
},
getPeriodosV2: async () => {
try {
const response = await fetch('periodos.v2.php');
return await response.json();
}
catch (error) {
console.log(error);
return [];
}
}
};
const store = reactive({
periodosV1: [],
periodosV2: [],
errors: [],
fechas(idPeriodo) {
const periodo = this.periodosV2.find((periodo) => periodo.IdPeriodo === idPeriodo);
return {
inicio: periodo ? periodo.FechaInicio : '',
fin: periodo ? periodo.FechaFin : ''
};
},
periodov1(idPeriodo) {
return this.periodosV1.find((periodo) => periodo.IdPeriodo === idPeriodo);
},
periodov2(idPeriodo) {
return this.periodosV2.filter((periodo) => periodo.IdPeriodo === idPeriodo);
},
async addPeriodo(periodo) {
try {
const result = await fetch('backend/periodos.php', {
method: 'POST',
body: JSON.stringify({
...periodo,
...this.fechas(periodo.IdPeriodo)
}),
headers: {
'Content-Type': 'application/json'
}
}).then((response) => response.json());
if (result.success) {
this.periodosV1 = this.periodosV1.map((periodoV1) => {
if (periodoV1.IdPeriodo === periodo.IdPeriodo) {
periodoV1.in_db = true;
}
return periodoV1;
});
return result;
}
else {
this.errors.push(result.message);
}
}
catch (error) {
this.errors.push(error);
}
},
async addCarreras(idPeriodo) {
try {
const periodoV1 = this.periodov1(idPeriodo);
const periodoV2 = this.periodov2(idPeriodo);
const data = periodoV2.map(({ ClaveCarrera, NombreCarrera }) => ({
ClaveCarrera: ClaveCarrera,
NombreCarrera: NombreCarrera,
IdNivel: periodoV1.IdNivel,
}));
const result = await fetch('backend/carreras.php', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then((response) => response.json());
if (result.success) {
await webServices.getPeriodosV1().then((periodosV1) => {
this.periodosV1 = periodosV1;
});
await webServices.getPeriodosV2().then((periodosV2) => {
this.periodosV2 = periodosV2;
});
}
}
catch (error) {
this.errors.push(error);
}
}
});
createApp({
store,
info(IdPeriodo) {
const periodo = store.periodosV2.find((periodo) => periodo.IdPeriodo === IdPeriodo &&
periodo.FechaInicio != '' && periodo.FechaFin != '');
return periodo;
},
complete(IdPeriodo) {
const info = this.info(IdPeriodo);
return info !== undefined;
},
mounted: async () => {
await webServices.getPeriodosV1().then((periodosV1) => {
store.periodosV1 = periodosV1;
});
await webServices.getPeriodosV2().then((periodosV2) => {
store.periodosV2 = periodosV2;
});
}
}).mount();
// @ts-ignore Import module
import { createApp, reactive } from 'https://unpkg.com/petite-vue?module';
const webServices = {
getPeriodosV1: async () => {
try {
const response = await fetch('periodos.v1.php');
return await response.json();
}
catch (error) {
console.log(error);
return [];
}
},
getPeriodosV2: async () => {
try {
const response = await fetch('periodos.v2.php');
return await response.json();
}
catch (error) {
console.log(error);
return [];
}
}
};
const store = reactive({
periodosV1: [],
periodosV2: [],
errors: [],
fechas(idPeriodo) {
const periodo = this.periodosV2.find((periodo) => periodo.IdPeriodo === idPeriodo);
return {
inicio: periodo ? periodo.FechaInicio : '',
fin: periodo ? periodo.FechaFin : ''
};
},
periodov1(idPeriodo) {
return this.periodosV1.find((periodo) => periodo.IdPeriodo === idPeriodo);
},
periodov2(idPeriodo) {
return this.periodosV2.filter((periodo) => periodo.IdPeriodo === idPeriodo);
},
async addPeriodo(periodo) {
try {
const result = await fetch('backend/periodos.php', {
method: 'POST',
body: JSON.stringify({
...periodo,
...this.fechas(periodo.IdPeriodo)
}),
headers: {
'Content-Type': 'application/json'
}
}).then((response) => response.json());
if (result.success) {
this.periodosV1 = this.periodosV1.map((periodoV1) => {
if (periodoV1.IdPeriodo === periodo.IdPeriodo) {
periodoV1.in_db = true;
}
return periodoV1;
});
return result;
}
else {
this.errors.push(result.message);
}
}
catch (error) {
this.errors.push(error);
}
},
async addCarreras(idPeriodo) {
try {
const periodoV1 = this.periodov1(idPeriodo);
const periodoV2 = this.periodov2(idPeriodo);
const data = periodoV2.map(({ ClaveCarrera, NombreCarrera }) => ({
ClaveCarrera: ClaveCarrera,
NombreCarrera: NombreCarrera,
IdNivel: periodoV1.IdNivel,
}));
const result = await fetch('backend/carreras.php', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then((response) => response.json());
if (result.success) {
await webServices.getPeriodosV1().then((periodosV1) => {
this.periodosV1 = periodosV1;
});
await webServices.getPeriodosV2().then((periodosV2) => {
this.periodosV2 = periodosV2;
});
}
}
catch (error) {
this.errors.push(error);
}
}
});
createApp({
store,
info(IdPeriodo) {
const periodo = store.periodosV2.find((periodo) => periodo.IdPeriodo === IdPeriodo &&
periodo.FechaInicio != '' && periodo.FechaFin != '');
return periodo;
},
complete(IdPeriodo) {
const info = this.info(IdPeriodo);
return info !== undefined;
},
mounted: async () => {
await webServices.getPeriodosV1().then((periodosV1) => {
store.periodosV1 = periodosV1;
});
await webServices.getPeriodosV2().then((periodosV2) => {
store.periodosV2 = periodosV2;
});
}
}).mount();

View File

@@ -1,288 +1,288 @@
// initial state
const días = ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado"];
const horas_estándar = /* range from 7 to 22 */ Array.from(Array(22 - 7 + 1).keys()).map(x => x + 7);
// fill the table with empty cells
for (let i = 0; i < horas_estándar.length - 1; i++) {
const hora = horas_estándar[i];
const tr = document.createElement("tr");
tr.id = `hora-${hora}-00`;
tr.classList.add(hora > 13 ? "tarde" : "mañana");
const th = document.createElement("th");
th.classList.add("text-center");
th.scope = "row";
th.rowSpan = 4;
th.innerText = `${hora}:00`;
th.style.verticalAlign = "middle";
tr.appendChild(th);
for (let j = 0; j < días.length; j++) {
const día = días[j];
const td = document.createElement("td");
td.id = `hora-${hora}-00-${día}`;
tr.appendChild(td);
}
document.querySelector("tbody#horario")?.appendChild(tr);
// add 7 rows for each hour
const hours = [15, 30, 45];
for (let j = 1; j < 4; j++) {
const tr = document.createElement("tr");
tr.id = `hora-${hora}-${hours[j - 1]}`;
tr.classList.add(hora > 13 ? "tarde" : "mañana");
for (let k = 0; k < días.length; k++) {
const día = días[k];
const td = document.createElement("td");
td.id = `hora-${hora}-${hours[j - 1]}-${día}`;
// td.innerText = `hora-${hora}-${hours[j - 1]}-${día}`;
tr.appendChild(td);
}
document.querySelector("tbody#horario")?.appendChild(tr);
}
}
// add an inital height to the table cells
const tds = document.querySelectorAll("tbody#horario td");
tds.forEach(td => td.style.height = "2rem");
var table = document.querySelector("table");
var empty_table = table?.innerHTML || "";
// hide the table
table.style.display = "none";
document.getElementById('dlProfesor')?.addEventListener('input', function () {
var input = document.getElementById('dlProfesor');
var value = input.value;
var option = document.querySelector(`option[value="${value}"]`);
if (option) {
var id = option.getAttribute('data-id');
const input_profesor = document.getElementById('editor_profesor');
input_profesor.value = id;
// remove is invalid class
input.classList.remove("is-invalid");
// add is valid class
input.classList.add("is-valid");
}
else {
const input_profesor = document.getElementById('editor_profesor');
input_profesor.value = "";
// remove is valid class
input.classList.remove("is-valid");
// add is invalid class
input.classList.add("is-invalid");
}
});
/**
* Functions and Methods
**/
const buscarGrupo = async () => {
// Add loading animation in the button
const btn = document.querySelector("#btn-buscar");
btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Cargando...';
btn.disabled = true;
const carrera = document.querySelector("#filter_carrera")?.value;
const grupo = document.querySelector("#filter_grupo")?.value;
console.log(`Carrera: ${carrera}, Grupo: ${grupo}`);
if (carrera == "" || grupo == "") {
triggerMessage("El nombre del grupo y la carrera son requeridos", "Faltan campos");
// Remove loading animation in the button
btn.innerHTML = '<i class="ing-buscar ing"></i> Buscar';
btn.disabled = false;
return;
}
const formData = new FormData();
formData.append("carrera", carrera);
formData.append("grupo", grupo);
formData.append("periodo", document.querySelector("#periodo")?.value);
const thisScript = document.currentScript;
const facultad = thisScript.getAttribute("data-facultad");
formData.append('facultad', facultad);
try {
const response = await fetch("action/action_horario.php", {
method: "POST",
body: formData
}).then(res => res.json());
if (response.status == "success") {
let limits = {
min: 22,
max: 7
};
let sábado = false;
const horario = response.horario;
// show the table
table.style.display = "table";
// clear the table
table.innerHTML = empty_table;
// fill the table
for (let i = 0; i < horario.length; i++) {
const dia = horario[i].dia;
if (dia == "sábado")
sábado = true;
const { hora, minutos } = {
hora: parseInt(horario[i].hora.split(":")[0]),
minutos: horario[i].hora.split(":")[1]
};
// update the limits
if (hora < limits.min) {
limits.min = hora;
}
if (hora > limits.max) {
limits.max = hora;
}
const materia = horario[i].materia;
const profesor = horario[i].profesor;
const salon = horario[i].salon;
const id = horario[i].horario_id;
const prof_id = horario[i].profesor_id;
const cell = document.querySelector(`#hora-${hora}-${minutos}-${dia}`);
cell.innerHTML =
`
<div>
<small class="text-gray">${hora}:${minutos}</small>
<b class="title">${materia}</b> <br>
<br><span>Salón: </span>${salon} <br>
<span class="ing ing-formacion mx-1"></span>${profesor}
</div>
`;
const html = `<div class="menu-flotante p-2">
<a
class="mx-2"
href="#"
data-toggle="modal"
data-target="#modal-editar"
data-dia="${dia}"
data-hora="${hora}:${minutos}"
data-materia="${materia}"
data-profesor="${prof_id}"
data-salon="${salon}"
data-id="${id}"
>
<i class="ing-editar ing"></i>
</a>
<a
class="mx-2"
href="#"
data-toggle="modal"
data-target="#modal-borrar"
data-hoario_id="${id}"
>
<i class="ing-basura ing"></i>
</a>
</div>`;
const td = cell.closest("td");
td.innerHTML += html;
td.classList.add("position-relative");
// this cell spans 4 rows
cell.rowSpan = 6;
cell.classList.add("bloque-clase", "overflow");
for (let j = 1; j < 6; j++) {
const minute = (parseInt(minutos) + j * 15);
const next_minute = (minute % 60).toString().padStart(2, "0");
const next_hour = (hora + Math.floor(minute / 60));
const next_cell = document.querySelector(`#hora-${next_hour}-${next_minute}-${dia}`);
next_cell.remove();
}
}
// remove the elements that are not in the limits
const horas = document.querySelectorAll("tbody#horario tr");
for (let i = 0; i < horas.length; i++) {
const hora = horas[i];
const hora_id = parseInt(hora.id.split("-")[1]);
if (hora_id < limits.min || hora_id > limits.max) {
hora.remove();
}
}
// if there is no sábado, remove the column
if (!sábado) {
document.querySelectorAll("tbody#horario td").forEach(td => {
if (td.id.split("-")[3] == "sábado") {
td.remove();
}
});
// remove the header (the last)
const headers = document.querySelector("#headers");
headers.lastElementChild?.remove();
}
// adjust width
const ths = document.querySelectorAll("tr#headers th");
const width = 95 / (ths.length - 1);
ths.forEach((th, key) => th.style.width = (key == 0) ? "5%" : `${width}%`);
// search item animation
const menúFlontantes = document.querySelectorAll(".menu-flotante");
menúFlontantes.forEach((element) => {
element.classList.add("d-none");
element.parentElement?.addEventListener("mouseover", () => {
element.classList.remove("d-none");
});
element.parentElement?.addEventListener("mouseout", () => {
element.classList.add("d-none");
});
});
}
else {
triggerMessage(response.message, "Error");
// Remove loading animation in the button
btn.innerHTML = '<i class="ing-buscar ing"></i> Buscar';
btn.disabled = false;
}
}
catch (error) {
triggerMessage("Error al cargar el horario", "Error");
triggerMessage(error, "Error");
}
// Remove loading animation in the button
btn.innerHTML = '<i class="ing-buscar ing"></i> Buscar';
btn.disabled = false;
};
async function guardar(id) {
const btn = document.querySelector("#btn-guardar");
const clone = btn.cloneNode(true);
btn.innerHTML = '<i class="ing-cargando ing"></i> Guardando...';
btn.disabled = true;
const data = {
hora: document.querySelector("#editor_hora"),
dia: document.querySelector("#editor_dia"),
salon: document.querySelector("#editor_salón"),
profesor: document.querySelector("#editor_profesor"),
};
const hora = data.hora.value; // h:mm
const { compareHours } = await import('./date_functions');
const hora_antes = compareHours(hora, "07:15") < 0;
const hora_después = compareHours(hora, "21:30") > 0;
if (hora_antes || hora_después) {
alert(`La hora ${hora} no es válida`);
triggerMessage("Selecciona una hora", "Error");
btn.innerHTML = clone.innerHTML;
btn.disabled = false;
data.hora.focus();
data.hora.classList.add("is-invalid");
return;
}
const dia = data.dia.value;
const salon = data.salon.value;
const profesor = data.profesor.value;
const formData = new FormData();
formData.append("id", id);
formData.append("hora", hora);
formData.append("dia", dia);
formData.append("salon", salon);
formData.append("profesor", profesor);
const response = await fetch("action/action_horario_update.php", {
method: "POST",
body: formData
}).then(res => res.json());
if (response.status == "success") {
triggerMessage(response.message, "Éxito", "success");
btn.innerHTML = '<i class="ing-aceptar ing"></i> Guardado';
btn.classList.add("btn-success");
btn.classList.remove("btn-primary");
// return to the initial state
setTimeout(() => {
buscarGrupo();
btn.replaceWith(clone);
$("#modal-editar").modal("hide");
}, 1000);
}
else {
triggerMessage(response.message, "Error");
btn.replaceWith(clone);
$("#modal-editar").modal("hide");
}
}
function triggerMessage(message, header, colour = "danger") {
throw new Error('Function not implemented.');
}
// initial state
const días = ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado"];
const horas_estándar = /* range from 7 to 22 */ Array.from(Array(22 - 7 + 1).keys()).map(x => x + 7);
// fill the table with empty cells
for (let i = 0; i < horas_estándar.length - 1; i++) {
const hora = horas_estándar[i];
const tr = document.createElement("tr");
tr.id = `hora-${hora}-00`;
tr.classList.add(hora > 13 ? "tarde" : "mañana");
const th = document.createElement("th");
th.classList.add("text-center");
th.scope = "row";
th.rowSpan = 4;
th.innerText = `${hora}:00`;
th.style.verticalAlign = "middle";
tr.appendChild(th);
for (let j = 0; j < días.length; j++) {
const día = días[j];
const td = document.createElement("td");
td.id = `hora-${hora}-00-${día}`;
tr.appendChild(td);
}
document.querySelector("tbody#horario")?.appendChild(tr);
// add 7 rows for each hour
const hours = [15, 30, 45];
for (let j = 1; j < 4; j++) {
const tr = document.createElement("tr");
tr.id = `hora-${hora}-${hours[j - 1]}`;
tr.classList.add(hora > 13 ? "tarde" : "mañana");
for (let k = 0; k < días.length; k++) {
const día = días[k];
const td = document.createElement("td");
td.id = `hora-${hora}-${hours[j - 1]}-${día}`;
// td.innerText = `hora-${hora}-${hours[j - 1]}-${día}`;
tr.appendChild(td);
}
document.querySelector("tbody#horario")?.appendChild(tr);
}
}
// add an inital height to the table cells
const tds = document.querySelectorAll("tbody#horario td");
tds.forEach(td => td.style.height = "2rem");
var table = document.querySelector("table");
var empty_table = table?.innerHTML || "";
// hide the table
table.style.display = "none";
document.getElementById('dlProfesor')?.addEventListener('input', function () {
var input = document.getElementById('dlProfesor');
var value = input.value;
var option = document.querySelector(`option[value="${value}"]`);
if (option) {
var id = option.getAttribute('data-id');
const input_profesor = document.getElementById('editor_profesor');
input_profesor.value = id;
// remove is invalid class
input.classList.remove("is-invalid");
// add is valid class
input.classList.add("is-valid");
}
else {
const input_profesor = document.getElementById('editor_profesor');
input_profesor.value = "";
// remove is valid class
input.classList.remove("is-valid");
// add is invalid class
input.classList.add("is-invalid");
}
});
/**
* Functions and Methods
**/
const buscarGrupo = async () => {
// Add loading animation in the button
const btn = document.querySelector("#btn-buscar");
btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Cargando...';
btn.disabled = true;
const carrera = document.querySelector("#filter_carrera")?.value;
const grupo = document.querySelector("#filter_grupo")?.value;
console.log(`Carrera: ${carrera}, Grupo: ${grupo}`);
if (carrera == "" || grupo == "") {
triggerMessage("El nombre del grupo y la carrera son requeridos", "Faltan campos");
// Remove loading animation in the button
btn.innerHTML = '<i class="ing-buscar ing"></i> Buscar';
btn.disabled = false;
return;
}
const formData = new FormData();
formData.append("carrera", carrera);
formData.append("grupo", grupo);
formData.append("periodo", document.querySelector("#periodo")?.value);
const thisScript = document.currentScript;
const facultad = thisScript.getAttribute("data-facultad");
formData.append('facultad', facultad);
try {
const response = await fetch("action/action_horario.php", {
method: "POST",
body: formData
}).then(res => res.json());
if (response.status == "success") {
let limits = {
min: 22,
max: 7
};
let sábado = false;
const horario = response.horario;
// show the table
table.style.display = "table";
// clear the table
table.innerHTML = empty_table;
// fill the table
for (let i = 0; i < horario.length; i++) {
const dia = horario[i].dia;
if (dia == "sábado")
sábado = true;
const { hora, minutos } = {
hora: parseInt(horario[i].hora.split(":")[0]),
minutos: horario[i].hora.split(":")[1]
};
// update the limits
if (hora < limits.min) {
limits.min = hora;
}
if (hora > limits.max) {
limits.max = hora;
}
const materia = horario[i].materia;
const profesor = horario[i].profesor;
const salon = horario[i].salon;
const id = horario[i].horario_id;
const prof_id = horario[i].profesor_id;
const cell = document.querySelector(`#hora-${hora}-${minutos}-${dia}`);
cell.innerHTML =
`
<div>
<small class="text-gray">${hora}:${minutos}</small>
<b class="title">${materia}</b> <br>
<br><span>Salón: </span>${salon} <br>
<span class="ing ing-formacion mx-1"></span>${profesor}
</div>
`;
const html = `<div class="menu-flotante p-2">
<a
class="mx-2"
href="#"
data-toggle="modal"
data-target="#modal-editar"
data-dia="${dia}"
data-hora="${hora}:${minutos}"
data-materia="${materia}"
data-profesor="${prof_id}"
data-salon="${salon}"
data-id="${id}"
>
<i class="ing-editar ing"></i>
</a>
<a
class="mx-2"
href="#"
data-toggle="modal"
data-target="#modal-borrar"
data-hoario_id="${id}"
>
<i class="ing-basura ing"></i>
</a>
</div>`;
const td = cell.closest("td");
td.innerHTML += html;
td.classList.add("position-relative");
// this cell spans 4 rows
cell.rowSpan = 6;
cell.classList.add("bloque-clase", "overflow");
for (let j = 1; j < 6; j++) {
const minute = (parseInt(minutos) + j * 15);
const next_minute = (minute % 60).toString().padStart(2, "0");
const next_hour = (hora + Math.floor(minute / 60));
const next_cell = document.querySelector(`#hora-${next_hour}-${next_minute}-${dia}`);
next_cell.remove();
}
}
// remove the elements that are not in the limits
const horas = document.querySelectorAll("tbody#horario tr");
for (let i = 0; i < horas.length; i++) {
const hora = horas[i];
const hora_id = parseInt(hora.id.split("-")[1]);
if (hora_id < limits.min || hora_id > limits.max) {
hora.remove();
}
}
// if there is no sábado, remove the column
if (!sábado) {
document.querySelectorAll("tbody#horario td").forEach(td => {
if (td.id.split("-")[3] == "sábado") {
td.remove();
}
});
// remove the header (the last)
const headers = document.querySelector("#headers");
headers.lastElementChild?.remove();
}
// adjust width
const ths = document.querySelectorAll("tr#headers th");
const width = 95 / (ths.length - 1);
ths.forEach((th, key) => th.style.width = (key == 0) ? "5%" : `${width}%`);
// search item animation
const menúFlontantes = document.querySelectorAll(".menu-flotante");
menúFlontantes.forEach((element) => {
element.classList.add("d-none");
element.parentElement?.addEventListener("mouseover", () => {
element.classList.remove("d-none");
});
element.parentElement?.addEventListener("mouseout", () => {
element.classList.add("d-none");
});
});
}
else {
triggerMessage(response.message, "Error");
// Remove loading animation in the button
btn.innerHTML = '<i class="ing-buscar ing"></i> Buscar';
btn.disabled = false;
}
}
catch (error) {
triggerMessage("Error al cargar el horario", "Error");
triggerMessage(error, "Error");
}
// Remove loading animation in the button
btn.innerHTML = '<i class="ing-buscar ing"></i> Buscar';
btn.disabled = false;
};
async function guardar(id) {
const btn = document.querySelector("#btn-guardar");
const clone = btn.cloneNode(true);
btn.innerHTML = '<i class="ing-cargando ing"></i> Guardando...';
btn.disabled = true;
const data = {
hora: document.querySelector("#editor_hora"),
dia: document.querySelector("#editor_dia"),
salon: document.querySelector("#editor_salón"),
profesor: document.querySelector("#editor_profesor"),
};
const hora = data.hora.value; // h:mm
const { compareHours } = await import('./date_functions');
const hora_antes = compareHours(hora, "07:15") < 0;
const hora_después = compareHours(hora, "21:30") > 0;
if (hora_antes || hora_después) {
alert(`La hora ${hora} no es válida`);
triggerMessage("Selecciona una hora", "Error");
btn.innerHTML = clone.innerHTML;
btn.disabled = false;
data.hora.focus();
data.hora.classList.add("is-invalid");
return;
}
const dia = data.dia.value;
const salon = data.salon.value;
const profesor = data.profesor.value;
const formData = new FormData();
formData.append("id", id);
formData.append("hora", hora);
formData.append("dia", dia);
formData.append("salon", salon);
formData.append("profesor", profesor);
const response = await fetch("action/action_horario_update.php", {
method: "POST",
body: formData
}).then(res => res.json());
if (response.status == "success") {
triggerMessage(response.message, "Éxito", "success");
btn.innerHTML = '<i class="ing-aceptar ing"></i> Guardado';
btn.classList.add("btn-success");
btn.classList.remove("btn-primary");
// return to the initial state
setTimeout(() => {
buscarGrupo();
btn.replaceWith(clone);
$("#modal-editar").modal("hide");
}, 1000);
}
else {
triggerMessage(response.message, "Error");
btn.replaceWith(clone);
$("#modal-editar").modal("hide");
}
}
function triggerMessage(message, header, colour = "danger") {
throw new Error('Function not implemented.');
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,75 +1,75 @@
/*
jQuery Custom Input File Plugin - version 1.0
Copyright 2014, Ángel Espro, www.aesolucionesweb.com.ar,
Licence : GNU General Public License
Site: www.aesolucionesweb.com.ar/plugins/custom-input-file
You must not remove these lines. Read gpl.txt for further legal information.
*/
(function($){CustomFile=function(elem,options){this.elem=$(elem);this.itemFileList=[];this.defaults={type:'all',allowed:'all',notAllowed:[],addContainerAfter:$(elem),multiple:true,maxFiles:5,maxMB:0,maxKBperFile:2048,fileWrapper:'<div class="cif-parent"></div>',filePicker:'<h3>Soltar archivos aquí</h3><p>o clic para seleccionar desde carpeta</p><div class="cif-icon-picker"></div>',image:{crop:false,preview:{display:true,maxWidth:300},cropSize:[320,225],minSize:[0,0],maxSize:[0,0]},messages:{errorType:"Tipo de archivo no permitido",errorMaxMB:"Peso máximo de archivos acumulado excedido",errorFileKB:"Archivo muy pesado",errorMaxFiles:"Cantidad máxima de archivos alcanzada",errorBigImage:"Imagen muy grande",errorSmallImage:"Imagen muy pequeña",errorOnReading:"Aplicación ocupada. Inténtelo más tarde.",errorMultipleDisable:"Suelte un archivo por vez."},popup:{active:true,autoclose:true,delay:10000},callbacks:{onComplete:function(app){},beforeRead:function(file){},onSuccess:function(item,callback){},onError:function(file,msg){},beforeRemove:function(item){},}}
this.settings=$.extend(true,{},this.defaults,options);this.status='stop';this.init();}
CustomFile.prototype={init:function(){var attnm=this.elem.attr("name");if(attnm=='')var attnm="inputfile";this.name=(attnm.indexOf("[]",attnm-2)===-1)?attnm+"[]":attnm;this.form=this.elem.parents('form');this.container=$('<div class="cif-file-container cif-container-'+this.settings.type+'-type">');var image=this.settings.image;image.minSize=(typeof(image.minSize)!=='object'||image.minSize.length!==2)?[0,0]:image.minSize;if(image.crop){var minSize=[];for(i=0;i<image.minSize.length;i++){var value=(image.minSize[i]>image.cropSize[i])?image.minSize[i]:image.cropSize[i];minSize.push(value);}
image.minSize=minSize}
this.setFileWrapper();this.appendContainer();this.filePicker=new FilePicker(this);$.customFile.elements.push(this);},onSuccess:function(item,callback){this.itemFileList.push(item);if(this.settings.callbacks.onSuccess(item,callback)===false)return;callback();},onError:function(file,msg){this.settings.callbacks.onError(file,msg);var popupSet=this.settings.popup;if(popupSet.active)
for(k=0;k<msg.length;k++){var fileExt=file.name.substr(file.name.lastIndexOf('.')+1);var fileName=file.name.substr(0,file.name.lastIndexOf('.'));if(fileName.length>42)var fileName=fileName.substr(0,40)+"...";msg[k]+=' ('+fileName+'.'+fileExt+')';$.customFile.popup.add(msg[k],popupSet.autoclose,popupSet.delay,'error');}},onComplete:function(){this.status="completed";if(this.settings.multiple){var response=this.checkMaxFiles()
var popupSet=this.settings.popup;if(response&&popupSet.active)$.customFile.popup.add(response,popupSet.autoclose,popupSet.delay,'ok');}else{if(this.itemFileList.length>1)this.itemFileList[0].destroy();}
this.settings.callbacks.onComplete(this);},read:function(fileList,currentItem){var i=currentItem;if(i+1>fileList.length)this.status='completed';if(this.status==='completed'){this.onComplete();return false;}
var beforeRead=this.settings.callbacks.beforeRead(fileList[i]);if(beforeRead===false)return this.read(fileList,i+1);app=this;var response=app.checkMaxFiles(fileList[i]);if(typeof(response)==='string'){this.onError(fileList[i],[response]);return this.read(fileList,i+1);}
var msg=[];var checklist=["checkFileKB","checkFileType","checkTotalMB"]
for(j=0;j<checklist.length;j++){var response=app[checklist[j]](fileList[i]);if(response)msg.push(response)}
if(msg.length>0){this.onError(fileList[i],msg);return this.read(fileList,i+1);}
new FileItem(this,fileList,i);},appendContainer:function(){var sett=this.settings;if(sett.fileWrapper.parent().length!=0&&sett.appendAfter!=this.elem){sett.addContainerAfter=sett.fileWrapper;}
sett.addContainerAfter.after(this.container);},setFileWrapper:function(){var app=this;var fwr=this.settings.fileWrapper;if(typeof(fwr)==='string')this.settings.fileWrapper=$(fwr);this.settings.fileWrapper=$('<div>',{class:"cif-file-row"}).append(this.settings.fileWrapper);var fwr=this.settings.fileWrapper;fwr.find(':input').each(function(index){var $this=$(this);var attnm=$this.attr("name");if(!attnm)var attnm=app.name.substr(0,app.name.indexOf("[]",-2))+"-"+index;if(attnm.indexOf("[]",-2)===-1){$this.attr("name",attnm+"[]");}});if(fwr.find('.cif-img').length==0&&this.settings.type=='image'){var parent=fwr.find('.cif-parent');if(parent.length===0){var $img=fwr.find('img');var parent=$('<div>',{class:'cif-parent'});parent.append($img);fwr.append(parent);}
if(parent.find('img').length===0)parent.append('<img>')
parent.find('img').addClass("cif-img");}
if(fwr.find('.cif-parent').length==0){fwr.prepend('<div class="cif-parent"></div>');}},checkFileKB:function(file){if(file.size>this.settings.maxKBperFile*1024&&this.settings.maxKBperFile!=0){var msg=this.settings.messages.errorFileKB;}
return msg;},checkFileType:function(file){var ext=file.name.substr(file.name.lastIndexOf('.')+1);var ext=ext.toLowerCase();var imageCropAllowed=["jpeg","jpg","png"]
if((this.settings.type=='image'&&this.settings.image.crop&&imageCropAllowed.indexOf(ext)==-1)||(this.settings.type=='image'&&!file.type.match(/image\//))||(this.settings.allowed!='all'&&this.settings.allowed.indexOf(ext)==-1)||(this.settings.notAllowed.indexOf(ext)!=-1))
{var msg=this.settings.messages.errorType;}
return msg;},checkMaxFiles:function(file){if(this.settings.maxFiles<=this.itemFileList.length&&this.settings.maxFiles){var msg=this.settings.messages.errorMaxFiles;this.filePicker.btn.addClass('inactive');}else{this.filePicker.btn.removeClass('inactive');}
return msg;},checkTotalMB:function(file){var fileSize=(typeof(file)!=='undefined')?file.size:0;var totalSize=0;for(var obj in this.itemFileList){totalSize+=this.itemFileList[obj].file.size;}
if(fileSize+totalSize>this.settings.maxMB*1024*1024&&this.settings.maxMB!=0){var msg=this.settings.messages.errorMaxMB;}
return msg;},checkImageSize:function(img,file){var stt=this.settings.image
if((stt.minSize[0]&&img.width<stt.minSize[0])||(stt.minSize[1]&&img.height<stt.minSize[1])){var msg=this.settings.messages.errorSmallImage;if(stt.minSize[0])msg+=' Ancho mínimo:'+stt.minSize[0]+'px.';if(stt.minSize[1])msg+=' Alto mínimo: '+stt.minSize[1]+'px.';}
if((stt.maxSize[0]&&img.width>stt.maxSize[0])||(stt.maxSize[1]&&img.height>stt.maxSize[1])){var msg=this.settings.messages.errorBigImage;if(stt.maxSize[0])msg+=' Ancho máximo:'+stt.maxSize[0]+'px.';if(stt.maxSize[1])msg+=' Alto máximo: '+stt.maxSize[1]+'px.';}
return msg;},}
FilePicker=function(app){this.btn=$('<div class="cif-file-picker"></div>').append(app.settings.filePicker);this.init(app);}
FilePicker.prototype={init:function(app){var multiple=(app.settings.multiple||app.elem.attr("multiple")=="multiple")?'multiple="multiple"':' ';this.inputHidden=$('<input type="file" '+multiple+'/>');app.elem.after(this.btn);var elem=app.elem.clone();app.elem.detach();app.elem=elem;this.btn.addClass("cif-pkr-"+app.elem.attr("name"));var btn=this.btn;var inputHidden=this.inputHidden;inputHidden.change(function(){var popupSet=app.settings.popup;if(app.status=='reading')return $.customFile.popup.add(app.settings.messages.errorOnReading,popupSet.autoclose,popupSet.delay,'error');$.customFile.popup.close();fileList=$(this)[0].files;app.status='reading';app.read(fileList,0);});btn.on({click:function(){if(!$(this).is('.inactive'))inputHidden.click();return false;},dragover:function(e){e=e||window.event;e.preventDefault();if($(this).is('.inactive'))e.dataTransfer.dropEffect='none';btn.addClass('dragover');return false;},dragleave:function(e){btn.removeClass('dragover');return false;},drop:function(e){e=window.event;e.preventDefault();btn.removeClass('dragover');var popupSet=app.settings.popup;if(app.status=='reading')return $.customFile.popup.add(app.settings.messages.errorOnReading,popupSet.autoclose,popupSet.delay,'error');$.customFile.popup.close();var fileList=e.dataTransfer.files;if(fileList.length>1&&!app.settings.multiple)return $.customFile.popup.add(app.settings.messages.errorMultipleDisable,popupSet.autoclose,popupSet.delay,'error');app.status='reading';app.read(fileList,0);}});},};FileItem=function(app,fileList,currentItem){this.file=fileList[currentItem];this.app=app;this.fileList=fileList;this.currentItem=currentItem;this.init();}
FileItem.prototype={init:function(){this.jcropObj=null;this.node=this.app.settings.fileWrapper.clone();this.img=null;this.btnClose=$('<div class="cif-close" title="Remove">close</div>');this.btnClose.click(function(){fileObj.destroy();});this.fr=new FileReader;var fr=this.fr;var app=this.app;var fileObj=this;var fileList=this.fileList;var currentItem=this.currentItem;var callback=function(){app.onSuccess(fileObj,function(){app.read(fileList,currentItem+1);});delete fileObj.fr;delete fileObj.fileList;delete fileObj.currentItem;}
fr.onload=function(){switch(app.settings.type){case"image":fileObj.readImage(callback);break;default:fileObj.readAllTypes(callback);break;}}
fr.readAsDataURL(this.file);},destroy:function(){this.app.settings.callbacks.beforeRemove(this);if(this.node)this.node.remove();var i=this.app.itemFileList.indexOf(this);this.app.itemFileList.splice(i,1);this.app.checkMaxFiles();},serialize:function(){return $.customFile.serialize([{key:this.app.name,value:this.file}]);},readImage:function(callback){var fileObj=this;var fr=this.fr;var app=this.app;var imgNode=fileObj.node.find("img.cif-img");fileObj.img=new Image;fileObj.img.src=fr.result;fileObj.img.onload=function(){msg=app.checkImageSize(fileObj.img,fileObj.file);if(msg){app.onError(fileObj.file,[msg]);return app.read(fileObj.fileList,fileObj.currentItem+1);}
imgNode.attr("src",fr.result);imgNode.parent().prepend(fileObj.btnClose);app.container.append(fileObj.node);if(app.settings.image.crop===true){fileObj.jcropObj=fileObj.initJcrop(app.settings.image,imgNode.parent(),fileObj.img,app.name);}
callback();}},readAllTypes:function(callback){fileObj=this;var parent=fileObj.node.find('.cif-parent');var FileExt=fileObj.file.name.substr(fileObj.file.name.lastIndexOf('.')+1);var FileName=fileObj.file.name.substr(0,fileObj.file.name.lastIndexOf('.'));if(FileName.length>42)var FileName=FileName.substr(0,40)+"...";var fileSize=(fileObj.file.size<102400)?(fileObj.file.size/1024).toFixed(2):Math.round(fileObj.file.size/1024);parent.append($('<div class="cif-all-type">'+FileName+'.'+FileExt+' <span class="cif-file-size">('+fileSize+'KB)</span><div>')).append(fileObj.btnClose);this.app.container.append(fileObj.node)
callback();},initJcrop:function(options,parent,img,appName){var jcrop_api,boundx,boundy;if(options.preview.display){appName=appName.replace("[]","");prevMaxWidth=options.preview.maxWidth;prevSize=(options.cropSize[0]>prevMaxWidth)?[prevMaxWidth,options.cropSize[1]/options.cropSize[0]*prevMaxWidth]:options.cropSize;parent.append('<div class="preview-pane" style="width:'+prevSize[0]+'px;height:'+prevSize[1]+'px;"><div class="preview-container" style="width:'+prevSize[0]+'px;height:'+prevSize[1]+'px; overflow:hidden"><img src="'+img.src+'" class="jcrop-preview im-prv" /></div></div> '
+'<input type="hidden" class="jcropx" name="'+appName+'-x[]" /><input type="hidden" class="jcropy" name="'+appName+'-y[]" /><input type="hidden" class="jcropw" name="'+appName+'-w[]" /><input type="hidden" class="jcroph" name="'+appName+'-h[]" />');parent.css("min-height",prevSize[1]+20+"px");}
var $preview=parent.find('.preview-pane'),$pcnt=$preview.find('.preview-container'),$pimg=$preview.find('.preview-container img'),xsize=$pcnt.width(),ysize=$pcnt.height();api=parent.find('.cif-img').Jcrop({keySupport:false,onChange:updatePreview,onSelect:updatePreview,aspectRatio:options.cropSize[0]/options.cropSize[1],minSize:options.cropSize,trueSize:[img.width,img.height]},function(){var bounds=this.getBounds();boundx=bounds[0];boundy=bounds[1];jcrop_api=this;jcrop_api.animateTo([0,0,options.cropSize[0]]);$preview.appendTo(jcrop_api.ui.holder);});function updatePreview(c){if(parseInt(c.w)>0&&options.preview.display){var rx=xsize / c.w;var ry=ysize / c.h;$pimg.css({width:Math.round(rx*boundx)+'px',height:Math.round(ry*boundy)+'px',marginLeft:'-'+Math.round(rx*c.x)+'px',marginTop:'-'+Math.round(ry*c.y)+'px'});}
updateCoords(c);};function updateCoords(c){parent.find('.jcropx').val(c.x);parent.find('.jcropy').val(c.y);parent.find('.jcropw').val(c.w);parent.find('.jcroph').val(c.h);}
return jcrop_api;}}
$.customFile={elements:[],getElements:function(selector){var elements=[];var selector=selector.split(",");var el=$.customFile.elements;for(k=0;k<selector.length;k++){selector[k]=selector[k].trim()
for(i=0;i<el.length;i++){if(el[i].name===selector[k]+"[]"||el[i].name===selector[k])
elements.push({type:"pseudoinput",obj:el[i]});if($(selector[k]).is('form')){$(selector[k]).each(function(){elements.push({type:"form",obj:$(this),pseudoChild:(el[i].form[0]===$(this)[0])});});}
if($(selector[k]).is(':input')){$(selector[k]).not(':submit').each(function(){elements.push({type:"input",obj:$(this)});});}}}
var indexToRemove=[]
for(i=0;i<elements.length;i++){if(indexToRemove.indexOf(i)!==-1)continue;for(j=0;j<elements.length;j++){if(j===i||indexToRemove.indexOf(j)!==-1)continue;switch(elements[i].type){case"form":var el=elements[i].obj[0];if(el===elements[j].obj[0]||(elements[j].type==="pseudoinput"&&el==elements[j].obj.form[0])||(elements[j].type==="input"&&el==elements[j].obj.parents('form')[0])){indexToRemove.push(j);}
break;case"input":var el=elements[i].obj[0];if(el===elements[j].obj[0])
indexToRemove.push(j);break;case"pseudoinput":var el=elements[i].obj.name;if(el===elements[j].obj.name||el+"[]"===elements[j].obj.name)
indexToRemove.push(j);break;}}}
var result=[];for(i=0;i<elements.length;i++){if(indexToRemove.indexOf(i)===-1)result.push(elements[i]);}
return result;},serialize:function(elements){formData=null;if(typeof(elements)==='object'){formData=formData||new FormData();if(!elements.length)var elements=[elements]
for(j=0;j<elements.length;j++){if(elements[j].hasOwnProperty("key")&&elements[j].hasOwnProperty("value")){formData.append(elements[j].key,elements[j].value);}}}
if(typeof(elements)==='string'){elements=this.getElements(elements);for(j=0;j<elements.length;j++){formData=formData||new FormData();var elem=elements[j];switch(elem.type){case'pseudoinput':$.each(elem.obj.itemFileList,function(index,element){formData.append(elem.obj.name,element.file);});break;case"form":$.each(elem.obj.find(':input'),function(){if($(this).not(':submit'))
formData.append($(this).attr("name"),$(this).val());});var app=elem.obj.data("appCustomFile");if(typeof(app)=="undefined"){elem.obj.data("appCustomFile",[]);}
$.each(app,function(){appThis=this;$.each(appThis.itemFileList,function(index,element){formData.append(appThis.name,element.file);});});break;case"input":formData.append(elem.obj.attr("name"),elem.obj.val());break;}}}
return formData},ajax:function(el,options){if(typeof(el)==='string'){var element=this.getElements(el)[0];switch(element.type){case"form":var action=element.obj.attr("action");break;case"input":var action=element.obj.parents("form").attr("action");break;case"pseudoinput":var action=element.obj.form.attr("action");break;}
var formData=$.customFile.serialize(el);}
if(typeof(el)==='object'&&el instanceof FileItem){var formData=el.serialize();var action=el.app.form.attr("action");}
var defaults={cache:false,contentType:false,data:formData,processData:false,url:action,type:'POST',progressBar:{active:true,markup:'<div class="cf-progressbar-wr"><div class="cf-progressbar"><span width="0"></span></div></div>',appendTo:$('body'),removeAfterComplete:true,node:null},progress:function(e,total,position,percent){this.progressBar.node.find("span").width(percent+'%');},xhr:function(){var ax=this;var xhr=$.ajaxSettings.xhr();xhr.upload.onprogress=function(e){var e=e||window.event;var position=e.position||e.loaded;var total=e.totalSize||e.total;var percent=((e.loaded/e.total)*100)+"";ax.progress(e,total,position,percent);};xhr.upload.onload=function(){ax.progressBar.node.find("span").width('100%');if(ax.progressBar.removeAfterComplete)
ax.progressBar.node.fadeOut(function(){$(this).remove();});};return xhr;},beforeSend:function(){},complete:function(){},success:function(xml){},}
var settings=$.extend(true,{},defaults,options);if(!settings.progressBar.active)settings.progress=function(){};settings.progressBar.node=$(settings.progressBar.markup);var settBefore=settings.beforeSend;if(settings.progressBar.active){settings.beforeSend=function(){settBefore();settings.progressBar.appendTo.append(settings.progressBar.node);};}
$.ajax(settings);},validate:function(elements,options){elements=this.getElements(elements);for(j=0;j<elements.length;j++){el=elements[j];switch(el.type){case"form":break;case"input":break;case"pseudoinput":break;}}},popup:{wrapper:$('<div id="cif-msg-wr"><div class="cif-msg-close">close</div></div>'),open:function(){var popup=this;this.wrapper.find('.cif-msg-close').click(function(){popup.close()});$('body').append(popup.wrapper);},add:function(msg,autoclose,delay,type){if(!delay)delay=3000;switch(type){case"error":var icon='<span class="cif-msg-icon cif-msg-icon-error"></span>';break;case"ok":var icon='<span class="cif-msg-icon cif-msg-icon-ok"></span>';break;default:var icon='';}
var popup=this;if($('body').find(popup.wrapper).length<1)popup.open();this.wrapper.append('<div class="cif-msg">'+icon+msg+'</div>');if(typeof(fftimeout)!=='undefined')clearTimeout(fftimeout);if(autoclose)
fftimeout=setTimeout(function(){popup.close();},delay);},close:function(){this.wrapper.find(".cif-msg").remove();this.wrapper.detach();}}}
$.fn.customFile=function(options){return this.each(function(){var element=$(this);var tagName=element[0].tagName.toLowerCase();if(tagName=='input'){var customFile=new CustomFile(this,options);var prop=customFile.form
if(typeof(customFile.form.data("appCustomFile"))!="undefined"){var formData=customFile.form.data("appCustomFile");formData.push(customFile);}else{var formData=new Array(customFile);}
/*
jQuery Custom Input File Plugin - version 1.0
Copyright 2014, Ángel Espro, www.aesolucionesweb.com.ar,
Licence : GNU General Public License
Site: www.aesolucionesweb.com.ar/plugins/custom-input-file
You must not remove these lines. Read gpl.txt for further legal information.
*/
(function($){CustomFile=function(elem,options){this.elem=$(elem);this.itemFileList=[];this.defaults={type:'all',allowed:'all',notAllowed:[],addContainerAfter:$(elem),multiple:true,maxFiles:5,maxMB:0,maxKBperFile:2048,fileWrapper:'<div class="cif-parent"></div>',filePicker:'<h3>Soltar archivos aquí</h3><p>o clic para seleccionar desde carpeta</p><div class="cif-icon-picker"></div>',image:{crop:false,preview:{display:true,maxWidth:300},cropSize:[320,225],minSize:[0,0],maxSize:[0,0]},messages:{errorType:"Tipo de archivo no permitido",errorMaxMB:"Peso máximo de archivos acumulado excedido",errorFileKB:"Archivo muy pesado",errorMaxFiles:"Cantidad máxima de archivos alcanzada",errorBigImage:"Imagen muy grande",errorSmallImage:"Imagen muy pequeña",errorOnReading:"Aplicación ocupada. Inténtelo más tarde.",errorMultipleDisable:"Suelte un archivo por vez."},popup:{active:true,autoclose:true,delay:10000},callbacks:{onComplete:function(app){},beforeRead:function(file){},onSuccess:function(item,callback){},onError:function(file,msg){},beforeRemove:function(item){},}}
this.settings=$.extend(true,{},this.defaults,options);this.status='stop';this.init();}
CustomFile.prototype={init:function(){var attnm=this.elem.attr("name");if(attnm=='')var attnm="inputfile";this.name=(attnm.indexOf("[]",attnm-2)===-1)?attnm+"[]":attnm;this.form=this.elem.parents('form');this.container=$('<div class="cif-file-container cif-container-'+this.settings.type+'-type">');var image=this.settings.image;image.minSize=(typeof(image.minSize)!=='object'||image.minSize.length!==2)?[0,0]:image.minSize;if(image.crop){var minSize=[];for(i=0;i<image.minSize.length;i++){var value=(image.minSize[i]>image.cropSize[i])?image.minSize[i]:image.cropSize[i];minSize.push(value);}
image.minSize=minSize}
this.setFileWrapper();this.appendContainer();this.filePicker=new FilePicker(this);$.customFile.elements.push(this);},onSuccess:function(item,callback){this.itemFileList.push(item);if(this.settings.callbacks.onSuccess(item,callback)===false)return;callback();},onError:function(file,msg){this.settings.callbacks.onError(file,msg);var popupSet=this.settings.popup;if(popupSet.active)
for(k=0;k<msg.length;k++){var fileExt=file.name.substr(file.name.lastIndexOf('.')+1);var fileName=file.name.substr(0,file.name.lastIndexOf('.'));if(fileName.length>42)var fileName=fileName.substr(0,40)+"...";msg[k]+=' ('+fileName+'.'+fileExt+')';$.customFile.popup.add(msg[k],popupSet.autoclose,popupSet.delay,'error');}},onComplete:function(){this.status="completed";if(this.settings.multiple){var response=this.checkMaxFiles()
var popupSet=this.settings.popup;if(response&&popupSet.active)$.customFile.popup.add(response,popupSet.autoclose,popupSet.delay,'ok');}else{if(this.itemFileList.length>1)this.itemFileList[0].destroy();}
this.settings.callbacks.onComplete(this);},read:function(fileList,currentItem){var i=currentItem;if(i+1>fileList.length)this.status='completed';if(this.status==='completed'){this.onComplete();return false;}
var beforeRead=this.settings.callbacks.beforeRead(fileList[i]);if(beforeRead===false)return this.read(fileList,i+1);app=this;var response=app.checkMaxFiles(fileList[i]);if(typeof(response)==='string'){this.onError(fileList[i],[response]);return this.read(fileList,i+1);}
var msg=[];var checklist=["checkFileKB","checkFileType","checkTotalMB"]
for(j=0;j<checklist.length;j++){var response=app[checklist[j]](fileList[i]);if(response)msg.push(response)}
if(msg.length>0){this.onError(fileList[i],msg);return this.read(fileList,i+1);}
new FileItem(this,fileList,i);},appendContainer:function(){var sett=this.settings;if(sett.fileWrapper.parent().length!=0&&sett.appendAfter!=this.elem){sett.addContainerAfter=sett.fileWrapper;}
sett.addContainerAfter.after(this.container);},setFileWrapper:function(){var app=this;var fwr=this.settings.fileWrapper;if(typeof(fwr)==='string')this.settings.fileWrapper=$(fwr);this.settings.fileWrapper=$('<div>',{class:"cif-file-row"}).append(this.settings.fileWrapper);var fwr=this.settings.fileWrapper;fwr.find(':input').each(function(index){var $this=$(this);var attnm=$this.attr("name");if(!attnm)var attnm=app.name.substr(0,app.name.indexOf("[]",-2))+"-"+index;if(attnm.indexOf("[]",-2)===-1){$this.attr("name",attnm+"[]");}});if(fwr.find('.cif-img').length==0&&this.settings.type=='image'){var parent=fwr.find('.cif-parent');if(parent.length===0){var $img=fwr.find('img');var parent=$('<div>',{class:'cif-parent'});parent.append($img);fwr.append(parent);}
if(parent.find('img').length===0)parent.append('<img>')
parent.find('img').addClass("cif-img");}
if(fwr.find('.cif-parent').length==0){fwr.prepend('<div class="cif-parent"></div>');}},checkFileKB:function(file){if(file.size>this.settings.maxKBperFile*1024&&this.settings.maxKBperFile!=0){var msg=this.settings.messages.errorFileKB;}
return msg;},checkFileType:function(file){var ext=file.name.substr(file.name.lastIndexOf('.')+1);var ext=ext.toLowerCase();var imageCropAllowed=["jpeg","jpg","png"]
if((this.settings.type=='image'&&this.settings.image.crop&&imageCropAllowed.indexOf(ext)==-1)||(this.settings.type=='image'&&!file.type.match(/image\//))||(this.settings.allowed!='all'&&this.settings.allowed.indexOf(ext)==-1)||(this.settings.notAllowed.indexOf(ext)!=-1))
{var msg=this.settings.messages.errorType;}
return msg;},checkMaxFiles:function(file){if(this.settings.maxFiles<=this.itemFileList.length&&this.settings.maxFiles){var msg=this.settings.messages.errorMaxFiles;this.filePicker.btn.addClass('inactive');}else{this.filePicker.btn.removeClass('inactive');}
return msg;},checkTotalMB:function(file){var fileSize=(typeof(file)!=='undefined')?file.size:0;var totalSize=0;for(var obj in this.itemFileList){totalSize+=this.itemFileList[obj].file.size;}
if(fileSize+totalSize>this.settings.maxMB*1024*1024&&this.settings.maxMB!=0){var msg=this.settings.messages.errorMaxMB;}
return msg;},checkImageSize:function(img,file){var stt=this.settings.image
if((stt.minSize[0]&&img.width<stt.minSize[0])||(stt.minSize[1]&&img.height<stt.minSize[1])){var msg=this.settings.messages.errorSmallImage;if(stt.minSize[0])msg+=' Ancho mínimo:'+stt.minSize[0]+'px.';if(stt.minSize[1])msg+=' Alto mínimo: '+stt.minSize[1]+'px.';}
if((stt.maxSize[0]&&img.width>stt.maxSize[0])||(stt.maxSize[1]&&img.height>stt.maxSize[1])){var msg=this.settings.messages.errorBigImage;if(stt.maxSize[0])msg+=' Ancho máximo:'+stt.maxSize[0]+'px.';if(stt.maxSize[1])msg+=' Alto máximo: '+stt.maxSize[1]+'px.';}
return msg;},}
FilePicker=function(app){this.btn=$('<div class="cif-file-picker"></div>').append(app.settings.filePicker);this.init(app);}
FilePicker.prototype={init:function(app){var multiple=(app.settings.multiple||app.elem.attr("multiple")=="multiple")?'multiple="multiple"':' ';this.inputHidden=$('<input type="file" '+multiple+'/>');app.elem.after(this.btn);var elem=app.elem.clone();app.elem.detach();app.elem=elem;this.btn.addClass("cif-pkr-"+app.elem.attr("name"));var btn=this.btn;var inputHidden=this.inputHidden;inputHidden.change(function(){var popupSet=app.settings.popup;if(app.status=='reading')return $.customFile.popup.add(app.settings.messages.errorOnReading,popupSet.autoclose,popupSet.delay,'error');$.customFile.popup.close();fileList=$(this)[0].files;app.status='reading';app.read(fileList,0);});btn.on({click:function(){if(!$(this).is('.inactive'))inputHidden.click();return false;},dragover:function(e){e=e||window.event;e.preventDefault();if($(this).is('.inactive'))e.dataTransfer.dropEffect='none';btn.addClass('dragover');return false;},dragleave:function(e){btn.removeClass('dragover');return false;},drop:function(e){e=window.event;e.preventDefault();btn.removeClass('dragover');var popupSet=app.settings.popup;if(app.status=='reading')return $.customFile.popup.add(app.settings.messages.errorOnReading,popupSet.autoclose,popupSet.delay,'error');$.customFile.popup.close();var fileList=e.dataTransfer.files;if(fileList.length>1&&!app.settings.multiple)return $.customFile.popup.add(app.settings.messages.errorMultipleDisable,popupSet.autoclose,popupSet.delay,'error');app.status='reading';app.read(fileList,0);}});},};FileItem=function(app,fileList,currentItem){this.file=fileList[currentItem];this.app=app;this.fileList=fileList;this.currentItem=currentItem;this.init();}
FileItem.prototype={init:function(){this.jcropObj=null;this.node=this.app.settings.fileWrapper.clone();this.img=null;this.btnClose=$('<div class="cif-close" title="Remove">close</div>');this.btnClose.click(function(){fileObj.destroy();});this.fr=new FileReader;var fr=this.fr;var app=this.app;var fileObj=this;var fileList=this.fileList;var currentItem=this.currentItem;var callback=function(){app.onSuccess(fileObj,function(){app.read(fileList,currentItem+1);});delete fileObj.fr;delete fileObj.fileList;delete fileObj.currentItem;}
fr.onload=function(){switch(app.settings.type){case"image":fileObj.readImage(callback);break;default:fileObj.readAllTypes(callback);break;}}
fr.readAsDataURL(this.file);},destroy:function(){this.app.settings.callbacks.beforeRemove(this);if(this.node)this.node.remove();var i=this.app.itemFileList.indexOf(this);this.app.itemFileList.splice(i,1);this.app.checkMaxFiles();},serialize:function(){return $.customFile.serialize([{key:this.app.name,value:this.file}]);},readImage:function(callback){var fileObj=this;var fr=this.fr;var app=this.app;var imgNode=fileObj.node.find("img.cif-img");fileObj.img=new Image;fileObj.img.src=fr.result;fileObj.img.onload=function(){msg=app.checkImageSize(fileObj.img,fileObj.file);if(msg){app.onError(fileObj.file,[msg]);return app.read(fileObj.fileList,fileObj.currentItem+1);}
imgNode.attr("src",fr.result);imgNode.parent().prepend(fileObj.btnClose);app.container.append(fileObj.node);if(app.settings.image.crop===true){fileObj.jcropObj=fileObj.initJcrop(app.settings.image,imgNode.parent(),fileObj.img,app.name);}
callback();}},readAllTypes:function(callback){fileObj=this;var parent=fileObj.node.find('.cif-parent');var FileExt=fileObj.file.name.substr(fileObj.file.name.lastIndexOf('.')+1);var FileName=fileObj.file.name.substr(0,fileObj.file.name.lastIndexOf('.'));if(FileName.length>42)var FileName=FileName.substr(0,40)+"...";var fileSize=(fileObj.file.size<102400)?(fileObj.file.size/1024).toFixed(2):Math.round(fileObj.file.size/1024);parent.append($('<div class="cif-all-type">'+FileName+'.'+FileExt+' <span class="cif-file-size">('+fileSize+'KB)</span><div>')).append(fileObj.btnClose);this.app.container.append(fileObj.node)
callback();},initJcrop:function(options,parent,img,appName){var jcrop_api,boundx,boundy;if(options.preview.display){appName=appName.replace("[]","");prevMaxWidth=options.preview.maxWidth;prevSize=(options.cropSize[0]>prevMaxWidth)?[prevMaxWidth,options.cropSize[1]/options.cropSize[0]*prevMaxWidth]:options.cropSize;parent.append('<div class="preview-pane" style="width:'+prevSize[0]+'px;height:'+prevSize[1]+'px;"><div class="preview-container" style="width:'+prevSize[0]+'px;height:'+prevSize[1]+'px; overflow:hidden"><img src="'+img.src+'" class="jcrop-preview im-prv" /></div></div> '
+'<input type="hidden" class="jcropx" name="'+appName+'-x[]" /><input type="hidden" class="jcropy" name="'+appName+'-y[]" /><input type="hidden" class="jcropw" name="'+appName+'-w[]" /><input type="hidden" class="jcroph" name="'+appName+'-h[]" />');parent.css("min-height",prevSize[1]+20+"px");}
var $preview=parent.find('.preview-pane'),$pcnt=$preview.find('.preview-container'),$pimg=$preview.find('.preview-container img'),xsize=$pcnt.width(),ysize=$pcnt.height();api=parent.find('.cif-img').Jcrop({keySupport:false,onChange:updatePreview,onSelect:updatePreview,aspectRatio:options.cropSize[0]/options.cropSize[1],minSize:options.cropSize,trueSize:[img.width,img.height]},function(){var bounds=this.getBounds();boundx=bounds[0];boundy=bounds[1];jcrop_api=this;jcrop_api.animateTo([0,0,options.cropSize[0]]);$preview.appendTo(jcrop_api.ui.holder);});function updatePreview(c){if(parseInt(c.w)>0&&options.preview.display){var rx=xsize / c.w;var ry=ysize / c.h;$pimg.css({width:Math.round(rx*boundx)+'px',height:Math.round(ry*boundy)+'px',marginLeft:'-'+Math.round(rx*c.x)+'px',marginTop:'-'+Math.round(ry*c.y)+'px'});}
updateCoords(c);};function updateCoords(c){parent.find('.jcropx').val(c.x);parent.find('.jcropy').val(c.y);parent.find('.jcropw').val(c.w);parent.find('.jcroph').val(c.h);}
return jcrop_api;}}
$.customFile={elements:[],getElements:function(selector){var elements=[];var selector=selector.split(",");var el=$.customFile.elements;for(k=0;k<selector.length;k++){selector[k]=selector[k].trim()
for(i=0;i<el.length;i++){if(el[i].name===selector[k]+"[]"||el[i].name===selector[k])
elements.push({type:"pseudoinput",obj:el[i]});if($(selector[k]).is('form')){$(selector[k]).each(function(){elements.push({type:"form",obj:$(this),pseudoChild:(el[i].form[0]===$(this)[0])});});}
if($(selector[k]).is(':input')){$(selector[k]).not(':submit').each(function(){elements.push({type:"input",obj:$(this)});});}}}
var indexToRemove=[]
for(i=0;i<elements.length;i++){if(indexToRemove.indexOf(i)!==-1)continue;for(j=0;j<elements.length;j++){if(j===i||indexToRemove.indexOf(j)!==-1)continue;switch(elements[i].type){case"form":var el=elements[i].obj[0];if(el===elements[j].obj[0]||(elements[j].type==="pseudoinput"&&el==elements[j].obj.form[0])||(elements[j].type==="input"&&el==elements[j].obj.parents('form')[0])){indexToRemove.push(j);}
break;case"input":var el=elements[i].obj[0];if(el===elements[j].obj[0])
indexToRemove.push(j);break;case"pseudoinput":var el=elements[i].obj.name;if(el===elements[j].obj.name||el+"[]"===elements[j].obj.name)
indexToRemove.push(j);break;}}}
var result=[];for(i=0;i<elements.length;i++){if(indexToRemove.indexOf(i)===-1)result.push(elements[i]);}
return result;},serialize:function(elements){formData=null;if(typeof(elements)==='object'){formData=formData||new FormData();if(!elements.length)var elements=[elements]
for(j=0;j<elements.length;j++){if(elements[j].hasOwnProperty("key")&&elements[j].hasOwnProperty("value")){formData.append(elements[j].key,elements[j].value);}}}
if(typeof(elements)==='string'){elements=this.getElements(elements);for(j=0;j<elements.length;j++){formData=formData||new FormData();var elem=elements[j];switch(elem.type){case'pseudoinput':$.each(elem.obj.itemFileList,function(index,element){formData.append(elem.obj.name,element.file);});break;case"form":$.each(elem.obj.find(':input'),function(){if($(this).not(':submit'))
formData.append($(this).attr("name"),$(this).val());});var app=elem.obj.data("appCustomFile");if(typeof(app)=="undefined"){elem.obj.data("appCustomFile",[]);}
$.each(app,function(){appThis=this;$.each(appThis.itemFileList,function(index,element){formData.append(appThis.name,element.file);});});break;case"input":formData.append(elem.obj.attr("name"),elem.obj.val());break;}}}
return formData},ajax:function(el,options){if(typeof(el)==='string'){var element=this.getElements(el)[0];switch(element.type){case"form":var action=element.obj.attr("action");break;case"input":var action=element.obj.parents("form").attr("action");break;case"pseudoinput":var action=element.obj.form.attr("action");break;}
var formData=$.customFile.serialize(el);}
if(typeof(el)==='object'&&el instanceof FileItem){var formData=el.serialize();var action=el.app.form.attr("action");}
var defaults={cache:false,contentType:false,data:formData,processData:false,url:action,type:'POST',progressBar:{active:true,markup:'<div class="cf-progressbar-wr"><div class="cf-progressbar"><span width="0"></span></div></div>',appendTo:$('body'),removeAfterComplete:true,node:null},progress:function(e,total,position,percent){this.progressBar.node.find("span").width(percent+'%');},xhr:function(){var ax=this;var xhr=$.ajaxSettings.xhr();xhr.upload.onprogress=function(e){var e=e||window.event;var position=e.position||e.loaded;var total=e.totalSize||e.total;var percent=((e.loaded/e.total)*100)+"";ax.progress(e,total,position,percent);};xhr.upload.onload=function(){ax.progressBar.node.find("span").width('100%');if(ax.progressBar.removeAfterComplete)
ax.progressBar.node.fadeOut(function(){$(this).remove();});};return xhr;},beforeSend:function(){},complete:function(){},success:function(xml){},}
var settings=$.extend(true,{},defaults,options);if(!settings.progressBar.active)settings.progress=function(){};settings.progressBar.node=$(settings.progressBar.markup);var settBefore=settings.beforeSend;if(settings.progressBar.active){settings.beforeSend=function(){settBefore();settings.progressBar.appendTo.append(settings.progressBar.node);};}
$.ajax(settings);},validate:function(elements,options){elements=this.getElements(elements);for(j=0;j<elements.length;j++){el=elements[j];switch(el.type){case"form":break;case"input":break;case"pseudoinput":break;}}},popup:{wrapper:$('<div id="cif-msg-wr"><div class="cif-msg-close">close</div></div>'),open:function(){var popup=this;this.wrapper.find('.cif-msg-close').click(function(){popup.close()});$('body').append(popup.wrapper);},add:function(msg,autoclose,delay,type){if(!delay)delay=3000;switch(type){case"error":var icon='<span class="cif-msg-icon cif-msg-icon-error"></span>';break;case"ok":var icon='<span class="cif-msg-icon cif-msg-icon-ok"></span>';break;default:var icon='';}
var popup=this;if($('body').find(popup.wrapper).length<1)popup.open();this.wrapper.append('<div class="cif-msg">'+icon+msg+'</div>');if(typeof(fftimeout)!=='undefined')clearTimeout(fftimeout);if(autoclose)
fftimeout=setTimeout(function(){popup.close();},delay);},close:function(){this.wrapper.find(".cif-msg").remove();this.wrapper.detach();}}}
$.fn.customFile=function(options){return this.each(function(){var element=$(this);var tagName=element[0].tagName.toLowerCase();if(tagName=='input'){var customFile=new CustomFile(this,options);var prop=customFile.form
if(typeof(customFile.form.data("appCustomFile"))!="undefined"){var formData=customFile.form.data("appCustomFile");formData.push(customFile);}else{var formData=new Array(customFile);}
customFile.form.data("appCustomFile",formData);}});};})(jQuery);

View File

@@ -1,14 +1,14 @@
// function that receives two hours in hh:mm format and compares as a spaceship operator
export function compareHours(h1, h2) {
const [h1h, h1m] = h1.split(":").map(Number);
const [h2h, h2m] = h2.split(":").map(Number);
if (h1h > h2h)
return 1;
if (h1h < h2h)
return -1;
if (h1m > h2m)
return 1;
if (h1m < h2m)
return -1;
return 0;
}
// function that receives two hours in hh:mm format and compares as a spaceship operator
export function compareHours(h1, h2) {
const [h1h, h1m] = h1.split(":").map(Number);
const [h2h, h2m] = h2.split(":").map(Number);
if (h1h > h2h)
return 1;
if (h1h < h2h)
return -1;
if (h1m > h2m)
return 1;
if (h1m < h2m)
return -1;
return 0;
}

View File

@@ -1,44 +1,44 @@
var submit = function (url, data) {
// create a form
var form = document.createElement('form');
form.method = 'POST';
form.action = url;
form.style.display = 'none';
// add the form data to the form
for (var key in data) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = data[key];
form.appendChild(input);
}
// submit the form
document.body.appendChild(form);
form.submit();
}
var toFormData = function (obj) {
var formData = new FormData();
for (var key in obj) {
formData.append(key, obj[key]);
}
return formData;
}
var fetchPHP = async function (url, data = {}) {
return response = await fetch(
url,
{ method: 'POST', body: toFormData(data) }
)
.then(response => {
try {
return response.json()
}
catch (e) {
var message = 'Error en la respuesta del servidor';
Promise.reject(message)
}
})
.then(response => response.error ? Promise.reject(response.error) : Promise.resolve(response))
var submit = function (url, data) {
// create a form
var form = document.createElement('form');
form.method = 'POST';
form.action = url;
form.style.display = 'none';
// add the form data to the form
for (var key in data) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = data[key];
form.appendChild(input);
}
// submit the form
document.body.appendChild(form);
form.submit();
}
var toFormData = function (obj) {
var formData = new FormData();
for (var key in obj) {
formData.append(key, obj[key]);
}
return formData;
}
var fetchPHP = async function (url, data = {}) {
return response = await fetch(
url,
{ method: 'POST', body: toFormData(data) }
)
.then(response => {
try {
return response.json()
}
catch (e) {
var message = 'Error en la respuesta del servidor';
Promise.reject(message)
}
})
.then(response => response.error ? Promise.reject(response.error) : Promise.resolve(response))
}

View File

@@ -1,414 +1,414 @@
const compareHours = (hora1, hora2) => {
const [h1, m1] = hora1.split(":").map(Number);
const [h2, m2] = hora2.split(":").map(Number);
if (h1 !== h2) {
return h1 > h2 ? 1 : -1;
}
if (m1 !== m2) {
return m1 > m2 ? 1 : -1;
}
return 0;
};
let horarios = [];
const table = document.querySelector("table");
if (!(table instanceof HTMLTableElement)) {
triggerMessage("No se ha encontrado la tabla", "Error", "error");
throw new Error("No se ha encontrado la tabla");
}
[...Array(16).keys()].map(x => x + 7).forEach(hora => {
// add 7 rows for each hour
[0, 15, 30, 45].map((minute) => `${minute}`.padStart(2, '0')).forEach((minute) => {
const tr = document.createElement("tr");
tr.id = `hora-${hora}:${minute}`;
tr.classList.add(hora > 13 ? "tarde" : "mañana");
if (minute == "00") {
const th = document.createElement("th");
th.classList.add("text-center");
th.scope = "row";
th.rowSpan = 4;
th.innerText = `${hora}:00`;
th.style.verticalAlign = "middle";
tr.appendChild(th);
}
["lunes", "martes", "miércoles", "jueves", "viernes", "sábado"].forEach(día => {
const td = document.createElement("td");
td.id = `hora-${hora}:${minute}-${día}`;
tr.appendChild(td);
});
const tbody = document.querySelector("tbody#horario");
if (!(tbody instanceof HTMLTableSectionElement)) {
throw new Error("No se ha encontrado el tbody");
}
tbody.appendChild(tr);
});
});
const empty_table = table.cloneNode(true);
document.querySelectorAll('.hidden').forEach((element) => {
element.style.display = "none";
});
// hide the table
table.style.display = "none";
function moveHorario(id, día, hora) {
const formData = new FormData();
formData.append("id", id);
formData.append("hora", hora);
formData.append("día", día);
fetch("action/action_horario_update.php", {
method: "POST",
body: formData
}).then(res => res.json()).then(response => {
if (response.status == "success") {
triggerMessage("Horario movido", "Éxito", "success");
}
else {
triggerMessage(response.message, "Error");
}
}).then(() => {
renderHorario();
}).catch(err => {
triggerMessage(err, "Error");
});
}
function renderHorario() {
if (horarios.length == 0) {
triggerMessage("Este profesor hay horarios para mostrar", "Error", "info");
table.style.display = "none";
document.querySelectorAll('.hidden').forEach((element) => element.style.display = "none");
return;
}
// show the table
table.style.display = "table";
document.querySelectorAll('.hidden').forEach((element) => element.style.display = "block");
// clear the table
table.innerHTML = empty_table.outerHTML;
function conflicts(horario1, horario2) {
const { hora: hora_inicio1, hora_final: hora_final1, dia: dia1 } = horario1;
const { hora: hora_inicio2, hora_final: hora_final2, dia: dia2 } = horario2;
if (dia1 !== dia2) {
return false;
}
const compareInicios = compareHours(hora_inicio1, hora_inicio2);
const compareFinales = compareHours(hora_final1, hora_final2);
if (compareInicios >= 0 && compareInicios <= compareFinales ||
compareFinales >= 0 && compareFinales <= -compareInicios) {
return true;
}
return false;
}
// remove the next 5 cells
function removeNextCells(horas, minutos, dia, cells = 5) {
for (let i = 1; i <= cells; i++) {
const minute = minutos + i * 15;
const nextMinute = (minute % 60).toString().padStart(2, "0");
const nextHour = horas + Math.floor(minute / 60);
const cellId = `hora-${nextHour}:${nextMinute}-${dia}`;
const cellElement = document.getElementById(cellId);
if (cellElement) {
cellElement.remove();
}
else {
console.log(`No se ha encontrado la celda ${cellId}`);
break;
}
}
}
function newBlock(horario, edit = false) {
function move(horario, cells = 5) {
const [horas, minutos] = horario.hora.split(":").map(Number);
const cell = document.getElementById(`hora-${horas}:${minutos.toString().padStart(2, "0")}-${horario.dia}`);
const { top, left } = cell.getBoundingClientRect();
const block = document.getElementById(`block-${horario.id}`);
block.style.top = `${top}px`;
block.style.left = `${left}px`;
removeNextCells(horas, minutos, horario.dia, cells);
}
const [horas, minutos] = horario.hora.split(":").map(x => parseInt(x));
const hora = `${horas}:${minutos.toString().padStart(2, "0")}`;
horario.hora = hora;
const cell = document.getElementById(`hora-${horario.hora}-${horario.dia}`);
if (!cell)
return;
cell.dataset.ids = `${horario.id}`;
const float_menu = edit ?
`<div class="menu-flotante p-2" style="opacity: .7;">
<a class="mx-2" href="#" data-toggle="modal" data-target="#modal-editar">
<i class="ing-editar ing"></i>
</a>
<a class="mx-2" href="#" data-toggle="modal" data-target="#modal-borrar">
<i class="ing-basura ing"></i>
</a>
</div>`
: '';
cell.innerHTML =
`<div style="overflow-y: auto; overflow-x: hidden; height: 100%;" id="block-${horario.id}" class="position-absolute w-100 h-100">
<small class="text-gray">${horario.hora}</small>
<b class="title">${horario.materia}</b> <br>
<br><span>Salón: </span>${horario.salon} <br>
<small class="my-2">
${horario.profesores.map((profesor) => ` <span class="ing ing-formacion mx-1"></span>${profesor.grado ?? ''} ${profesor.profesor}`).join("<br>")}
</small>
</div>
${float_menu}`;
cell.classList.add("bloque-clase", "position-relative");
cell.rowSpan = horario.bloques;
// draggable
cell.draggable = write;
if (horario.bloques > 0) {
removeNextCells(horas, minutos, horario.dia, horario.bloques - 1);
}
}
function newConflictBlock(horarios, edit = false) {
const first_horario = horarios[0];
const [horas, minutos] = first_horario.hora.split(":").map(x => parseInt(x));
const hora = `${horas}:${minutos.toString().padStart(2, "0")}`;
const ids = horarios.map(horario => horario.id);
const cell = document.getElementById(`hora-${hora}-${first_horario.dia}`);
if (cell == null) {
console.error(`Error: No se encontró la celda: hora-${hora}-${first_horario.dia}`);
return;
}
cell.dataset.ids = ids.join(",");
// replace the content of the cell
cell.innerHTML = `
<small class='text-danger'>
${hora}
</small>
<div class="d-flex justify-content-center align-items-center mt-4">
<div class="d-flex flex-column justify-content-center align-items-center">
<span class="ing ing-importante text-danger" style="font-size: 2rem;"></span>
<b class='text-danger'>
Empalme de ${ids.length} horarios
</b>
<hr>
<i class="text-danger">Ver horarios &#8230;</i>
</div>
</div>
`;
// Add classes and attributes
cell.classList.add("conflict", "bloque-clase");
cell.setAttribute("role", "button");
// Add event listener for the cell
cell.addEventListener("click", () => {
$("#modal-choose").modal("show");
const ids = cell.getAttribute("data-ids").split(",").map(x => parseInt(x));
const tbody = document.querySelector("#modal-choose tbody");
tbody.innerHTML = "";
horarios.filter(horario => ids.includes(horario.id)).sort((a, b) => compareHours(a.hora, b.hora)).forEach(horario => {
tbody.innerHTML += `
<tr data-ids="${horario.id}">
<td><small>${horario.hora.slice(0, -3)}-${horario.hora_final.slice(0, -3)}</small></td>
<td>${horario.materia}</td>
<td>
${horario.profesores.map(({ grado, profesor }) => `${grado ?? ''} ${profesor}`).join(", ")}
</td>
<td>${horario.salon}</td>
${edit ? `
<td class="text-center">
<button class="btn btn-sm btn-primary dismiss-editar" data-toggle="modal" data-target="#modal-editar">
<i class="ing-editar ing"></i>
</button>
</td>
<td class="text-center">
<button class="btn btn-sm btn-danger dismiss-editar" data-toggle="modal" data-target="#modal-borrar">
<i class="ing-basura ing"></i>
</button>
</td>
` : ""}
</tr>`;
});
document.querySelectorAll(".dismiss-editar").forEach(btn => {
btn.addEventListener("click", () => $("#modal-choose").modal("hide"));
});
});
function getDuration(hora_i, hora_f) {
const [horas_i, minutos_i] = hora_i.split(":").map(x => parseInt(x));
const [horas_f, minutos_f] = hora_f.split(":").map(x => parseInt(x));
const date_i = new Date(0, 0, 0, horas_i, minutos_i);
const date_f = new Date(0, 0, 0, horas_f, minutos_f);
const diffInMilliseconds = date_f.getTime() - date_i.getTime();
const diffInMinutes = diffInMilliseconds / (1000 * 60);
const diffIn15MinuteIntervals = diffInMinutes / 15;
return Math.floor(diffIn15MinuteIntervals);
}
const maxHoraFinal = horarios.reduce((max, horario) => {
const [horas, minutos] = horario.hora_final.split(":").map(x => parseInt(x));
const date = new Date(0, 0, 0, horas, minutos);
return date > max ? date : max;
}, new Date(0, 0, 0, 0, 0));
const horaFinalMax = new Date(0, 0, 0, maxHoraFinal.getHours(), maxHoraFinal.getMinutes());
const blocks = getDuration(first_horario.hora, `${horaFinalMax.getHours()}:${horaFinalMax.getMinutes()}`);
cell.setAttribute("rowSpan", blocks.toString());
removeNextCells(horas, minutos, first_horario.dia, blocks - 1);
}
const conflictBlocks = horarios.filter((horario, index, arrayHorario) => arrayHorario.filter((_, i) => i != index).some(horario2 => conflicts(horario, horario2)))
.sort((a, b) => compareHours(a.hora, b.hora));
const classes = horarios.filter(horario => !conflictBlocks.includes(horario));
const conflictBlocksPacked = []; // array of sets
conflictBlocks.forEach(horario => {
const setIndex = conflictBlocksPacked.findIndex(set => set.some(horario2 => conflicts(horario, horario2)));
if (setIndex === -1) {
conflictBlocksPacked.push([horario]);
}
else {
conflictBlocksPacked[setIndex].push(horario);
}
});
classes.forEach(horario => newBlock(horario, write));
conflictBlocksPacked.forEach(horarios => newConflictBlock(horarios, write));
// remove the elements that are not in the limits
let max_hour = Math.max(...horarios.map(horario => {
const lastMoment = moment(horario.hora, "HH:mm").add(horario.bloques * 15, "minutes");
const lastHour = moment(`${lastMoment.hours()}:00`, "HH:mm");
const hourInt = parseInt(lastMoment.format("HH"));
return lastMoment.isSame(lastHour) ? hourInt - 1 : hourInt;
}));
let min_hour = Math.min(...horarios.map(horario => parseInt(horario.hora.split(":")[0])));
document.querySelectorAll("tbody#horario tr").forEach(hora => {
const hora_id = parseInt(hora.id.split("-")[1].split(":")[0]);
(hora_id < min_hour || hora_id > max_hour) ? hora.remove() : null;
});
// if there is no sábado, remove the column
if (!horarios.some(horario => horario.dia == "sábado")) {
document.querySelectorAll("tbody#horario td").forEach(td => {
if (td.id.split("-")[2] == "sábado") {
td.remove();
}
});
// remove the header (the last)
document.querySelector("#headers").lastElementChild.remove();
}
// adjust width
const ths = document.querySelectorAll("tr#headers th");
ths.forEach((th, key) => th.style.width = (key == 0) ? "5%" : `${95 / (ths.length - 1)}%`);
// search item animation
const menúFlontantes = document.querySelectorAll(".menu-flotante");
menúFlontantes.forEach((element) => {
element.classList.add("d-none");
element.parentElement.addEventListener("mouseover", () => element.classList.remove("d-none"));
element.parentElement.addEventListener("mouseout", (e) => element.classList.add("d-none"));
});
// droppables
// forall the .bloque-elements add the event listeners for drag and drop
document.querySelectorAll(".bloque-clase").forEach(element => {
function dragStart() {
this.classList.add("dragging");
}
function dragEnd() {
this.classList.remove("dragging");
}
element.addEventListener("dragstart", dragStart);
element.addEventListener("dragend", dragEnd);
});
// forall the cells that are not .bloque-clase add the event listeners for drag and drop
document.querySelectorAll("td:not(.bloque-clase)").forEach(element => {
function dragOver(e) {
e.preventDefault();
this.classList.add("dragging-over");
}
function dragLeave() {
this.classList.remove("dragging-over");
}
function drop() {
this.classList.remove("dragging-over");
const dragging = document.querySelector(".dragging");
const id = dragging.getAttribute("data-ids");
const hora = this.id.split("-")[1];
const días = ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado"];
let día = this.id.split("-")[2];
día = días.indexOf(día) + 1;
// rowspan
const bloques = parseInt(dragging.getAttribute("rowspan"));
const horaMoment = moment(hora, "HH:mm");
const horaFin = horaMoment.add(bloques * 15, "minutes");
const limit = moment('22:00', 'HH:mm');
if (horaFin.isAfter(limit)) {
triggerMessage("No se puede mover el bloque a esa hora", "Error");
// scroll to the top
window.scrollTo(0, 0);
return;
}
// get the horario
// remove the horario
const bloque = document.querySelector(`.bloque-clase[data-ids="${id}"]`);
// remove all children
while (bloque.firstChild) {
bloque.removeChild(bloque.firstChild);
}
// prepend a loading child
const loading = `<div class="spinner-border" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>`;
bloque.insertAdjacentHTML("afterbegin", loading);
// add style vertical-align: middle
bloque.style.verticalAlign = "middle";
bloque.classList.add("text-center");
// remove draggable
bloque.removeAttribute("draggable");
moveHorario(id, día, hora);
}
element.addEventListener("dragover", dragOver);
element.addEventListener("dragleave", dragLeave);
element.addEventListener("drop", drop);
});
}
const form = document.getElementById('form');
if (!(form instanceof HTMLFormElement)) {
triggerMessage('No se ha encontrado el formulario', 'Error', 'danger');
throw new Error("No se ha encontrado el formulario");
}
form.querySelector('#clave_profesor').addEventListener('input', function (e) {
const input = form.querySelector('#clave_profesor');
const option = form.querySelector(`option[value="${input.value}"]`);
if (input.value == "") {
input.classList.remove("is-invalid", "is-valid");
return;
}
if (!option) {
input.classList.remove("is-valid");
input.classList.add("is-invalid");
}
else {
const profesor_id = form.querySelector('#profesor_id');
profesor_id.value = option.dataset.id;
input.classList.remove("is-invalid");
input.classList.add("is-valid");
}
});
form.addEventListener('submit', async function (e) {
e.preventDefault();
const input = form.querySelector('#clave_profesor');
if (input.classList.contains("is-invalid")) {
triggerMessage('El profesor no se encuentra registrado', 'Error', 'danger');
return;
}
const formData = new FormData(form);
try {
const buttons = document.querySelectorAll("button");
buttons.forEach(button => {
button.disabled = true;
button.classList.add("disabled");
});
const response = await fetch('action/action_horario_profesor.php', {
method: 'POST',
body: formData,
});
const data = await response.json();
buttons.forEach(button => {
button.disabled = false;
button.classList.remove("disabled");
});
if (data.status == 'success') {
horarios = data.data;
renderHorario();
}
else {
triggerMessage(data.message, 'Error en la consulta', 'warning');
}
}
catch (error) {
triggerMessage('Fallo al consutar los datos ', 'Error', 'danger');
console.log(error);
}
});
const input = form.querySelector('#clave_profesor');
const option = form.querySelector(`option[value="${input.value}"]`);
const compareHours = (hora1, hora2) => {
const [h1, m1] = hora1.split(":").map(Number);
const [h2, m2] = hora2.split(":").map(Number);
if (h1 !== h2) {
return h1 > h2 ? 1 : -1;
}
if (m1 !== m2) {
return m1 > m2 ? 1 : -1;
}
return 0;
};
let horarios = [];
const table = document.querySelector("table");
if (!(table instanceof HTMLTableElement)) {
triggerMessage("No se ha encontrado la tabla", "Error", "error");
throw new Error("No se ha encontrado la tabla");
}
[...Array(16).keys()].map(x => x + 7).forEach(hora => {
// add 7 rows for each hour
[0, 15, 30, 45].map((minute) => `${minute}`.padStart(2, '0')).forEach((minute) => {
const tr = document.createElement("tr");
tr.id = `hora-${hora}:${minute}`;
tr.classList.add(hora > 13 ? "tarde" : "mañana");
if (minute == "00") {
const th = document.createElement("th");
th.classList.add("text-center");
th.scope = "row";
th.rowSpan = 4;
th.innerText = `${hora}:00`;
th.style.verticalAlign = "middle";
tr.appendChild(th);
}
["lunes", "martes", "miércoles", "jueves", "viernes", "sábado"].forEach(día => {
const td = document.createElement("td");
td.id = `hora-${hora}:${minute}-${día}`;
tr.appendChild(td);
});
const tbody = document.querySelector("tbody#horario");
if (!(tbody instanceof HTMLTableSectionElement)) {
throw new Error("No se ha encontrado el tbody");
}
tbody.appendChild(tr);
});
});
const empty_table = table.cloneNode(true);
document.querySelectorAll('.hidden').forEach((element) => {
element.style.display = "none";
});
// hide the table
table.style.display = "none";
function moveHorario(id, día, hora) {
const formData = new FormData();
formData.append("id", id);
formData.append("hora", hora);
formData.append("día", día);
fetch("action/action_horario_update.php", {
method: "POST",
body: formData
}).then(res => res.json()).then(response => {
if (response.status == "success") {
triggerMessage("Horario movido", "Éxito", "success");
}
else {
triggerMessage(response.message, "Error");
}
}).then(() => {
renderHorario();
}).catch(err => {
triggerMessage(err, "Error");
});
}
function renderHorario() {
if (horarios.length == 0) {
triggerMessage("Este profesor hay horarios para mostrar", "Error", "info");
table.style.display = "none";
document.querySelectorAll('.hidden').forEach((element) => element.style.display = "none");
return;
}
// show the table
table.style.display = "table";
document.querySelectorAll('.hidden').forEach((element) => element.style.display = "block");
// clear the table
table.innerHTML = empty_table.outerHTML;
function conflicts(horario1, horario2) {
const { hora: hora_inicio1, hora_final: hora_final1, dia: dia1 } = horario1;
const { hora: hora_inicio2, hora_final: hora_final2, dia: dia2 } = horario2;
if (dia1 !== dia2) {
return false;
}
const compareInicios = compareHours(hora_inicio1, hora_inicio2);
const compareFinales = compareHours(hora_final1, hora_final2);
if (compareInicios >= 0 && compareInicios <= compareFinales ||
compareFinales >= 0 && compareFinales <= -compareInicios) {
return true;
}
return false;
}
// remove the next 5 cells
function removeNextCells(horas, minutos, dia, cells = 5) {
for (let i = 1; i <= cells; i++) {
const minute = minutos + i * 15;
const nextMinute = (minute % 60).toString().padStart(2, "0");
const nextHour = horas + Math.floor(minute / 60);
const cellId = `hora-${nextHour}:${nextMinute}-${dia}`;
const cellElement = document.getElementById(cellId);
if (cellElement) {
cellElement.remove();
}
else {
console.log(`No se ha encontrado la celda ${cellId}`);
break;
}
}
}
function newBlock(horario, edit = false) {
function move(horario, cells = 5) {
const [horas, minutos] = horario.hora.split(":").map(Number);
const cell = document.getElementById(`hora-${horas}:${minutos.toString().padStart(2, "0")}-${horario.dia}`);
const { top, left } = cell.getBoundingClientRect();
const block = document.getElementById(`block-${horario.id}`);
block.style.top = `${top}px`;
block.style.left = `${left}px`;
removeNextCells(horas, minutos, horario.dia, cells);
}
const [horas, minutos] = horario.hora.split(":").map(x => parseInt(x));
const hora = `${horas}:${minutos.toString().padStart(2, "0")}`;
horario.hora = hora;
const cell = document.getElementById(`hora-${horario.hora}-${horario.dia}`);
if (!cell)
return;
cell.dataset.ids = `${horario.id}`;
const float_menu = edit ?
`<div class="menu-flotante p-2" style="opacity: .7;">
<a class="mx-2" href="#" data-toggle="modal" data-target="#modal-editar">
<i class="ing-editar ing"></i>
</a>
<a class="mx-2" href="#" data-toggle="modal" data-target="#modal-borrar">
<i class="ing-basura ing"></i>
</a>
</div>`
: '';
cell.innerHTML =
`<div style="overflow-y: auto; overflow-x: hidden; height: 100%;" id="block-${horario.id}" class="position-absolute w-100 h-100">
<small class="text-gray">${horario.hora}</small>
<b class="title">${horario.materia}</b> <br>
<br><span>Salón: </span>${horario.salon} <br>
<small class="my-2">
${horario.profesores.map((profesor) => ` <span class="ing ing-formacion mx-1"></span>${profesor.grado ?? ''} ${profesor.profesor}`).join("<br>")}
</small>
</div>
${float_menu}`;
cell.classList.add("bloque-clase", "position-relative");
cell.rowSpan = horario.bloques;
// draggable
cell.draggable = write;
if (horario.bloques > 0) {
removeNextCells(horas, minutos, horario.dia, horario.bloques - 1);
}
}
function newConflictBlock(horarios, edit = false) {
const first_horario = horarios[0];
const [horas, minutos] = first_horario.hora.split(":").map(x => parseInt(x));
const hora = `${horas}:${minutos.toString().padStart(2, "0")}`;
const ids = horarios.map(horario => horario.id);
const cell = document.getElementById(`hora-${hora}-${first_horario.dia}`);
if (cell == null) {
console.error(`Error: No se encontró la celda: hora-${hora}-${first_horario.dia}`);
return;
}
cell.dataset.ids = ids.join(",");
// replace the content of the cell
cell.innerHTML = `
<small class='text-danger'>
${hora}
</small>
<div class="d-flex justify-content-center align-items-center mt-4">
<div class="d-flex flex-column justify-content-center align-items-center">
<span class="ing ing-importante text-danger" style="font-size: 2rem;"></span>
<b class='text-danger'>
Empalme de ${ids.length} horarios
</b>
<hr>
<i class="text-danger">Ver horarios &#8230;</i>
</div>
</div>
`;
// Add classes and attributes
cell.classList.add("conflict", "bloque-clase");
cell.setAttribute("role", "button");
// Add event listener for the cell
cell.addEventListener("click", () => {
$("#modal-choose").modal("show");
const ids = cell.getAttribute("data-ids").split(",").map(x => parseInt(x));
const tbody = document.querySelector("#modal-choose tbody");
tbody.innerHTML = "";
horarios.filter(horario => ids.includes(horario.id)).sort((a, b) => compareHours(a.hora, b.hora)).forEach(horario => {
tbody.innerHTML += `
<tr data-ids="${horario.id}">
<td><small>${horario.hora.slice(0, -3)}-${horario.hora_final.slice(0, -3)}</small></td>
<td>${horario.materia}</td>
<td>
${horario.profesores.map(({ grado, profesor }) => `${grado ?? ''} ${profesor}`).join(", ")}
</td>
<td>${horario.salon}</td>
${edit ? `
<td class="text-center">
<button class="btn btn-sm btn-primary dismiss-editar" data-toggle="modal" data-target="#modal-editar">
<i class="ing-editar ing"></i>
</button>
</td>
<td class="text-center">
<button class="btn btn-sm btn-danger dismiss-editar" data-toggle="modal" data-target="#modal-borrar">
<i class="ing-basura ing"></i>
</button>
</td>
` : ""}
</tr>`;
});
document.querySelectorAll(".dismiss-editar").forEach(btn => {
btn.addEventListener("click", () => $("#modal-choose").modal("hide"));
});
});
function getDuration(hora_i, hora_f) {
const [horas_i, minutos_i] = hora_i.split(":").map(x => parseInt(x));
const [horas_f, minutos_f] = hora_f.split(":").map(x => parseInt(x));
const date_i = new Date(0, 0, 0, horas_i, minutos_i);
const date_f = new Date(0, 0, 0, horas_f, minutos_f);
const diffInMilliseconds = date_f.getTime() - date_i.getTime();
const diffInMinutes = diffInMilliseconds / (1000 * 60);
const diffIn15MinuteIntervals = diffInMinutes / 15;
return Math.floor(diffIn15MinuteIntervals);
}
const maxHoraFinal = horarios.reduce((max, horario) => {
const [horas, minutos] = horario.hora_final.split(":").map(x => parseInt(x));
const date = new Date(0, 0, 0, horas, minutos);
return date > max ? date : max;
}, new Date(0, 0, 0, 0, 0));
const horaFinalMax = new Date(0, 0, 0, maxHoraFinal.getHours(), maxHoraFinal.getMinutes());
const blocks = getDuration(first_horario.hora, `${horaFinalMax.getHours()}:${horaFinalMax.getMinutes()}`);
cell.setAttribute("rowSpan", blocks.toString());
removeNextCells(horas, minutos, first_horario.dia, blocks - 1);
}
const conflictBlocks = horarios.filter((horario, index, arrayHorario) => arrayHorario.filter((_, i) => i != index).some(horario2 => conflicts(horario, horario2)))
.sort((a, b) => compareHours(a.hora, b.hora));
const classes = horarios.filter(horario => !conflictBlocks.includes(horario));
const conflictBlocksPacked = []; // array of sets
conflictBlocks.forEach(horario => {
const setIndex = conflictBlocksPacked.findIndex(set => set.some(horario2 => conflicts(horario, horario2)));
if (setIndex === -1) {
conflictBlocksPacked.push([horario]);
}
else {
conflictBlocksPacked[setIndex].push(horario);
}
});
classes.forEach(horario => newBlock(horario, write));
conflictBlocksPacked.forEach(horarios => newConflictBlock(horarios, write));
// remove the elements that are not in the limits
let max_hour = Math.max(...horarios.map(horario => {
const lastMoment = moment(horario.hora, "HH:mm").add(horario.bloques * 15, "minutes");
const lastHour = moment(`${lastMoment.hours()}:00`, "HH:mm");
const hourInt = parseInt(lastMoment.format("HH"));
return lastMoment.isSame(lastHour) ? hourInt - 1 : hourInt;
}));
let min_hour = Math.min(...horarios.map(horario => parseInt(horario.hora.split(":")[0])));
document.querySelectorAll("tbody#horario tr").forEach(hora => {
const hora_id = parseInt(hora.id.split("-")[1].split(":")[0]);
(hora_id < min_hour || hora_id > max_hour) ? hora.remove() : null;
});
// if there is no sábado, remove the column
if (!horarios.some(horario => horario.dia == "sábado")) {
document.querySelectorAll("tbody#horario td").forEach(td => {
if (td.id.split("-")[2] == "sábado") {
td.remove();
}
});
// remove the header (the last)
document.querySelector("#headers").lastElementChild.remove();
}
// adjust width
const ths = document.querySelectorAll("tr#headers th");
ths.forEach((th, key) => th.style.width = (key == 0) ? "5%" : `${95 / (ths.length - 1)}%`);
// search item animation
const menúFlontantes = document.querySelectorAll(".menu-flotante");
menúFlontantes.forEach((element) => {
element.classList.add("d-none");
element.parentElement.addEventListener("mouseover", () => element.classList.remove("d-none"));
element.parentElement.addEventListener("mouseout", (e) => element.classList.add("d-none"));
});
// droppables
// forall the .bloque-elements add the event listeners for drag and drop
document.querySelectorAll(".bloque-clase").forEach(element => {
function dragStart() {
this.classList.add("dragging");
}
function dragEnd() {
this.classList.remove("dragging");
}
element.addEventListener("dragstart", dragStart);
element.addEventListener("dragend", dragEnd);
});
// forall the cells that are not .bloque-clase add the event listeners for drag and drop
document.querySelectorAll("td:not(.bloque-clase)").forEach(element => {
function dragOver(e) {
e.preventDefault();
this.classList.add("dragging-over");
}
function dragLeave() {
this.classList.remove("dragging-over");
}
function drop() {
this.classList.remove("dragging-over");
const dragging = document.querySelector(".dragging");
const id = dragging.getAttribute("data-ids");
const hora = this.id.split("-")[1];
const días = ["lunes", "martes", "miércoles", "jueves", "viernes", "sábado"];
let día = this.id.split("-")[2];
día = días.indexOf(día) + 1;
// rowspan
const bloques = parseInt(dragging.getAttribute("rowspan"));
const horaMoment = moment(hora, "HH:mm");
const horaFin = horaMoment.add(bloques * 15, "minutes");
const limit = moment('22:00', 'HH:mm');
if (horaFin.isAfter(limit)) {
triggerMessage("No se puede mover el bloque a esa hora", "Error");
// scroll to the top
window.scrollTo(0, 0);
return;
}
// get the horario
// remove the horario
const bloque = document.querySelector(`.bloque-clase[data-ids="${id}"]`);
// remove all children
while (bloque.firstChild) {
bloque.removeChild(bloque.firstChild);
}
// prepend a loading child
const loading = `<div class="spinner-border" role="status" style="width: 3rem; height: 3rem;">
<span class="sr-only">Loading...</span>
</div>`;
bloque.insertAdjacentHTML("afterbegin", loading);
// add style vertical-align: middle
bloque.style.verticalAlign = "middle";
bloque.classList.add("text-center");
// remove draggable
bloque.removeAttribute("draggable");
moveHorario(id, día, hora);
}
element.addEventListener("dragover", dragOver);
element.addEventListener("dragleave", dragLeave);
element.addEventListener("drop", drop);
});
}
const form = document.getElementById('form');
if (!(form instanceof HTMLFormElement)) {
triggerMessage('No se ha encontrado el formulario', 'Error', 'danger');
throw new Error("No se ha encontrado el formulario");
}
form.querySelector('#clave_profesor').addEventListener('input', function (e) {
const input = form.querySelector('#clave_profesor');
const option = form.querySelector(`option[value="${input.value}"]`);
if (input.value == "") {
input.classList.remove("is-invalid", "is-valid");
return;
}
if (!option) {
input.classList.remove("is-valid");
input.classList.add("is-invalid");
}
else {
const profesor_id = form.querySelector('#profesor_id');
profesor_id.value = option.dataset.id;
input.classList.remove("is-invalid");
input.classList.add("is-valid");
}
});
form.addEventListener('submit', async function (e) {
e.preventDefault();
const input = form.querySelector('#clave_profesor');
if (input.classList.contains("is-invalid")) {
triggerMessage('El profesor no se encuentra registrado', 'Error', 'danger');
return;
}
const formData = new FormData(form);
try {
const buttons = document.querySelectorAll("button");
buttons.forEach(button => {
button.disabled = true;
button.classList.add("disabled");
});
const response = await fetch('action/action_horario_profesor.php', {
method: 'POST',
body: formData,
});
const data = await response.json();
buttons.forEach(button => {
button.disabled = false;
button.classList.remove("disabled");
});
if (data.status == 'success') {
horarios = data.data;
renderHorario();
}
else {
triggerMessage(data.message, 'Error en la consulta', 'warning');
}
}
catch (error) {
triggerMessage('Fallo al consutar los datos ', 'Error', 'danger');
console.log(error);
}
});
const input = form.querySelector('#clave_profesor');
const option = form.querySelector(`option[value="${input.value}"]`);

View File

@@ -1,11 +1,11 @@
/*!
* jQuery UI Touch Punch 0.2.3
*
* Copyright 20112014, Dave Furfero
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Depends:
* jquery.ui.widget.js
* jquery.ui.mouse.js
*/
/*!
* jQuery UI Touch Punch 0.2.3
*
* Copyright 20112014, Dave Furfero
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Depends:
* jquery.ui.widget.js
* jquery.ui.mouse.js
*/
!function (a) { function f(a, b) { if (!(a.originalEvent.touches.length > 1)) { a.preventDefault(); var c = a.originalEvent.changedTouches[0], d = document.createEvent("MouseEvents"); d.initMouseEvent(b, !0, !0, window, 1, c.screenX, c.screenY, c.clientX, c.clientY, !1, !1, !1, !1, 0, null), a.target.dispatchEvent(d) } } if (a.support.touch = "ontouchend" in document, a.support.touch) { var e, b = a.ui.mouse.prototype, c = b._mouseInit, d = b._mouseDestroy; b._touchStart = function (a) { var b = this; !e && b._mouseCapture(a.originalEvent.changedTouches[0]) && (e = !0, b._touchMoved = !1, f(a, "mouseover"), f(a, "mousemove"), f(a, "mousedown")) }, b._touchMove = function (a) { e && (this._touchMoved = !0, f(a, "mousemove")) }, b._touchEnd = function (a) { e && (f(a, "mouseup"), f(a, "mouseout"), this._touchMoved || f(a, "click"), e = !1) }, b._mouseInit = function () { var b = this; b.element.bind({ touchstart: a.proxy(b, "_touchStart"), touchmove: a.proxy(b, "_touchMove"), touchend: a.proxy(b, "_touchEnd") }), c.call(b) }, b._mouseDestroy = function () { var b = this; b.element.unbind({ touchstart: a.proxy(b, "_touchStart"), touchmove: a.proxy(b, "_touchMove"), touchend: a.proxy(b, "_touchEnd") }), d.call(b) } } }(jQuery);

View File

@@ -1,36 +1,36 @@
function triggerMessage(message, header, color = "danger", selector = "message") {
const container = document.getElementById(selector);
container.innerHTML = '';
/* Template message_tmp */
var node = /* html */`
<article class="alert alert-${color} alert-dismissible fade show" role="alert" id="alert-color">
<h4 class="alert-heading"><span class="ing-${(color !== 'success') ? 'importante' : 'aceptar'}"></span> ${header}</h4>
<span id="message-alert">${message}</span>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</article>
`
setTimeout(function () {
container.innerHTML = node;
}, 100);
/* setTimeout(function () {
container.innerHTML = '';
}, 5000); */
}
function messageMissingInputs(required) {
var message = 'Faltan los siguientes campos: ';
required.forEach(function (item, index) {
let last = required.length - 1;
if (index == last)
message += item;
else if (index == last - 1)
message += item + ' y ';
else
message += item + ', ';
});
triggerMessage(message, 'Error', 'danger');
function triggerMessage(message, header, color = "danger", selector = "message") {
const container = document.getElementById(selector);
container.innerHTML = '';
/* Template message_tmp */
var node = /* html */`
<article class="alert alert-${color} alert-dismissible fade show" role="alert" id="alert-color">
<h4 class="alert-heading"><span class="ing-${(color !== 'success') ? 'importante' : 'aceptar'}"></span> ${header}</h4>
<span id="message-alert">${message}</span>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</article>
`
setTimeout(function () {
container.innerHTML = node;
}, 100);
/* setTimeout(function () {
container.innerHTML = '';
}, 5000); */
}
function messageMissingInputs(required) {
var message = 'Faltan los siguientes campos: ';
required.forEach(function (item, index) {
let last = required.length - 1;
if (index == last)
message += item;
else if (index == last - 1)
message += item + ' y ';
else
message += item + ', ';
});
triggerMessage(message, 'Error', 'danger');
}

View File

@@ -1,39 +1,39 @@
<script>
function triggerMessage(message, header, color = "danger", selector = "message") {
const container = document.getElementById(selector);
let logo;
container.innerHTML = '';
/* Template message_tmp */
var node = /* html */`
<article class="alert alert-${color} alert-dismissible fade show" role="alert" id="alert-color">
<h4 class="alert-heading"><span class="ing-${(color !== 'success') ? 'importante' : 'aceptar'}"></span> ${header}</h4>
<span id="message-alert">${message}</span>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</article>
`
setTimeout(function() {
container.innerHTML = node;
}, 100);
/* setTimeout(function() {
container.innerHTML = '';
}, 5000); */
}
function messageMissingInputs(required) {
var message = 'Faltan los siguientes campos: ';
required.forEach(function(item, index) {
let last = required.length - 1;
if (index == last)
message += item;
else if (index == last - 1)
message += item + ' y ';
else
message += item + ', ';
});
triggerMessage(message, 'Error', 'danger');
}
<script>
function triggerMessage(message, header, color = "danger", selector = "message") {
const container = document.getElementById(selector);
let logo;
container.innerHTML = '';
/* Template message_tmp */
var node = /* html */`
<article class="alert alert-${color} alert-dismissible fade show" role="alert" id="alert-color">
<h4 class="alert-heading"><span class="ing-${(color !== 'success') ? 'importante' : 'aceptar'}"></span> ${header}</h4>
<span id="message-alert">${message}</span>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</article>
`
setTimeout(function() {
container.innerHTML = node;
}, 100);
/* setTimeout(function() {
container.innerHTML = '';
}, 5000); */
}
function messageMissingInputs(required) {
var message = 'Faltan los siguientes campos: ';
required.forEach(function(item, index) {
let last = required.length - 1;
if (index == last)
message += item;
else if (index == last - 1)
message += item + ' y ';
else
message += item + ', ';
});
triggerMessage(message, 'Error', 'danger');
}
</script>

File diff suppressed because one or more lines are too long

View File

@@ -1,178 +1,178 @@
// Get references to the HTML elements
const form = document.getElementById('form');
const steps = Array.from(form.querySelectorAll('.step'));
const nextButton = document.getElementById('next-button');
const prevButton = document.getElementById('prev-button');
let currentStep = 0;
// #clave_profesor on change => show step 2
const clave_profesor = document.getElementById('clave_profesor');
const horario_reponer = document.getElementById('horario_reponer');
const fechas_clase = document.getElementById('fechas_clase');
const fecha_reponer = $('#fecha_reponer');
const hora_reponer = $('#hora_reponer');
const minutos_reponer = $('#minutos_reponer');
clave_profesor.addEventListener('change', async () => {
const step2 = document.getElementById('step-2');
clave_profesor.disabled = true;
// get option which value is the same as clave_profesor.value
const option = document.querySelector(`option[value="${clave_profesor.value}"]`);
// make a form data with #form
const profesor_id = document.getElementById('profesor_id');
profesor_id.value = option.dataset.id;
const formData = new FormData(form);
const response = await fetch(`./action/action_horario_profesor.php`, {
method: 'POST',
body: formData
});
const data = await response.json();
if (data['success'] === false) {
const message = "Hubo un error al obtener los horarios del profesor.";
const title = 'Error';
const color = 'danger';
triggerMessage(message, title, color);
return;
}
const horarios = data.data;
const initial = document.createElement('option');
initial.value = '';
initial.textContent = 'Seleccione un horario';
initial.selected = true;
initial.disabled = true;
horario_reponer.innerHTML = '';
horario_reponer.appendChild(initial);
horarios.forEach((horario) => {
const dias = ['Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado', 'Domingo'];
const option = document.createElement('option');
option.value = `${horario.id}`;
// materia máx 25 caracteres, if materia.length > 25 then slice(0, 20)
const max = 25;
option.textContent = `${horario.materia.slice(0, max) + (horario.materia.length > max ? '...' : '')} - Grupo: ${horario.grupo} - ${horario.hora.slice(0, 5)}-${horario.hora_final.slice(0, 5)} - Salon: ${horario.salon} - ${horario.dia}`;
option.dataset.materia = `${horario.materia}`;
option.dataset.grupo = `${horario.grupo}`;
option.dataset.hora = `${horario.hora.slice(0, 5)}`; // slice(0, 5) => HH:MM
option.dataset.hora_final = `${horario.hora_final.slice(0, 5)}`;
option.dataset.salon = `${horario.salon}`;
option.dataset.dia = `${horario.dia}`;
option.dataset.id = `${horario.id}`;
horario_reponer.appendChild(option);
});
currentStep = 1;
step2.style.display = 'block';
prevButton.disabled = false;
});
// disable clave_profesor
// from second step to first step
prevButton.addEventListener('click', () => {
const inputs = [clave_profesor, horario_reponer, fechas_clase, fecha_reponer, hora_reponer];
switch (currentStep) {
case 1:
case 2:
case 3:
const step = document.getElementById(`step-${currentStep + 1}`);
step.style.display = 'none';
inputs[currentStep - 1].disabled = false;
inputs[currentStep - 1].value = '';
if (--currentStep === 0) {
prevButton.disabled = true;
}
break;
case 4:
const step5 = document.getElementById('step-5');
step5.style.display = 'none';
fecha_reponer.prop('disabled', false);
fecha_reponer.val('');
hora_reponer.parent().removeClass('disabled');
hora_reponer.siblings('.datalist-input').text('hh');
hora_reponer.val('');
minutos_reponer.parent().removeClass('disabled');
minutos_reponer.siblings('.datalist-input').text('mm');
minutos_reponer.val('');
currentStep--;
break;
}
nextButton.disabled = true;
});
// #horario_reponer on change => show step 3
horario_reponer.addEventListener('change', async () => {
const selected = horario_reponer.querySelector(`option[value="${horario_reponer.value}"]`);
horario_reponer.title = `Materia: ${selected.dataset.materia} - Grupo: ${selected.dataset.grupo} - Horario: ${selected.dataset.hora}-${selected.dataset.hora_final} - Salon: ${selected.dataset.salon} - Día: ${selected.dataset.dia}`;
const step3 = document.getElementById('step-3');
horario_reponer.disabled = true;
// make a form data with #form
const response = await fetch(`./action/action_fechas_clase.php?horario_id=${horario_reponer.value}`, {
method: 'GET',
});
const data = await response.json();
if (data['success'] === false) {
const message = "Hubo un error al obtener las fechas de clase.";
const title = 'Error';
const color = 'danger';
triggerMessage(message, title, color);
return;
}
const meses = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
const fechas = data.data;
const initial = document.createElement('option');
initial.value = '';
initial.textContent = 'Seleccione la fecha de la falta';
initial.selected = true;
initial.disabled = true;
fechas_clase.innerHTML = '';
fechas_clase.appendChild(initial);
fechas_clase.title = 'Seleccione la fecha de la falta';
fechas.forEach((fecha) => {
const option = document.createElement('option');
option.value = `${fecha}`;
option.textContent = `${fecha.dia_mes} de ${meses[fecha.month - 1]} de ${fecha.year}`;
fechas_clase.appendChild(option);
});
step3.style.display = 'block';
currentStep = 2;
});
// #fechas_clase on change => show step 4
fechas_clase.addEventListener('change', () => {
const step4 = document.getElementById('step-4');
step4.style.display = 'block';
fechas_clase.disabled = true;
currentStep = 3;
});
// when both #fecha_reponer and #hora_reponer are selected => show step 5
const lastStep = () => {
// timeout to wait for the value to be set
setTimeout(() => {
if (fecha_reponer.val() !== '' && hora_reponer.val() !== '' && minutos_reponer.val() !== '') {
const step5 = document.getElementById('step-5');
step5.style.display = 'block';
// disable both
fecha_reponer.prop('disabled', true);
hora_reponer.parent().addClass('disabled');
minutos_reponer.parent().addClass('disabled');
const nextButton = document.getElementById('next-button');
// remove property disabled
nextButton.removeAttribute('disabled');
currentStep = 4;
}
}, 100);
};
fecha_reponer.on('change', lastStep);
// on click on the sibling ul>li of #hora_reponer and #minutos_reponer
hora_reponer.siblings('ul').children('li').on('click', lastStep);
minutos_reponer.siblings('ul').children('li').on('click', lastStep);
// Initialize the form
hideSteps();
showCurrentStep();
function hideSteps() {
steps.forEach((step) => {
step.style.display = 'none';
});
}
function showCurrentStep() {
steps[currentStep].style.display = 'block';
prevButton.disabled = currentStep === 0;
}
function handleSubmit(event) {
event.preventDefault();
// Handle form submission
// You can access the form data using the FormData API or serialize it manually
}
export {};
// Get references to the HTML elements
const form = document.getElementById('form');
const steps = Array.from(form.querySelectorAll('.step'));
const nextButton = document.getElementById('next-button');
const prevButton = document.getElementById('prev-button');
let currentStep = 0;
// #clave_profesor on change => show step 2
const clave_profesor = document.getElementById('clave_profesor');
const horario_reponer = document.getElementById('horario_reponer');
const fechas_clase = document.getElementById('fechas_clase');
const fecha_reponer = $('#fecha_reponer');
const hora_reponer = $('#hora_reponer');
const minutos_reponer = $('#minutos_reponer');
clave_profesor.addEventListener('change', async () => {
const step2 = document.getElementById('step-2');
clave_profesor.disabled = true;
// get option which value is the same as clave_profesor.value
const option = document.querySelector(`option[value="${clave_profesor.value}"]`);
// make a form data with #form
const profesor_id = document.getElementById('profesor_id');
profesor_id.value = option.dataset.id;
const formData = new FormData(form);
const response = await fetch(`./action/action_horario_profesor.php`, {
method: 'POST',
body: formData
});
const data = await response.json();
if (data['success'] === false) {
const message = "Hubo un error al obtener los horarios del profesor.";
const title = 'Error';
const color = 'danger';
triggerMessage(message, title, color);
return;
}
const horarios = data.data;
const initial = document.createElement('option');
initial.value = '';
initial.textContent = 'Seleccione un horario';
initial.selected = true;
initial.disabled = true;
horario_reponer.innerHTML = '';
horario_reponer.appendChild(initial);
horarios.forEach((horario) => {
const dias = ['Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado', 'Domingo'];
const option = document.createElement('option');
option.value = `${horario.id}`;
// materia máx 25 caracteres, if materia.length > 25 then slice(0, 20)
const max = 25;
option.textContent = `${horario.materia.slice(0, max) + (horario.materia.length > max ? '...' : '')} - Grupo: ${horario.grupo} - ${horario.hora.slice(0, 5)}-${horario.hora_final.slice(0, 5)} - Salon: ${horario.salon} - ${horario.dia}`;
option.dataset.materia = `${horario.materia}`;
option.dataset.grupo = `${horario.grupo}`;
option.dataset.hora = `${horario.hora.slice(0, 5)}`; // slice(0, 5) => HH:MM
option.dataset.hora_final = `${horario.hora_final.slice(0, 5)}`;
option.dataset.salon = `${horario.salon}`;
option.dataset.dia = `${horario.dia}`;
option.dataset.id = `${horario.id}`;
horario_reponer.appendChild(option);
});
currentStep = 1;
step2.style.display = 'block';
prevButton.disabled = false;
});
// disable clave_profesor
// from second step to first step
prevButton.addEventListener('click', () => {
const inputs = [clave_profesor, horario_reponer, fechas_clase, fecha_reponer, hora_reponer];
switch (currentStep) {
case 1:
case 2:
case 3:
const step = document.getElementById(`step-${currentStep + 1}`);
step.style.display = 'none';
inputs[currentStep - 1].disabled = false;
inputs[currentStep - 1].value = '';
if (--currentStep === 0) {
prevButton.disabled = true;
}
break;
case 4:
const step5 = document.getElementById('step-5');
step5.style.display = 'none';
fecha_reponer.prop('disabled', false);
fecha_reponer.val('');
hora_reponer.parent().removeClass('disabled');
hora_reponer.siblings('.datalist-input').text('hh');
hora_reponer.val('');
minutos_reponer.parent().removeClass('disabled');
minutos_reponer.siblings('.datalist-input').text('mm');
minutos_reponer.val('');
currentStep--;
break;
}
nextButton.disabled = true;
});
// #horario_reponer on change => show step 3
horario_reponer.addEventListener('change', async () => {
const selected = horario_reponer.querySelector(`option[value="${horario_reponer.value}"]`);
horario_reponer.title = `Materia: ${selected.dataset.materia} - Grupo: ${selected.dataset.grupo} - Horario: ${selected.dataset.hora}-${selected.dataset.hora_final} - Salon: ${selected.dataset.salon} - Día: ${selected.dataset.dia}`;
const step3 = document.getElementById('step-3');
horario_reponer.disabled = true;
// make a form data with #form
const response = await fetch(`./action/action_fechas_clase.php?horario_id=${horario_reponer.value}`, {
method: 'GET',
});
const data = await response.json();
if (data['success'] === false) {
const message = "Hubo un error al obtener las fechas de clase.";
const title = 'Error';
const color = 'danger';
triggerMessage(message, title, color);
return;
}
const meses = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
const fechas = data.data;
const initial = document.createElement('option');
initial.value = '';
initial.textContent = 'Seleccione la fecha de la falta';
initial.selected = true;
initial.disabled = true;
fechas_clase.innerHTML = '';
fechas_clase.appendChild(initial);
fechas_clase.title = 'Seleccione la fecha de la falta';
fechas.forEach((fecha) => {
const option = document.createElement('option');
option.value = `${fecha}`;
option.textContent = `${fecha.dia_mes} de ${meses[fecha.month - 1]} de ${fecha.year}`;
fechas_clase.appendChild(option);
});
step3.style.display = 'block';
currentStep = 2;
});
// #fechas_clase on change => show step 4
fechas_clase.addEventListener('change', () => {
const step4 = document.getElementById('step-4');
step4.style.display = 'block';
fechas_clase.disabled = true;
currentStep = 3;
});
// when both #fecha_reponer and #hora_reponer are selected => show step 5
const lastStep = () => {
// timeout to wait for the value to be set
setTimeout(() => {
if (fecha_reponer.val() !== '' && hora_reponer.val() !== '' && minutos_reponer.val() !== '') {
const step5 = document.getElementById('step-5');
step5.style.display = 'block';
// disable both
fecha_reponer.prop('disabled', true);
hora_reponer.parent().addClass('disabled');
minutos_reponer.parent().addClass('disabled');
const nextButton = document.getElementById('next-button');
// remove property disabled
nextButton.removeAttribute('disabled');
currentStep = 4;
}
}, 100);
};
fecha_reponer.on('change', lastStep);
// on click on the sibling ul>li of #hora_reponer and #minutos_reponer
hora_reponer.siblings('ul').children('li').on('click', lastStep);
minutos_reponer.siblings('ul').children('li').on('click', lastStep);
// Initialize the form
hideSteps();
showCurrentStep();
function hideSteps() {
steps.forEach((step) => {
step.style.display = 'none';
});
}
function showCurrentStep() {
steps[currentStep].style.display = 'block';
prevButton.disabled = currentStep === 0;
}
function handleSubmit(event) {
event.preventDefault();
// Handle form submission
// You can access the form data using the FormData API or serialize it manually
}
export {};

View File

@@ -1,31 +1,31 @@
const scrollButtons = `
<a href="#up" id="scroll-up" class="btn btn-primary btn-sm" role="button" aria-pressed="true" style="display: sticky; position: fixed; bottom: 3rem; right: 1rem;">
<span class="ing-caret ing-rotate-180 ing-fw"></span>
</a>
<a href="#down" id="scroll-down" class="btn btn-primary btn-sm" role="button" aria-pressed="true" style="display: sticky; position: fixed; bottom: 1rem; right: 1rem;">
<span class="ing-caret ing-fw"></span>
</a>
`
document.body.insertAdjacentHTML('beforeend', scrollButtons);
const scroll_up = document.querySelector('#scroll-up');
const scroll_down = document.querySelector('#scroll-down');
scroll_up.style.transition = scroll_down.style.transition = 'display 1.5s ease-in-out';
scroll_up.style.display = scroll_down.style.display = 'none';
scroll_up.addEventListener('click', () =>
window.scrollTo({ top: 0, behavior: 'smooth' }))
scroll_down.addEventListener('click', () =>
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' }))
const check = () => {
scroll_down.style.display = (window.scrollY + window.innerHeight) > document.body.scrollHeight * .8 ? 'none' : 'block'
scroll_up.style.display = (window.scrollY) < document.body.scrollHeight * .2 ? 'none' : 'block'
}
['scroll', 'resize'].forEach(e => window.addEventListener(e, check))
const scrollButtons = `
<a href="#up" id="scroll-up" class="btn btn-primary btn-sm" role="button" aria-pressed="true" style="display: sticky; position: fixed; bottom: 3rem; right: 1rem;">
<span class="ing-caret ing-rotate-180 ing-fw"></span>
</a>
<a href="#down" id="scroll-down" class="btn btn-primary btn-sm" role="button" aria-pressed="true" style="display: sticky; position: fixed; bottom: 1rem; right: 1rem;">
<span class="ing-caret ing-fw"></span>
</a>
`
document.body.insertAdjacentHTML('beforeend', scrollButtons);
const scroll_up = document.querySelector('#scroll-up');
const scroll_down = document.querySelector('#scroll-down');
scroll_up.style.transition = scroll_down.style.transition = 'display 1.5s ease-in-out';
scroll_up.style.display = scroll_down.style.display = 'none';
scroll_up.addEventListener('click', () =>
window.scrollTo({ top: 0, behavior: 'smooth' }))
scroll_down.addEventListener('click', () =>
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' }))
const check = () => {
scroll_down.style.display = (window.scrollY + window.innerHeight) > document.body.scrollHeight * .8 ? 'none' : 'block'
scroll_up.style.display = (window.scrollY) < document.body.scrollHeight * .2 ? 'none' : 'block'
}
['scroll', 'resize'].forEach(e => window.addEventListener(e, check))

View File

@@ -1,65 +1,65 @@
$(".date-picker").datepicker($.datepicker.regional["es"]);
$(".date-picker").datepicker({
dateFormat: "dd/mm/yyyy",
changeMonth: true,
});
$("#fecha_inicial").datepicker("option", "minDate", fecha_inicial);
$("#fecha_inicial").datepicker("option", "maxDate", limit);
$("#fecha_final").datepicker("option", "minDate", fecha_inicial);
$("#fecha_final").datepicker("option", "maxDate", limit);
var today = new Date();
var fecha_inicial = new Date(<?= isset($fecha_inicial) ? $fecha_inicial->format("Y, m-1, d") : date("Y, m-1, d", strtotime($periodo['inicio'])) ?>);
var fecha_final = new Date(<?= isset($fecha_final) ? $fecha_final->format("Y, m-1, d") : date("Y, m-1, d", strtotime($periodo['fin'])) ?>);
var limit = new Date(Math.min(today, fecha_final));
// if today is in the period, set the initial date to today
$("#fecha_inicial").datepicker("setDate", fecha_inicial);
$("#fecha_final").datepicker("setDate", today <= fecha_final ? today : fecha_final);
function reset_form() {
$("#fecha_inicial").datepicker("setDate", fecha_inicial);
$("#fecha_final").datepicker("setDate", today <= fecha_final ? today : fecha_final);
$("#dlcarrera").find("li").removeClass("selected");
$("#dlcarrera").find("li[data-value='0']").addClass("selected");
$("#dlmateria").find("li").removeClass("selected");
$("#dlmateria").find("li[data-value='0']").addClass("selected");
$("#filter_carrera").val("");
$("#filter_materia").val("");
console.log(`Todos los campos han sido limpiados.`);
}
<?php if (empty($carrera)) { ?>
disableDatalist("#filter_materia", true);
<?php } ?>
reset_form();
// $("#fecha_inicial").on("change", function() {
// var fecha_inicial = $("#fecha_inicial").datepicker("getDate");
// var fecha_final = $("#fecha_final").datepicker("getDate");
// if (fecha_final < fecha_inicial) {
// $("#fecha_final").datepicker("setDate", fecha_inicial);
// }
// $("#fecha_final").datepicker("option", "minDate", fecha_inicial);
// });
// $("#fecha_final").on("change", function() {
// var fecha_inicial = $("#fecha_inicial").datepicker("getDate");
// var fecha_final = $("#fecha_final").datepicker("getDate");
// if (fecha_final < fecha_inicial) {
// $("#fecha_inicial").datepicker("setDate", fecha_final);
// }
// $("#fecha_inicial").datepicker("option", "maxDate", fecha_final);
// });
// Datalist carrera then select materia
$(document).on('click', '#dlcarrera li', function() {
// if this is empty
// console.log($(this).attr('data-value'));
if ($(this).attr('data-value') == '0')
disableDatalist("#filter_materia", true);
$(".date-picker").datepicker($.datepicker.regional["es"]);
$(".date-picker").datepicker({
dateFormat: "dd/mm/yyyy",
changeMonth: true,
});
$("#fecha_inicial").datepicker("option", "minDate", fecha_inicial);
$("#fecha_inicial").datepicker("option", "maxDate", limit);
$("#fecha_final").datepicker("option", "minDate", fecha_inicial);
$("#fecha_final").datepicker("option", "maxDate", limit);
var today = new Date();
var fecha_inicial = new Date(<?= isset($fecha_inicial) ? $fecha_inicial->format("Y, m-1, d") : date("Y, m-1, d", strtotime($periodo['inicio'])) ?>);
var fecha_final = new Date(<?= isset($fecha_final) ? $fecha_final->format("Y, m-1, d") : date("Y, m-1, d", strtotime($periodo['fin'])) ?>);
var limit = new Date(Math.min(today, fecha_final));
// if today is in the period, set the initial date to today
$("#fecha_inicial").datepicker("setDate", fecha_inicial);
$("#fecha_final").datepicker("setDate", today <= fecha_final ? today : fecha_final);
function reset_form() {
$("#fecha_inicial").datepicker("setDate", fecha_inicial);
$("#fecha_final").datepicker("setDate", today <= fecha_final ? today : fecha_final);
$("#dlcarrera").find("li").removeClass("selected");
$("#dlcarrera").find("li[data-value='0']").addClass("selected");
$("#dlmateria").find("li").removeClass("selected");
$("#dlmateria").find("li[data-value='0']").addClass("selected");
$("#filter_carrera").val("");
$("#filter_materia").val("");
console.log(`Todos los campos han sido limpiados.`);
}
<?php if (empty($carrera)) { ?>
disableDatalist("#filter_materia", true);
<?php } ?>
reset_form();
// $("#fecha_inicial").on("change", function() {
// var fecha_inicial = $("#fecha_inicial").datepicker("getDate");
// var fecha_final = $("#fecha_final").datepicker("getDate");
// if (fecha_final < fecha_inicial) {
// $("#fecha_final").datepicker("setDate", fecha_inicial);
// }
// $("#fecha_final").datepicker("option", "minDate", fecha_inicial);
// });
// $("#fecha_final").on("change", function() {
// var fecha_inicial = $("#fecha_inicial").datepicker("getDate");
// var fecha_final = $("#fecha_final").datepicker("getDate");
// if (fecha_final < fecha_inicial) {
// $("#fecha_inicial").datepicker("setDate", fecha_final);
// }
// $("#fecha_inicial").datepicker("option", "maxDate", fecha_final);
// });
// Datalist carrera then select materia
$(document).on('click', '#dlcarrera li', function() {
// if this is empty
// console.log($(this).attr('data-value'));
if ($(this).attr('data-value') == '0')
disableDatalist("#filter_materia", true);
});