feat(schedule): group reservations by real time slots and clean date-time formatting v3.4.2
This commit is contained in:
+60
-7
@@ -85,9 +85,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), {
|
||||
});
|
||||
|
||||
// Versiones institucionales del sistema
|
||||
const APP_VERSION = '3.4.1';
|
||||
const FRONTEND_VERSION = '3.4.1';
|
||||
const BACKEND_VERSION = '3.4.1';
|
||||
const APP_VERSION = '3.4.2';
|
||||
const FRONTEND_VERSION = '3.4.2';
|
||||
const BACKEND_VERSION = '3.4.2';
|
||||
|
||||
env.addGlobal('app_version', APP_VERSION);
|
||||
env.addGlobal('frontend_version', FRONTEND_VERSION);
|
||||
@@ -129,20 +129,73 @@ env.addFilter('format', function(str, ...args) {
|
||||
|
||||
const formatDateHelper = function(d, fmt) {
|
||||
if (!d) return '';
|
||||
if (typeof d === 'string') return d.split('T')[0];
|
||||
return new Date(d).toISOString().split('T')[0];
|
||||
let str = String(d);
|
||||
let datePart = str.includes('T') ? str.split('T')[0] : (str.includes(' ') ? str.split(' ')[0] : str);
|
||||
if (datePart.match(/^\d{4}-\d{2}-\d{2}$/)) {
|
||||
const [y, m, day] = datePart.split('-');
|
||||
const year = parseInt(y, 10);
|
||||
const month = parseInt(m, 10);
|
||||
const dayNum = parseInt(day, 10);
|
||||
const dObj = new Date(year, month - 1, dayNum);
|
||||
const daysNames = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
|
||||
const monthsNames = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
|
||||
const dayName = daysNames[dObj.getDay()] || '';
|
||||
const monthName = monthsNames[month - 1] || '';
|
||||
const dayPad = String(dayNum).padStart(2, '0');
|
||||
const monthPad = String(month).padStart(2, '0');
|
||||
|
||||
if (fmt === 'long' || fmt === 'human') {
|
||||
return `${dayName} ${dayPad}/${monthPad}/${year}`;
|
||||
}
|
||||
if (fmt === 'full') {
|
||||
return `${dayName}, ${dayPad} de ${monthName} de ${year}`;
|
||||
}
|
||||
return `${dayPad}/${monthPad}/${year}`;
|
||||
}
|
||||
return datePart;
|
||||
};
|
||||
|
||||
const formatDateTimeHelper = function(d, fmt) {
|
||||
if (!d) return '';
|
||||
if (typeof d === 'string') return d.replace('T', ' ').substring(0, 16);
|
||||
return new Date(d).toLocaleString();
|
||||
let str = String(d);
|
||||
let datePart = formatDateHelper(str);
|
||||
let timePart = '';
|
||||
if (str.includes('T')) {
|
||||
timePart = str.split('T')[1].substring(0, 5) + ' hs';
|
||||
} else if (str.includes(' ')) {
|
||||
timePart = str.split(' ')[1].substring(0, 5) + ' hs';
|
||||
}
|
||||
return timePart ? `${datePart} ${timePart}` : datePart;
|
||||
};
|
||||
|
||||
const formatTimeCleanHelper = function(d) {
|
||||
if (!d) return '';
|
||||
let str = String(d);
|
||||
if (str.includes('T')) return str.split('T')[1].substring(0, 5) + ' hs';
|
||||
if (str.includes(' ')) return str.split(' ')[1].substring(0, 5) + ' hs';
|
||||
if (str.match(/^\d{2}:\d{2}/)) return str.substring(0, 5) + ' hs';
|
||||
return str;
|
||||
};
|
||||
|
||||
const formatTimeRangeHelper = function(start, end) {
|
||||
if (!start) return '';
|
||||
let s = String(start);
|
||||
let e = String(end || '');
|
||||
let st = s.includes('T') ? s.split('T')[1].substring(0, 5) : (s.includes(' ') ? s.split(' ')[1].substring(0, 5) : s.substring(0, 5));
|
||||
let et = e.includes('T') ? e.split('T')[1].substring(0, 5) : (e.includes(' ') ? e.split(' ')[1].substring(0, 5) : e.substring(0, 5));
|
||||
return et ? `${st} - ${et} hs` : `${st} hs`;
|
||||
};
|
||||
|
||||
env.addGlobal('format_date', formatDateHelper);
|
||||
env.addGlobal('format_datetime', formatDateTimeHelper);
|
||||
env.addGlobal('format_time', formatTimeCleanHelper);
|
||||
env.addGlobal('format_time_range', formatTimeRangeHelper);
|
||||
|
||||
env.addFilter('format_date', formatDateHelper);
|
||||
env.addFilter('format_datetime', formatDateTimeHelper);
|
||||
env.addFilter('format_date_human', function(d) { return formatDateHelper(d, 'human'); });
|
||||
env.addFilter('format_time', formatTimeCleanHelper);
|
||||
env.addFilter('format_time_range', formatTimeRangeHelper);
|
||||
|
||||
env.addFilter('tojson', function(val) {
|
||||
return JSON.stringify(val !== undefined ? val : null);
|
||||
|
||||
+159
-23
@@ -125,11 +125,132 @@ const handleCalendarData = async (req, res) => {
|
||||
router.get('/calendar_data', handleCalendarData);
|
||||
router.get('/calendar-data', handleCalendarData);
|
||||
|
||||
// Función utilitaria para normalizar y formatear fechas, horarios y atributos de una reserva
|
||||
function formatReservationDates(r) {
|
||||
if (!r) return r;
|
||||
const rawStart = r.start_time ? String(r.start_time) : '';
|
||||
const rawEnd = r.end_time ? String(r.end_time) : '';
|
||||
|
||||
// Extraer fecha 'YYYY-MM-DD'
|
||||
let dateStr = '';
|
||||
if (rawStart.includes('T')) {
|
||||
dateStr = rawStart.split('T')[0];
|
||||
} else if (rawStart.includes(' ')) {
|
||||
dateStr = rawStart.split(' ')[0];
|
||||
} else if (rawStart.match(/^\d{4}-\d{2}-\d{2}/)) {
|
||||
dateStr = rawStart.substring(0, 10);
|
||||
}
|
||||
|
||||
// Extraer horas HH:mm
|
||||
let startTimeStr = '08:00';
|
||||
let endTimeStr = '10:00';
|
||||
if (rawStart.includes('T')) {
|
||||
startTimeStr = rawStart.split('T')[1].substring(0, 5);
|
||||
} else if (rawStart.includes(' ')) {
|
||||
startTimeStr = rawStart.split(' ')[1].substring(0, 5);
|
||||
} else if (rawStart.match(/^\d{2}:\d{2}/)) {
|
||||
startTimeStr = rawStart.substring(0, 5);
|
||||
}
|
||||
|
||||
if (rawEnd.includes('T')) {
|
||||
endTimeStr = rawEnd.split('T')[1].substring(0, 5);
|
||||
} else if (rawEnd.includes(' ')) {
|
||||
endTimeStr = rawEnd.split(' ')[1].substring(0, 5);
|
||||
} else if (rawEnd.match(/^\d{2}:\d{2}/)) {
|
||||
endTimeStr = rawEnd.substring(0, 5);
|
||||
}
|
||||
|
||||
// Formatear fecha en español
|
||||
let date_short = dateStr;
|
||||
let date_display = dateStr;
|
||||
let date_full = dateStr;
|
||||
if (dateStr && dateStr.includes('-')) {
|
||||
const parts = dateStr.split('-');
|
||||
if (parts.length === 3) {
|
||||
const year = parseInt(parts[0], 10);
|
||||
const month = parseInt(parts[1], 10);
|
||||
const day = parseInt(parts[2], 10);
|
||||
const dObj = new Date(year, month - 1, day);
|
||||
const daysNames = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
|
||||
const monthsNames = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
|
||||
const dayName = daysNames[dObj.getDay()] || '';
|
||||
const monthName = monthsNames[month - 1] || '';
|
||||
const dayPad = String(day).padStart(2, '0');
|
||||
const monthPad = String(month).padStart(2, '0');
|
||||
|
||||
date_short = `${dayPad}/${monthPad}/${year}`;
|
||||
date_display = `${dayName} ${dayPad}/${monthPad}/${year}`;
|
||||
date_full = `${dayName}, ${dayPad} de ${monthName} de ${year}`;
|
||||
}
|
||||
}
|
||||
|
||||
// Calcular duración amigable
|
||||
let durationMinutes = 0;
|
||||
if (startTimeStr && endTimeStr) {
|
||||
const [sh, sm] = startTimeStr.split(':').map(Number);
|
||||
const [eh, em] = endTimeStr.split(':').map(Number);
|
||||
durationMinutes = (eh * 60 + em) - (sh * 60 + sm);
|
||||
if (durationMinutes < 0) durationMinutes += 24 * 60;
|
||||
}
|
||||
let duration_display = '2 hs';
|
||||
if (durationMinutes > 0) {
|
||||
const hours = Math.floor(durationMinutes / 60);
|
||||
const mins = durationMinutes % 60;
|
||||
if (mins === 0) {
|
||||
duration_display = `${hours} hs`;
|
||||
} else {
|
||||
duration_display = `${hours}h ${mins}m`;
|
||||
}
|
||||
}
|
||||
|
||||
const isVirt = Boolean(r.is_virtual || (r.classroom && r.classroom.is_virtual) || (r.classroom_name && r.classroom_name.includes('VIRTUAL')));
|
||||
const startHour = parseInt(startTimeStr.split(':')[0], 10) || 8;
|
||||
let inferredShift = r.shift;
|
||||
if (!inferredShift) {
|
||||
if (startHour >= 18) inferredShift = 'Noche';
|
||||
else if (startHour >= 13) inferredShift = 'Tarde';
|
||||
else inferredShift = 'Mañana';
|
||||
}
|
||||
|
||||
return {
|
||||
...r,
|
||||
raw_start_time: rawStart,
|
||||
raw_end_time: rawEnd,
|
||||
start_time: startTimeStr,
|
||||
end_time: endTimeStr,
|
||||
start_time_clean: startTimeStr,
|
||||
end_time_clean: endTimeStr,
|
||||
start_time_display: `${startTimeStr} hs`,
|
||||
end_time_display: `${endTimeStr} hs`,
|
||||
time_display: `${startTimeStr} - ${endTimeStr} hs`,
|
||||
time_range: `${startTimeStr} - ${endTimeStr} hs`,
|
||||
duration_minutes: durationMinutes,
|
||||
duration_display,
|
||||
date_raw: dateStr,
|
||||
date_short,
|
||||
date_display,
|
||||
date_full,
|
||||
shift: inferredShift,
|
||||
is_virtual: isVirt,
|
||||
subject_name: r.subject_name || r.purpose || 'Clase Regular',
|
||||
subject_code: r.subject_code || '',
|
||||
effective_virtual_link: r.effective_virtual_link || r.virtual_link || '',
|
||||
classroom: r.classroom || {
|
||||
code: r.classroom_name || (isVirt ? 'VIRTUAL' : 'Sin Aula'),
|
||||
floor: isVirt ? 0 : 1,
|
||||
is_virtual: isVirt,
|
||||
building: isVirt ? 'Campus Virtual' : 'Edificio Central'
|
||||
},
|
||||
user: r.user || { name: r.teacher_name || 'Docente' }
|
||||
};
|
||||
}
|
||||
|
||||
// 3. Vista de Lista de Reservas
|
||||
const handleReservationsList = async (req, res) => {
|
||||
try {
|
||||
const response = await req.apiClient.get('/reservations');
|
||||
const reservations = (response.data && response.data.reservations) || [];
|
||||
const rawReservations = (response.data && response.data.reservations) || [];
|
||||
const reservations = rawReservations.map(formatReservationDates);
|
||||
|
||||
res.render('schedule/list', {
|
||||
title: 'Listado de Reservas - Edu-Space Admin',
|
||||
@@ -190,35 +311,46 @@ const handleTodaySchedule = async (req, res) => {
|
||||
const response = await req.apiClient.get('/reservations', { params });
|
||||
let rawReservations = (response.data && response.data.reservations) || [];
|
||||
|
||||
// Format each reservation for the template
|
||||
const reservations = rawReservations.map(r => {
|
||||
const st = r.start_time.includes('T') ? r.start_time.split('T')[1].substring(0, 5) : r.start_time;
|
||||
const et = r.end_time.includes('T') ? r.end_time.split('T')[1].substring(0, 5) : r.end_time;
|
||||
const isVirt = Boolean(r.is_virtual || (r.classroom && r.classroom.is_virtual));
|
||||
return {
|
||||
...r,
|
||||
start_time: st,
|
||||
end_time: et,
|
||||
subject_name: r.subject_name || r.purpose || 'Clase Regular',
|
||||
subject_code: r.subject_code || '',
|
||||
effective_virtual_link: r.effective_virtual_link || r.virtual_link || '',
|
||||
is_virtual: isVirt,
|
||||
classroom: r.classroom || { code: r.classroom_name || (isVirt ? 'VIRTUAL' : 'Sin Aula'), floor: isVirt ? 0 : 1, is_virtual: isVirt },
|
||||
user: r.user || { name: r.teacher_name || 'Docente' }
|
||||
};
|
||||
// Formatear cada reserva con atributos enriquecidos
|
||||
const reservations = rawReservations.map(formatReservationDates);
|
||||
|
||||
// Agrupar en franjas horarias reales (Time Slots) para que cada reserva aparezca agrupada y una sola vez
|
||||
const slotsMap = new Map();
|
||||
reservations.forEach(r => {
|
||||
const slotKey = `${r.start_time} - ${r.end_time}`;
|
||||
if (!slotsMap.has(slotKey)) {
|
||||
slotsMap.set(slotKey, {
|
||||
key: slotKey,
|
||||
start_time: r.start_time,
|
||||
end_time: r.end_time,
|
||||
time_display: r.time_display,
|
||||
duration_display: r.duration_display,
|
||||
shift: r.shift,
|
||||
items: []
|
||||
});
|
||||
}
|
||||
slotsMap.get(slotKey).items.push({
|
||||
reservation: r,
|
||||
classroom: r.classroom,
|
||||
commission: r.commission,
|
||||
user: r.user
|
||||
});
|
||||
});
|
||||
|
||||
// Build time_blocks for hours 7 to 21
|
||||
// Ordenar slots cronológicamente por horario de inicio y fin
|
||||
const grouped_slots = Array.from(slotsMap.values()).sort((a, b) => {
|
||||
return a.start_time.localeCompare(b.start_time) || a.end_time.localeCompare(b.end_time);
|
||||
});
|
||||
|
||||
// Mantener time_blocks por compatibilidad (asigna a la hora de inicio sin duplicar)
|
||||
const time_blocks = {};
|
||||
for (let hour = 7; hour <= 21; hour++) {
|
||||
time_blocks[hour] = [];
|
||||
}
|
||||
|
||||
reservations.forEach(r => {
|
||||
const startHour = parseInt(r.start_time.split(':')[0], 10) || 8;
|
||||
const endHour = parseInt(r.end_time.split(':')[0], 10) || (startHour + 2);
|
||||
for (let h = Math.max(7, startHour); h <= Math.min(21, endHour - 1); h++) {
|
||||
time_blocks[h].push({
|
||||
if (time_blocks[startHour]) {
|
||||
time_blocks[startHour].push({
|
||||
reservation: r,
|
||||
classroom: r.classroom,
|
||||
commission: r.commission,
|
||||
@@ -227,7 +359,7 @@ const handleTodaySchedule = async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Compute stats
|
||||
// Computar estadísticas
|
||||
const confirmed = reservations.filter(r => r.status === 'CONFIRMED').length;
|
||||
const pending = reservations.filter(r => r.status === 'PENDING').length;
|
||||
const occupied_classrooms = new Set(reservations.map(r => r.classroom_id).filter(Boolean)).size;
|
||||
@@ -245,6 +377,7 @@ const handleTodaySchedule = async (req, res) => {
|
||||
res.render('schedule/today', {
|
||||
title: 'Cartelera del Día - Edu-Space Admin',
|
||||
reservations,
|
||||
grouped_slots,
|
||||
time_blocks,
|
||||
stats,
|
||||
today: todayStr,
|
||||
@@ -263,6 +396,7 @@ const handleTodaySchedule = async (req, res) => {
|
||||
res.render('schedule/today', {
|
||||
title: 'Cartelera del Día (Offline)',
|
||||
reservations: [],
|
||||
grouped_slots: [],
|
||||
time_blocks: {},
|
||||
stats: { total_reservations: 0, confirmed: 0, pending: 0, occupied_classrooms: 0, total_classrooms: 59 },
|
||||
today: fallbackToday,
|
||||
@@ -461,9 +595,11 @@ const handleViewReservation = async (req, res) => {
|
||||
|
||||
const response = await req.apiClient.get(`/reservations/${id}`);
|
||||
const r = response.data;
|
||||
const formatted = formatReservationDates(r);
|
||||
|
||||
const resObj = {
|
||||
...r,
|
||||
...formatted,
|
||||
status: {
|
||||
value: (r.status || 'CONFIRMED').toUpperCase(),
|
||||
toString: () => (r.status || 'CONFIRMED').toUpperCase()
|
||||
|
||||
Reference in New Issue
Block a user