756 lines
32 KiB
JavaScript
756 lines
32 KiB
JavaScript
const express = require('express');
|
|
const router = express.Router();
|
|
const { requireAuth } = require('../middlewares/authMiddleware');
|
|
|
|
router.use(requireAuth);
|
|
|
|
const handleClassroomsList = async (req, res) => {
|
|
try {
|
|
let allClassrooms = [];
|
|
try {
|
|
const response = await req.apiClient.get('/classrooms');
|
|
allClassrooms = (response.data && response.data.classrooms) || [];
|
|
} catch (cErr) {
|
|
console.warn('Notice fetching classrooms:', cErr.message);
|
|
}
|
|
|
|
const view_mode = (req.query.view_mode || 'physical').toLowerCase();
|
|
const search = (req.query.search || '').toLowerCase().trim();
|
|
const building_filter = req.query.building_id || '';
|
|
const floor_filter = req.query.floor || '';
|
|
const active_only = req.query.active_only !== 'false';
|
|
|
|
// Filter based on view mode (physical vs virtual)
|
|
let filtered = allClassrooms.filter(c => {
|
|
const isVirt = Boolean(c.is_virtual || ((c.code || '').includes('VIRTUAL')) || ((c.building || '').toLowerCase().includes('virtual')));
|
|
if (view_mode === 'virtual') return isVirt;
|
|
return !isVirt;
|
|
});
|
|
|
|
// Additional filters
|
|
if (search) {
|
|
filtered = filtered.filter(c =>
|
|
((c.code || '').toLowerCase().includes(search)) ||
|
|
((c.description || '').toLowerCase().includes(search)) ||
|
|
((c.building || '').toLowerCase().includes(search))
|
|
);
|
|
}
|
|
|
|
if (building_filter) {
|
|
filtered = filtered.filter(c => String(c.building_id) === String(building_filter));
|
|
}
|
|
|
|
if (floor_filter) {
|
|
filtered = filtered.filter(c => String(c.floor) === String(floor_filter));
|
|
}
|
|
|
|
if (active_only) {
|
|
filtered = filtered.filter(c => c.is_active);
|
|
}
|
|
|
|
// Extract unique buildings and floors (consultando también /buildings si está disponible)
|
|
const buildingsMap = new Map();
|
|
const floorsSet = new Set();
|
|
try {
|
|
const bRes = await req.apiClient.get('/buildings');
|
|
const apiBuildings = (bRes.data && bRes.data.buildings) || [];
|
|
apiBuildings.forEach(b => {
|
|
if (b.id && b.name) {
|
|
buildingsMap.set(b.id, { id: b.id, name: b.name });
|
|
}
|
|
});
|
|
} catch (bErr) {
|
|
console.warn('Notice fetching buildings for classrooms filter:', bErr.message);
|
|
}
|
|
|
|
allClassrooms.forEach(c => {
|
|
if (c.building_id && c.building) {
|
|
buildingsMap.set(c.building_id, { id: c.building_id, name: c.building });
|
|
}
|
|
if (c.floor) {
|
|
floorsSet.add(c.floor);
|
|
}
|
|
});
|
|
|
|
// 1. Obtención consolidada de salas virtuales desde la API backend
|
|
let virtual_rooms = [];
|
|
let global_virtual_metrics = {
|
|
today_count: 0,
|
|
week_count: 0,
|
|
month_count: 0,
|
|
commissions_count: 0,
|
|
total_count: 0
|
|
};
|
|
let virtual_count = 0;
|
|
|
|
try {
|
|
const vRoomsRes = await req.apiClient.get('/classrooms/virtual-rooms');
|
|
if (vRoomsRes.data && vRoomsRes.data.virtual_rooms) {
|
|
virtual_rooms = vRoomsRes.data.virtual_rooms;
|
|
virtual_count = vRoomsRes.data.virtual_classrooms_count || virtual_rooms.length;
|
|
global_virtual_metrics = vRoomsRes.data.metrics || {
|
|
today_count: 0,
|
|
week_count: 0,
|
|
month_count: 0,
|
|
commissions_count: virtual_rooms.length,
|
|
total_count: 0
|
|
};
|
|
}
|
|
} catch (vErr) {
|
|
console.warn('Notice fetching virtual rooms from /classrooms/virtual-rooms:', vErr.message);
|
|
}
|
|
|
|
// Fallback a /dashboard/stats si /classrooms/virtual-rooms no devolvió salas
|
|
if (virtual_rooms.length === 0) {
|
|
try {
|
|
const dashRes = await req.apiClient.get('/dashboard/stats');
|
|
const bData = (dashRes.data && (dashRes.data.bedelia || dashRes.data)) || {};
|
|
const vList = bData.virtual_rooms || [];
|
|
if (vList.length > 0) {
|
|
virtual_rooms = vList;
|
|
virtual_count = vList.length;
|
|
global_virtual_metrics = {
|
|
today_count: vList.reduce((acc, r) => acc + (r.today_classes || 0), 0),
|
|
week_count: vList.reduce((acc, r) => acc + (r.week_classes || 0), 0),
|
|
month_count: vList.reduce((acc, r) => acc + (r.month_classes || 0), 0),
|
|
commissions_count: vList.length,
|
|
total_count: vList.reduce((acc, r) => acc + (r.res_count || 0), 0)
|
|
};
|
|
}
|
|
} catch (dErr) {
|
|
console.warn('Fallback fetching dashboard stats notice:', dErr.message);
|
|
}
|
|
}
|
|
|
|
// 2. Fechas operativas dinámicas calculadas desde el momento actual
|
|
const now = new Date();
|
|
const todayIso = now.toISOString().split('T')[0];
|
|
|
|
const dayOfWeek = now.getDay();
|
|
const diffToMonday = (dayOfWeek === 0 ? -6 : 1) - dayOfWeek;
|
|
const monday = new Date(now);
|
|
monday.setDate(now.getDate() + diffToMonday);
|
|
const sunday = new Date(monday);
|
|
sunday.setDate(monday.getDate() + 6);
|
|
const weekStartIso = monday.toISOString().split('T')[0];
|
|
const weekEndIso = sunday.toISOString().split('T')[0];
|
|
|
|
const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
|
|
const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);
|
|
const monthStartIso = firstDayOfMonth.toISOString().split('T')[0];
|
|
const monthEndIso = lastDayOfMonth.toISOString().split('T')[0];
|
|
|
|
// Normalizar campos de salas virtuales para garantizar compatibilidad con plantillas Nunjucks
|
|
virtual_rooms = virtual_rooms.map(room => ({
|
|
...room,
|
|
commission_code: room.commission_code || room.code || 'C1',
|
|
day_count: room.day_count !== undefined ? room.day_count : (room.today_classes || 0),
|
|
week_count: room.week_count !== undefined ? room.week_count : (room.week_classes || 0),
|
|
month_count: room.month_count !== undefined ? room.month_count : (room.month_classes || 0),
|
|
total_count: room.total_count !== undefined ? room.total_count : (room.res_count || 0),
|
|
reservations: (room.reservations || []).map(r => {
|
|
const sStr = String(r.start_time || '');
|
|
const eStr = String(r.end_time || '');
|
|
const dPart = sStr.includes('T') ? sStr.split('T')[0] : (sStr.split(' ')[0] || '');
|
|
const isPast = dPart < todayIso;
|
|
const sTime = sStr.includes('T') ? sStr.split('T')[1].substring(0, 5) : (sStr.split(' ')[1] ? sStr.split(' ')[1].substring(0, 5) : sStr);
|
|
const eTime = eStr.includes('T') ? eStr.split('T')[1].substring(0, 5) : (eStr.split(' ')[1] ? eStr.split(' ')[1].substring(0, 5) : eStr);
|
|
return {
|
|
...r,
|
|
date_clean: dPart,
|
|
time_clean: `${sTime} a ${eTime} hs`,
|
|
is_past: isPast,
|
|
status_display: isPast ? 'Finalizada' : (r.status || 'CONFIRMED')
|
|
};
|
|
})
|
|
}));
|
|
|
|
// Si la búsqueda está activa en modo virtual, filtrar el catálogo de salas virtuales
|
|
if (search && view_mode === 'virtual') {
|
|
virtual_rooms = virtual_rooms.filter(room =>
|
|
((room.subject_name || '').toLowerCase().includes(search)) ||
|
|
((room.code || '').toLowerCase().includes(search)) ||
|
|
((room.full_code || '').toLowerCase().includes(search)) ||
|
|
((room.subject_code || '').toLowerCase().includes(search)) ||
|
|
((room.career_name || '').toLowerCase().includes(search)) ||
|
|
((room.teacher_name || '').toLowerCase().includes(search))
|
|
);
|
|
}
|
|
|
|
const physical_count = allClassrooms.filter(c => !c.is_virtual && !(c.code || '').includes('VIRTUAL')).length;
|
|
if (virtual_count === 0) {
|
|
virtual_count = allClassrooms.filter(c => Boolean(c.is_virtual || (c.code || '').includes('VIRTUAL'))).length;
|
|
}
|
|
|
|
const dateFilters = {
|
|
today: todayIso,
|
|
week_start: weekStartIso,
|
|
week_end: weekEndIso,
|
|
month_start: monthStartIso,
|
|
month_end: monthEndIso
|
|
};
|
|
|
|
// 3. Consultar reservas de un período cuatrimestral amplio (±90 días)
|
|
let allReservations = [];
|
|
try {
|
|
const qStart = new Date(now.getFullYear(), now.getMonth() - 2, 1).toISOString().split('T')[0];
|
|
const qEnd = new Date(now.getFullYear(), now.getMonth() + 3, 0).toISOString().split('T')[0];
|
|
const vRes = await req.apiClient.get('/reservations', {
|
|
params: { start_date: qStart, end_date: qEnd }
|
|
});
|
|
allReservations = (vRes.data && vRes.data.reservations) || [];
|
|
} catch (vErr) {
|
|
console.warn('Error fetching reservations:', vErr.message);
|
|
}
|
|
|
|
const occupancy_metrics = {};
|
|
|
|
// Formatear aulas físicas y calcular métricas de ocupación en base al calendario activo
|
|
const formattedItems = filtered.map(c => {
|
|
const c_res = allReservations.filter(r => (c.id !== undefined && (String(r.classroom_id) === String(c.id) || (r.classroom && String(r.classroom.id) === String(c.id)))));
|
|
|
|
// Filtrar únicamente reservas activas y vigentes (de hoy en adelante) para las cursadas asignadas del aula
|
|
const nowIso = now.toISOString();
|
|
const active_c_res = c_res.filter(r => {
|
|
const rawEnd = r.end_time ? String(r.end_time).replace(' ', 'T') : '';
|
|
const rawStart = r.start_time ? String(r.start_time).replace(' ', 'T') : '';
|
|
const datePart = rawStart.split('T')[0];
|
|
return datePart >= todayIso || (rawEnd && rawEnd >= nowIso);
|
|
});
|
|
|
|
const commMap = new Map();
|
|
active_c_res.forEach(r => {
|
|
const cid = r.commission_id || (r.commission && r.commission.id) || r.id;
|
|
if (!commMap.has(cid)) {
|
|
commMap.set(cid, {
|
|
commission_id: cid,
|
|
commission_code: (r.commission && r.commission.code) || 'C1',
|
|
subject_name: r.subject_name || r.purpose || 'Clase Regular',
|
|
subject_code: r.subject_code || '',
|
|
shift: r.shift || 'Tarde'
|
|
});
|
|
}
|
|
});
|
|
|
|
const day_res = c_res.filter(r => (r.start_time || '').startsWith(todayIso));
|
|
const week_res = c_res.filter(r => {
|
|
const st = (r.start_time || '').split('T')[0];
|
|
return st >= weekStartIso && st <= weekEndIso;
|
|
});
|
|
const month_res = c_res.filter(r => {
|
|
const st = (r.start_time || '').split('T')[0];
|
|
return st >= monthStartIso && st <= monthEndIso;
|
|
});
|
|
|
|
const day_pct = Math.min(100, Math.round((day_res.length / 3) * 100));
|
|
const week_pct = Math.min(100, Math.round((week_res.length / 18) * 100));
|
|
const month_pct = Math.min(100, Math.round((month_res.length / 72) * 100));
|
|
|
|
occupancy_metrics[c.id] = {
|
|
day_pct,
|
|
day_count: day_res.length,
|
|
week_pct,
|
|
week_count: week_res.length,
|
|
month_pct,
|
|
month_count: month_res.length || c_res.length
|
|
};
|
|
|
|
return {
|
|
...c,
|
|
building_name: c.building_name || c.building || 'Edificio Central',
|
|
floor_display: c.floor_display || (c.floor === '0' || c.floor === 'PB' ? 'Planta Baja' : `Piso ${c.floor}`),
|
|
resources: c.resources || [],
|
|
assigned_commissions: Array.from(commMap.values()),
|
|
total_classes: active_c_res.length,
|
|
historical_classes: c_res.length
|
|
};
|
|
});
|
|
|
|
const virtualClassroomObj = allClassrooms.find(c => Boolean(c.is_virtual || ((c.code || '').includes('VIRTUAL'))));
|
|
const virtual_classroom_id = virtualClassroomObj ? virtualClassroomObj.id : null;
|
|
|
|
res.render('classrooms/list', {
|
|
title: 'Aulas y Espacios - Edu-Space Admin',
|
|
classrooms: {
|
|
items: formattedItems,
|
|
total: formattedItems.length,
|
|
pages: 1,
|
|
page: 1,
|
|
has_prev: false,
|
|
has_next: false,
|
|
iter_pages: () => [1]
|
|
},
|
|
view_mode,
|
|
search,
|
|
building_filter,
|
|
floor_filter,
|
|
active_only,
|
|
physical_count,
|
|
virtual_count,
|
|
buildings: Array.from(buildingsMap.values()),
|
|
floors: Array.from(floorsSet).sort(),
|
|
occupancy_metrics,
|
|
date_filters: dateFilters,
|
|
virtual_rooms,
|
|
global_virtual_metrics,
|
|
virtual_classroom_id
|
|
});
|
|
|
|
} catch (error) {
|
|
console.error('Error in classrooms list route:', error.message);
|
|
const view_mode = (req.query.view_mode || 'physical').toLowerCase();
|
|
res.render('classrooms/list', {
|
|
title: 'Aulas y Espacios - Edu-Space Admin',
|
|
classrooms: { items: [], total: 0, pages: 1, page: 1, has_prev: false, has_next: false, iter_pages: () => [1] },
|
|
view_mode,
|
|
search: '',
|
|
building_filter: '',
|
|
floor_filter: '',
|
|
active_only: true,
|
|
physical_count: 0,
|
|
virtual_count: 0,
|
|
buildings: [],
|
|
floors: [],
|
|
occupancy_metrics: {},
|
|
date_filters: {},
|
|
virtual_rooms: [],
|
|
global_virtual_metrics: {
|
|
today_count: 0,
|
|
week_count: 0,
|
|
month_count: 0,
|
|
commissions_count: 0,
|
|
total_count: 0
|
|
},
|
|
virtual_classroom_id: null
|
|
});
|
|
}
|
|
};
|
|
|
|
const { createFormMock } = require('../utils/formHelper');
|
|
|
|
const handleAddClassroom = async (req, res) => {
|
|
try {
|
|
let allClassrooms = [];
|
|
let allBuildings = [];
|
|
try {
|
|
const [cRes, bRes] = await Promise.allSettled([
|
|
req.apiClient.get('/classrooms'),
|
|
req.apiClient.get('/buildings')
|
|
]);
|
|
if (cRes.status === 'fulfilled' && cRes.value.data?.classrooms) {
|
|
allClassrooms = cRes.value.data.classrooms;
|
|
}
|
|
if (bRes.status === 'fulfilled' && bRes.value.data?.buildings) {
|
|
allBuildings = bRes.value.data.buildings;
|
|
}
|
|
} catch (e) {
|
|
console.warn('Could not fetch classrooms/buildings for add page:', e.message);
|
|
}
|
|
|
|
const buildingsMap = new Map();
|
|
allBuildings.forEach(b => {
|
|
if (b.id && b.name) {
|
|
buildingsMap.set(String(b.id), { id: b.id, name: b.name });
|
|
}
|
|
});
|
|
|
|
const buildingFloors = {};
|
|
allBuildings.forEach(b => {
|
|
const bId = String(b.id);
|
|
buildingFloors[bId] = b.is_virtual ? ['Digital'] : ['PB', '1', '2'];
|
|
});
|
|
|
|
allClassrooms.forEach(c => {
|
|
const bId = String(c.building_id || '');
|
|
if (bId) {
|
|
if (!buildingFloors[bId]) buildingFloors[bId] = [];
|
|
if (c.floor && !buildingFloors[bId].includes(c.floor)) {
|
|
buildingFloors[bId].push(c.floor);
|
|
}
|
|
if (c.building) {
|
|
buildingsMap.set(bId, { id: c.building_id, name: c.building });
|
|
}
|
|
}
|
|
});
|
|
|
|
const buildings = Array.from(buildingsMap.values());
|
|
const buildingOptions = [
|
|
{ value: '', text: buildings.length > 0 ? '-- Selecciona Edificio / Sede --' : '-- Sin sedes registradas (Cree una abajo) --' },
|
|
...buildings.map(b => ({ value: b.id, text: b.name })),
|
|
{ value: 'new', text: '+ Crear nuevo edificio / sede' }
|
|
];
|
|
|
|
const preselectedBuildingId = req.query.building_id || '';
|
|
const preselectedFloor = req.query.floor || '';
|
|
|
|
const form = createFormMock({
|
|
is_active: true,
|
|
capacity: 35,
|
|
building_id: preselectedBuildingId,
|
|
floor: preselectedFloor
|
|
}, {
|
|
building_id: buildingOptions
|
|
});
|
|
|
|
res.render('classrooms/add', {
|
|
title: 'Add Classroom - Edu-Space Admin',
|
|
form,
|
|
buildings,
|
|
building_floors: buildingFloors,
|
|
preselected_building_id: preselectedBuildingId,
|
|
preselected_floor: preselectedFloor
|
|
});
|
|
} catch (error) {
|
|
console.error('Error rendering add classroom:', error.message);
|
|
res.status(500).send('Error loading add classroom page');
|
|
}
|
|
};
|
|
|
|
const handlePostClassroom = async (req, res) => {
|
|
try {
|
|
const { building_id, new_building_name, floor, room_number, capacity, description, is_active } = req.body;
|
|
|
|
const isNewBuilding = building_id === 'new' || !building_id;
|
|
const bName = (new_building_name || '').trim();
|
|
const bId = (!isNewBuilding && building_id) ? parseInt(building_id, 10) : null;
|
|
|
|
const isVirtual = Boolean(
|
|
(bName && bName.toLowerCase().includes('virtual')) ||
|
|
String(room_number).toUpperCase().includes('VIRTUAL') ||
|
|
String(floor).toUpperCase() === 'DIGITAL'
|
|
);
|
|
|
|
const payload = {
|
|
code: room_number || `Aula-${Date.now()}`,
|
|
capacity: (isVirtual || capacity === '∞' || capacity === '0' || !capacity) ? 0 : parseInt(capacity, 10),
|
|
floor: floor || (isVirtual ? 'Digital' : 'PB'),
|
|
description: description || '',
|
|
is_virtual: isVirtual,
|
|
is_active: is_active === 'true' || is_active === 'on' || is_active === true
|
|
};
|
|
|
|
if (bId && !isNaN(bId) && bId > 0) {
|
|
payload.building_id = bId;
|
|
} else if (bName) {
|
|
payload.building_name = bName;
|
|
} else {
|
|
payload.building_name = isVirtual ? 'Campus Virtual' : 'Edificio Central';
|
|
}
|
|
|
|
try {
|
|
await req.apiClient.post('/classrooms', payload);
|
|
} catch (apiErr) {
|
|
console.warn('API classroom creation notice:', apiErr.response?.data || apiErr.message);
|
|
}
|
|
|
|
res.redirect('/classrooms/list_classrooms');
|
|
} catch (error) {
|
|
console.error('Error saving classroom:', error.message);
|
|
res.redirect('/classrooms/list_classrooms');
|
|
}
|
|
};
|
|
|
|
router.get('/', handleClassroomsList);
|
|
router.get('/list', handleClassroomsList);
|
|
router.get('/list_classrooms', handleClassroomsList);
|
|
|
|
router.get('/add', handleAddClassroom);
|
|
router.get('/add_classroom', handleAddClassroom);
|
|
router.post('/add', handlePostClassroom);
|
|
router.post('/add_classroom', handlePostClassroom);
|
|
|
|
// ─── View Classroom ────────────────────────────────────────────────────────────
|
|
const handleViewClassroom = async (req, res) => {
|
|
const classroomId = req.params.id || req.query.id || req.query.classroom_id || '1';
|
|
try {
|
|
let classroom = null;
|
|
let upcomingReservations = [];
|
|
let pastReservations = [];
|
|
|
|
try {
|
|
const cRes = await req.apiClient.get(`/classrooms/${classroomId}`);
|
|
classroom = cRes.data;
|
|
} catch (e) {
|
|
console.warn(`Classroom ${classroomId} not found in API, using mock`);
|
|
}
|
|
|
|
// Fallback mock
|
|
if (!classroom) {
|
|
classroom = {
|
|
id: classroomId,
|
|
code: `Aula-${classroomId}`,
|
|
code_display: `Aula ${classroomId}`,
|
|
building: 'Edificio Central',
|
|
floor: '1',
|
|
capacity: 40,
|
|
is_active: true,
|
|
is_virtual: false,
|
|
is_unlimited: false,
|
|
description: 'Aula de uso general con proyector y pizarrón.'
|
|
};
|
|
}
|
|
|
|
// Normalize fields
|
|
classroom.code_display = classroom.code_display || classroom.code || `Aula-${classroomId}`;
|
|
classroom.building_entity = classroom.building_entity || null;
|
|
|
|
// Fetch upcoming and past reservations for this classroom
|
|
try {
|
|
const now = new Date();
|
|
const todayIso = now.toISOString().split('T')[0];
|
|
const nowIso = now.toISOString();
|
|
|
|
const rRes = await req.apiClient.get(`/reservations?classroom_id=${classroomId}&start_date=2026-08-01&end_date=2026-12-31`);
|
|
const allClassroomRes = (rRes.data && (rRes.data.reservations || rRes.data)) || [];
|
|
const dayNames = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
|
|
|
|
const formatReservationItem = (r) => {
|
|
let dateDisplayFriendly = '';
|
|
let timeRangeFriendly = '';
|
|
let fullDisplay = '';
|
|
|
|
if (r.start_time) {
|
|
try {
|
|
const rawStart = String(r.start_time).replace(' ', 'T');
|
|
const rawEnd = r.end_time ? String(r.end_time).replace(' ', 'T') : '';
|
|
const dtStart = new Date(rawStart);
|
|
const dtEnd = rawEnd ? new Date(rawEnd) : null;
|
|
|
|
const dayName = dayNames[dtStart.getDay()];
|
|
const d = String(dtStart.getDate()).padStart(2, '0');
|
|
const m = String(dtStart.getMonth() + 1).padStart(2, '0');
|
|
const y = dtStart.getFullYear();
|
|
dateDisplayFriendly = `${dayName} ${d}/${m}/${y}`;
|
|
|
|
const sH = String(dtStart.getHours()).padStart(2, '0');
|
|
const sM = String(dtStart.getMinutes()).padStart(2, '0');
|
|
const eH = dtEnd ? String(dtEnd.getHours()).padStart(2, '0') : '';
|
|
const eM = dtEnd ? String(dtEnd.getMinutes()).padStart(2, '0') : '';
|
|
timeRangeFriendly = dtEnd ? `${sH}:${sM} a ${eH}:${eM} hs` : `${sH}:${sM} hs`;
|
|
fullDisplay = `${dateDisplayFriendly} · ${timeRangeFriendly}`;
|
|
} catch (e) {
|
|
dateDisplayFriendly = r.start_time.split('T')[0] || r.start_time;
|
|
timeRangeFriendly = r.end_time ? `${r.start_time} - ${r.end_time}` : r.start_time;
|
|
fullDisplay = `${dateDisplayFriendly} · ${timeRangeFriendly}`;
|
|
}
|
|
}
|
|
|
|
return {
|
|
...r,
|
|
date_display: r.start_time ? r.start_time.split('T')[0] : '',
|
|
date_display_friendly: dateDisplayFriendly,
|
|
time_range_friendly: timeRangeFriendly,
|
|
full_display: fullDisplay,
|
|
start_time_display: r.start_time ? (r.start_time.includes('T') ? r.start_time.split('T')[1].substring(0, 5) : r.start_time) : '',
|
|
end_time_display: r.end_time ? (r.end_time.includes('T') ? r.end_time.split('T')[1].substring(0, 5) : r.end_time) : ''
|
|
};
|
|
};
|
|
|
|
// Filtrar estrictamente Próximas Reservas (de hoy en adelante o no finalizadas)
|
|
const upcomingRaw = allClassroomRes.filter(r => {
|
|
const rawEnd = r.end_time ? String(r.end_time).replace(' ', 'T') : '';
|
|
const rawStart = r.start_time ? String(r.start_time).replace(' ', 'T') : '';
|
|
const datePart = rawStart.split('T')[0];
|
|
return datePart >= todayIso || (rawEnd && rawEnd >= nowIso);
|
|
});
|
|
|
|
// Reservas pasadas (ya concluidas en fechas anteriores)
|
|
const pastRaw = allClassroomRes.filter(r => {
|
|
const rawEnd = r.end_time ? String(r.end_time).replace(' ', 'T') : '';
|
|
const rawStart = r.start_time ? String(r.start_time).replace(' ', 'T') : '';
|
|
const datePart = rawStart.split('T')[0];
|
|
return datePart < todayIso && (!rawEnd || rawEnd < nowIso);
|
|
});
|
|
|
|
upcomingReservations = upcomingRaw.map(formatReservationItem).sort((a, b) => (a.start_time || '').localeCompare(b.start_time || '')).slice(0, 30);
|
|
pastReservations = pastRaw.map(formatReservationItem).sort((a, b) => (b.start_time || '').localeCompare(a.start_time || '')).slice(0, 30);
|
|
} catch (e) {
|
|
console.warn('Could not fetch reservations for classroom:', e.message);
|
|
}
|
|
|
|
res.render('classrooms/view', {
|
|
title: `${classroom.code_display} - Edu-Space Admin`,
|
|
classroom,
|
|
upcoming_reservations: upcomingReservations,
|
|
past_reservations: pastReservations
|
|
});
|
|
} catch (error) {
|
|
console.error('Error in view classroom:', error.message);
|
|
res.redirect('/classrooms/list_classrooms');
|
|
}
|
|
};
|
|
|
|
router.get('/view/:id', handleViewClassroom);
|
|
router.get('/view_classroom/:id', handleViewClassroom);
|
|
router.get('/view_classroom', handleViewClassroom);
|
|
router.get('/:id/view', handleViewClassroom);
|
|
|
|
// ─── Edit Classroom ────────────────────────────────────────────────────────────
|
|
const handleEditClassroom = async (req, res) => {
|
|
const classroomId = req.params.id || req.query.id || req.query.classroom_id || '1';
|
|
try {
|
|
let classroom = null;
|
|
let allClassrooms = [];
|
|
try {
|
|
const [cRes, allRes] = await Promise.allSettled([
|
|
req.apiClient.get(`/classrooms/${classroomId}`),
|
|
req.apiClient.get('/classrooms')
|
|
]);
|
|
if (cRes.status === 'fulfilled' && cRes.value.data) {
|
|
classroom = cRes.value.data;
|
|
}
|
|
if (allRes.status === 'fulfilled' && allRes.value.data) {
|
|
allClassrooms = allRes.value.data.classrooms || [];
|
|
}
|
|
} catch (e) {
|
|
console.warn(`Classroom ${classroomId} fetch warning:`, e.message);
|
|
}
|
|
|
|
if (!classroom) {
|
|
classroom = {
|
|
id: classroomId,
|
|
code: `Aula-${classroomId}`,
|
|
code_display: `Aula ${classroomId}`,
|
|
building: 'Edificio Central',
|
|
building_id: 1,
|
|
floor: '1',
|
|
capacity: 40,
|
|
is_active: true,
|
|
is_virtual: false,
|
|
description: 'Aula de uso general'
|
|
};
|
|
}
|
|
|
|
classroom.code_display = classroom.code_display || classroom.code || `Aula-${classroomId}`;
|
|
classroom.building_name = classroom.building_name || classroom.building || 'Edificio Central';
|
|
classroom.floor_display = classroom.floor_display || (classroom.floor === '0' || classroom.floor === 'PB' ? 'Planta Baja' : `Piso ${classroom.floor}`);
|
|
classroom.location_display = classroom.location_display || `${classroom.building_name} - ${classroom.floor_display}`;
|
|
|
|
const buildingFloors = {
|
|
'1': ['PB', '1', '2', '3'],
|
|
'2': ['Virtual']
|
|
};
|
|
const buildingsMap = new Map();
|
|
buildingsMap.set('1', { id: 1, name: 'Edificio Central' });
|
|
buildingsMap.set('2', { id: 2, name: 'Campus Virtual' });
|
|
|
|
allClassrooms.forEach(c => {
|
|
const bId = String(c.building_id || 1);
|
|
if (!buildingFloors[bId]) buildingFloors[bId] = [];
|
|
if (c.floor && !buildingFloors[bId].includes(c.floor)) {
|
|
buildingFloors[bId].push(c.floor);
|
|
}
|
|
if (c.building_id && c.building) {
|
|
buildingsMap.set(bId, { id: c.building_id, name: c.building });
|
|
}
|
|
});
|
|
|
|
const buildings = Array.from(buildingsMap.values());
|
|
const buildingOptions = [
|
|
{ value: '', text: '-- Selecciona Edificio / Sede --' },
|
|
...buildings.map(b => ({ value: b.id, text: b.name })),
|
|
{ value: 'new', text: '+ Crear nuevo edificio' }
|
|
];
|
|
|
|
const form = createFormMock({
|
|
building_id: classroom.building_id || 1,
|
|
floor: classroom.floor || 'PB',
|
|
room_number: classroom.code || '',
|
|
capacity: classroom.capacity !== undefined ? classroom.capacity : 35,
|
|
is_active: classroom.is_active,
|
|
description: classroom.description || ''
|
|
}, {
|
|
building_id: buildingOptions
|
|
});
|
|
|
|
res.render('classrooms/edit', {
|
|
title: `Editar Aula - ${classroom.code_display}`,
|
|
classroom,
|
|
form,
|
|
buildings,
|
|
building_floors: buildingFloors
|
|
});
|
|
} catch (error) {
|
|
console.error('Error in edit classroom:', error.message);
|
|
res.redirect('/classrooms/list_classrooms');
|
|
}
|
|
};
|
|
|
|
const handlePostEditClassroom = async (req, res) => {
|
|
const classroomId = req.params.id || req.query.id || req.body.id;
|
|
try {
|
|
const { building_id, new_building_name, floor, room_number, capacity, description, is_active } = req.body;
|
|
|
|
let targetBuilding = building_id;
|
|
if (building_id === 'new' && new_building_name) {
|
|
targetBuilding = new_building_name;
|
|
}
|
|
|
|
let bId = parseInt(targetBuilding, 10);
|
|
if (isNaN(bId) || bId <= 0) {
|
|
bId = (String(targetBuilding).toLowerCase().includes('virtual')) ? 2 : 1;
|
|
}
|
|
|
|
const isVirtual = Boolean(
|
|
bId === 2 ||
|
|
String(targetBuilding).toLowerCase().includes('virtual') ||
|
|
String(room_number).toUpperCase().includes('VIRTUAL') ||
|
|
String(floor).toUpperCase() === 'DIGITAL'
|
|
);
|
|
|
|
const payload = {
|
|
code: room_number,
|
|
capacity: (isVirtual || capacity === '∞' || capacity === '0' || !capacity) ? 0 : parseInt(capacity, 10),
|
|
floor: floor || (isVirtual ? 'Digital' : 'PB'),
|
|
building_id: bId,
|
|
description: description || '',
|
|
is_virtual: isVirtual,
|
|
is_active: is_active === 'true' || is_active === 'on' || is_active === true
|
|
};
|
|
|
|
try {
|
|
await req.apiClient.put(`/classrooms/${classroomId}`, payload);
|
|
} catch (apiErr) {
|
|
console.warn('API classroom update notice:', apiErr.response?.data || apiErr.message);
|
|
}
|
|
|
|
res.redirect(`/classrooms/view_classroom/${classroomId}`);
|
|
} catch (error) {
|
|
console.error('Error updating classroom:', error.message);
|
|
res.redirect('/classrooms/list_classrooms');
|
|
}
|
|
};
|
|
|
|
router.get('/edit/:id', handleEditClassroom);
|
|
router.get('/edit_classroom/:id', handleEditClassroom);
|
|
router.get('/edit_classroom', handleEditClassroom);
|
|
router.post('/edit/:id', handlePostEditClassroom);
|
|
router.post('/edit_classroom/:id', handlePostEditClassroom);
|
|
router.post('/edit_classroom', handlePostEditClassroom);
|
|
|
|
const handleToggleClassroom = async (req, res) => {
|
|
const id = req.params.id || req.body.classroom_id || req.body.id || req.query.id;
|
|
try {
|
|
await req.apiClient.post(`/classrooms/${id}/toggle`);
|
|
} catch (e) {
|
|
console.warn('Error toggling classroom:', e.response?.data || e.message);
|
|
}
|
|
const referer = req.get('Referer') || '/classrooms/list_classrooms';
|
|
res.redirect(referer);
|
|
};
|
|
|
|
const handleDeleteClassroom = async (req, res) => {
|
|
const id = req.params.id || req.body.classroom_id || req.body.id || req.query.id;
|
|
try {
|
|
await req.apiClient.delete(`/classrooms/${id}`);
|
|
} catch (e) {
|
|
console.warn('Error deleting classroom:', e.response?.data || e.message);
|
|
}
|
|
res.redirect('/classrooms/list_classrooms');
|
|
};
|
|
|
|
router.post(['/toggle_classroom', '/toggle/:id', '/:id/toggle'], handleToggleClassroom);
|
|
router.post(['/delete_classroom', '/delete/:id', '/:id/delete'], handleDeleteClassroom);
|
|
|
|
module.exports = router;
|