feat(benefits-reception): add institutional benefits, QR digital card & reception access control (SDD-012 v3.8.39)

This commit is contained in:
2026-10-27 23:34:57 -03:00
parent e45eb972dd
commit e5e6bfa094
30 changed files with 2994 additions and 11 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "frontend",
"version": "3.8.38",
"version": "3.8.39",
"description": "",
"main": "index.js",
"scripts": {
+10 -3
View File
@@ -86,9 +86,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), {
});
// Versiones institucionales del sistema
const APP_VERSION = '3.8.38';
const FRONTEND_VERSION = '3.8.38';
const BACKEND_VERSION = '3.8.38';
const APP_VERSION = '3.8.39';
const FRONTEND_VERSION = '3.8.39';
const BACKEND_VERSION = '3.8.39';
env.addGlobal('app_version', APP_VERSION);
env.addGlobal('frontend_version', FRONTEND_VERSION);
@@ -311,6 +311,9 @@ const scheduleRoutes = require('./routes/schedule');
const buildingsRoutes = require('./routes/buildings');
const adminRoutes = require('./routes/admin');
const mySubjectsRoutes = require('./routes/my_subjects');
const benefitsRoutes = require('./routes/benefits');
const receptionRoutes = require('./routes/reception');
const credentialRoutes = require('./routes/credential');
// Proxy transparente hacia la API REST de FastAPI para llamadas AJAX frontend
app.use('/api/v1', async (req, res) => {
@@ -403,6 +406,10 @@ app.use('/buildings', buildingsRoutes);
app.use('/admin', adminRoutes);
app.use('/my_subjects', mySubjectsRoutes);
app.use('/mis-materias', mySubjectsRoutes);
app.use('/benefits', benefitsRoutes);
app.use('/reception', receptionRoutes);
app.use('/credential', credentialRoutes);
app.use('/credencial', credentialRoutes);
// Redirección de enlaces heredados de Jinja /main/dashboard preservando query params
app.get(['/main/dashboard', '/main'], (req, res) => {
@@ -7,6 +7,7 @@ const buildUserSession = (decoded) => {
const isBedelia = roleStr === 'bedelia';
const isDocente = roleStr === 'docente' || roleStr === 'profesor';
const isAlumno = roleStr === 'alumno' || roleStr === 'estudiante';
const isRecepcion = roleStr === 'recepcion' || roleStr === 'recepción' || roleStr === 'seguridad';
const canManage = isAdmin || isBedelia;
let badgeClass = 'bg-primary text-white';
@@ -25,6 +26,10 @@ const buildUserSession = (decoded) => {
badgeClass = 'bg-success text-white';
badgeIcon = 'bi-mortarboard';
badgeLabel = 'Alumno';
} else if (isRecepcion) {
badgeClass = 'bg-secondary text-white';
badgeIcon = 'bi-qr-code-scan';
badgeLabel = 'Recepción';
}
return {
@@ -39,6 +44,7 @@ const buildUserSession = (decoded) => {
is_bedelia: () => isBedelia,
is_docente: () => isDocente,
is_alumno: () => isAlumno,
is_recepcion: () => isRecepcion,
can_manage: () => canManage,
has_role: (r) => roleStr === (r || '').toLowerCase(),
has_permission: (module, action) => {
+202
View File
@@ -0,0 +1,202 @@
const express = require('express');
const router = express.Router();
const { requireAuth } = require('../middlewares/authMiddleware');
router.use(requireAuth);
const getNormalizedRole = (user) => {
const roleStr = (user?.role || '').toLowerCase();
if (roleStr.includes('admin')) return 'admin';
if (roleStr.includes('bedel')) return 'bedelia';
if (roleStr.includes('docent') || roleStr.includes('prof')) return 'docente';
if (roleStr.includes('recep')) return 'recepcion';
return 'alumno';
};
// GET /benefits — Catálogo interactivo para Alumnos, Docentes y Staff
router.get('/', async (req, res) => {
const role = getNormalizedRole(req.user);
const category = req.query.category || '';
const search = req.query.search || '';
let benefits = [];
let categories = [];
try {
const resp = await req.apiClient.get('/benefits', {
params: {
role,
category: category || undefined,
search: search || undefined,
active_only: true
}
});
if (resp.data) {
benefits = resp.data.items || [];
categories = resp.data.categories || [];
}
} catch (err) {
console.warn('Benefits catalog fetch notice:', err.message);
}
res.render('benefits/catalog', {
title: 'Club de Beneficios & Convenios — Edu-Space',
benefits,
categories,
currentCategory: category,
searchQuery: search,
userRole: role,
canManage: role === 'admin' || role === 'bedelia'
});
});
// GET /benefits/manage — Panel de Gestión ABM para Bedelía y Administradores
router.get('/manage', async (req, res) => {
const role = getNormalizedRole(req.user);
if (role !== 'admin' && role !== 'bedelia') {
return res.status(403).redirect('/benefits');
}
let benefits = [];
let buildings = [];
let categories = [];
try {
const [respBenefits, respBuildings] = await Promise.all([
req.apiClient.get('/benefits', { params: { active_only: false } }),
req.apiClient.get('/buildings')
]);
if (respBenefits.data) {
benefits = respBenefits.data.items || [];
categories = respBenefits.data.categories || [];
}
if (respBuildings.data) {
buildings = respBuildings.data.buildings || respBuildings.data || [];
}
} catch (err) {
console.warn('Benefits manage fetch notice:', err.message);
}
res.render('benefits/manage', {
title: 'Gestión de Convenios & Beneficios — Bedelía',
benefits,
buildings,
categories,
userRole: role
});
});
// POST /benefits — Creación de nuevo convenio
router.post('/', async (req, res) => {
const role = getNormalizedRole(req.user);
if (role !== 'admin' && role !== 'bedelia') {
return res.status(403).json({ error: 'Acceso no autorizado' });
}
try {
const payload = {
title: req.body.title,
partner_name: req.body.partner_name,
category: req.body.category || 'GENERAL',
discount_label: req.body.discount_label,
description: req.body.description || null,
terms_conditions: req.body.terms_conditions || null,
target_roles: req.body.target_roles || 'ALL',
building_id: req.body.building_id ? parseInt(req.body.building_id, 10) : null,
coupon_code: req.body.coupon_code || null,
valid_from: req.body.valid_from || new Date().toISOString().split('T')[0],
valid_until: req.body.valid_until || null,
is_active: req.body.is_active === 'true' || req.body.is_active === true || req.body.is_active === 'on',
image_url: req.body.image_url || null
};
const resp = await req.apiClient.post('/benefits', payload);
if (req.xhr || req.headers.accept?.includes('application/json')) {
return res.status(201).json(resp.data);
}
res.redirect('/benefits/manage?msg=created');
} catch (err) {
console.error('Error creating benefit:', err.response?.data || err.message);
if (req.xhr || req.headers.accept?.includes('application/json')) {
return res.status(err.response?.status || 500).json(err.response?.data || { error: err.message });
}
res.redirect('/benefits/manage?err=' + encodeURIComponent(err.response?.data?.detail || 'Error al guardar'));
}
});
// POST /benefits/:id/edit — Edición de convenio
router.post('/:id/edit', async (req, res) => {
const role = getNormalizedRole(req.user);
if (role !== 'admin' && role !== 'bedelia') {
return res.status(403).json({ error: 'Acceso no autorizado' });
}
try {
const benefitId = req.params.id;
const payload = {
title: req.body.title,
partner_name: req.body.partner_name,
category: req.body.category,
discount_label: req.body.discount_label,
description: req.body.description || null,
terms_conditions: req.body.terms_conditions || null,
target_roles: req.body.target_roles,
building_id: req.body.building_id ? parseInt(req.body.building_id, 10) : null,
coupon_code: req.body.coupon_code || null,
valid_from: req.body.valid_from,
valid_until: req.body.valid_until || null,
is_active: req.body.is_active === 'true' || req.body.is_active === true || req.body.is_active === 'on',
image_url: req.body.image_url || null
};
const resp = await req.apiClient.put(`/benefits/${benefitId}`, payload);
if (req.xhr || req.headers.accept?.includes('application/json')) {
return res.json(resp.data);
}
res.redirect('/benefits/manage?msg=updated');
} catch (err) {
console.error('Error updating benefit:', err.response?.data || err.message);
if (req.xhr || req.headers.accept?.includes('application/json')) {
return res.status(err.response?.status || 500).json(err.response?.data || { error: err.message });
}
res.redirect('/benefits/manage?err=' + encodeURIComponent(err.response?.data?.detail || 'Error al actualizar'));
}
});
// POST /benefits/:id/toggle — Switch de publicación rápido
router.post('/:id/toggle', async (req, res) => {
const role = getNormalizedRole(req.user);
if (role !== 'admin' && role !== 'bedelia') {
return res.status(403).json({ error: 'Acceso no autorizado' });
}
try {
const resp = await req.apiClient.patch(`/benefits/${req.params.id}/toggle-status`);
res.json(resp.data);
} catch (err) {
res.status(err.response?.status || 500).json(err.response?.data || { error: err.message });
}
});
// POST /benefits/:id/delete — Eliminación
router.post('/:id/delete', async (req, res) => {
const role = getNormalizedRole(req.user);
if (role !== 'admin' && role !== 'bedelia') {
return res.status(403).json({ error: 'Acceso no autorizado' });
}
try {
await req.apiClient.delete(`/benefits/${req.params.id}`);
if (req.xhr || req.headers.accept?.includes('application/json')) {
return res.json({ success: true });
}
res.redirect('/benefits/manage?msg=deleted');
} catch (err) {
if (req.xhr || req.headers.accept?.includes('application/json')) {
return res.status(err.response?.status || 500).json({ error: err.message });
}
res.redirect('/benefits/manage?err=error_deleting');
}
});
module.exports = router;
+29
View File
@@ -0,0 +1,29 @@
const express = require('express');
const router = express.Router();
const { requireAuth } = require('../middlewares/authMiddleware');
router.use(requireAuth);
router.get(['/my-card', '/', '/mi-credencial'], async (req, res) => {
let qrToken = '';
let expiresInHours = 72;
try {
const resp = await req.apiClient.get('/reception/my-qr-token');
if (resp.data) {
qrToken = resp.data.qr_token || '';
expiresInHours = resp.data.expires_in_hours || 72;
}
} catch (err) {
console.warn('QR token generation notice:', err.message);
}
res.render('credential/card', {
title: 'Mi Credencial Digital — UniCABA',
user: req.user,
qrToken,
expiresInHours
});
});
module.exports = router;
+82
View File
@@ -0,0 +1,82 @@
const express = require('express');
const router = express.Router();
const { requireAuth } = require('../middlewares/authMiddleware');
router.use(requireAuth);
const getNormalizedRole = (user) => {
const roleStr = (user?.role || '').toLowerCase();
if (roleStr.includes('admin')) return 'admin';
if (roleStr.includes('bedel')) return 'bedelia';
if (roleStr.includes('recep')) return 'recepcion';
return roleStr;
};
// GET /reception/scanner — Consola de Escaneo y Control de Acceso
router.get('/scanner', async (req, res) => {
const role = getNormalizedRole(req.user);
if (role !== 'admin' && role !== 'bedelia' && role !== 'recepcion') {
return res.status(403).redirect('/dashboard');
}
let buildings = [];
let recentLogs = [];
try {
const [respBld, respLogs] = await Promise.all([
req.apiClient.get('/buildings'),
req.apiClient.get('/reception/recent-logs', { params: { limit: 15 } })
]);
buildings = respBld.data?.buildings || respBld.data || [];
recentLogs = respLogs.data?.items || [];
} catch (err) {
console.warn('Reception scanner init notice:', err.message);
}
res.render('reception/scanner', {
title: 'Control de Acceso QR — Recepción & Seguridad',
buildings,
recentLogs,
userRole: role
});
});
// POST /reception/verify — Endpoint AJAX de verificación de código QR
router.post('/verify', async (req, res) => {
const role = getNormalizedRole(req.user);
if (role !== 'admin' && role !== 'bedelia' && role !== 'recepcion') {
return res.status(403).json({ error: 'Acceso no autorizado' });
}
try {
const payload = {
qr_token: req.body.qr_token,
building_id: req.body.building_id ? parseInt(req.body.building_id, 10) : null,
notes: req.body.notes || null
};
const resp = await req.apiClient.post('/reception/verify-qr', payload);
return res.json(resp.data);
} catch (err) {
console.error('Error verifying QR in reception:', err.response?.data || err.message);
return res.status(err.response?.status || 500).json(
err.response?.data || { status: 'DENEGADO', message: 'Error de comunicación con el validador' }
);
}
});
// GET /reception/recent-logs — Consulta de historial en vivo
router.get('/recent-logs', async (req, res) => {
try {
const buildingId = req.query.building_id;
const resp = await req.apiClient.get('/reception/recent-logs', {
params: {
building_id: buildingId || undefined,
limit: 25
}
});
return res.json(resp.data);
} catch (err) {
return res.status(err.response?.status || 500).json({ error: err.message });
}
});
module.exports = router;
+34
View File
@@ -1482,6 +1482,8 @@
{% set user_role = 'bedelia' %}
{% elif 'docent' in raw_user_role or 'prof' in raw_user_role %}
{% set user_role = 'docente' %}
{% elif 'recep' in raw_user_role %}
{% set user_role = 'recepcion' %}
{% else %}
{% set user_role = 'alumno' %}
{% endif %}
@@ -1553,6 +1555,8 @@
<li><a class="nav-link" href="/admin/milestone_types_list"><i class="bi bi-bookmark-star me-1"></i>Tipos de Hitos</a></li>
<li><a class="nav-link" href="/admin/google_sheets_import"><i class="bi bi-file-earmark-spreadsheet me-1"></i>Sincro Sheets</a></li>
<li><a class="nav-link" href="/admin/audit_logs"><i class="bi bi-journal-text me-1"></i>Auditoría</a></li>
<li><a class="nav-link text-warning" href="/benefits/manage"><i class="bi bi-tag me-1"></i>Convenios &amp; Beneficios</a></li>
<li><a class="nav-link text-info" href="/reception/scanner"><i class="bi bi-qr-code-scan me-1"></i>Control de Acceso QR</a></li>
<li><a class="nav-link text-primary fw-semibold" href="/admin/settings"><i class="bi bi-gear-wide-connected me-1"></i>Config. Global</a></li>
</ul>
</div>
@@ -1618,6 +1622,8 @@
<ul class="sidebar-submenu">
<li><a class="nav-link" href="/admin/google_sheets_import"><i class="bi bi-file-earmark-spreadsheet me-1"></i>Importador Google Sheets</a></li>
<li><a class="nav-link" href="/admin/milestone_types_list"><i class="bi bi-bookmark-star me-1"></i>Tipos de Hitos Evaluativos</a></li>
<li><a class="nav-link text-warning fw-semibold" href="/benefits/manage"><i class="bi bi-tag me-1"></i>Convenios &amp; Beneficios</a></li>
<li><a class="nav-link text-info fw-semibold" href="/reception/scanner"><i class="bi bi-qr-code-scan me-1"></i>Control de Acceso QR</a></li>
</ul>
</div>
</li>
@@ -1665,6 +1671,13 @@
</ul>
</div>
</li>
<li class="sidebar-section-header">Servicios &amp; Beneficios</li>
<li class="nav-item">
<a class="nav-link" href="/benefits"><i class="bi bi-tags text-warning"></i> <span class="nav-text">Club de Beneficios</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/credential/my-card"><i class="bi bi-person-badge text-primary"></i> <span class="nav-text">Mi Credencial QR</span></a>
</li>
{% else %}
<!-- ALUMNO / ESTUDIANTE -->
@@ -1697,6 +1710,27 @@
</ul>
</div>
</li>
<li class="sidebar-section-header">Servicios &amp; Beneficios</li>
<li class="nav-item">
<a class="nav-link" href="/benefits"><i class="bi bi-tags text-warning"></i> <span class="nav-text">Club de Beneficios</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/credential/my-card"><i class="bi bi-person-badge text-primary"></i> <span class="nav-text">Mi Credencial QR</span></a>
</li>
{% elif user_role == 'recepcion' %}
<!-- RECEPCIÓN / CONTROL DE ACCESO -->
<li class="sidebar-section-header">Control de Acceso</li>
<li class="nav-item">
<a class="nav-link" href="/reception/scanner"><i class="bi bi-qr-code-scan text-primary"></i> <span class="nav-text">Escáner de Acceso QR</span></a>
</li>
<li class="sidebar-section-header">Cartelera &amp; Aulas</li>
<li class="nav-item">
<a class="nav-link" href="/schedule/today_schedule"><i class="bi bi-calendar-day text-info"></i> <span class="nav-text">Cartelera del Día</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/classrooms/list_classrooms?view_mode=physical"><i class="bi bi-door-closed text-success"></i> <span class="nav-text">Aulas Presenciales</span></a>
</li>
{% endif %}
</ul>
</div>
+206
View File
@@ -0,0 +1,206 @@
{% extends "base.html" %}
{% block title %}Club de Beneficios & Convenios — UniCABA{% endblock %}
{% block content %}
<div class="container-fluid py-3 px-lg-4">
<!-- Hero / Banner Institucional -->
<div class="card border-0 rounded-4 p-4 p-lg-5 mb-4 shadow-sm text-white position-relative overflow-hidden"
style="background: linear-gradient(135deg, #7E22CE 0%, #B43E8E 50%, #EC4899 100%);">
<div class="position-relative z-1" style="max-width: 680px;">
<span class="badge bg-white text-dark rounded-pill px-3 py-1 fw-bold small text-uppercase mb-2 shadow-sm">
<i class="bi bi-stars text-warning me-1"></i> Comunidad UniCABA
</span>
<h1 class="display-6 fw-bold mb-2">Club de Beneficios &amp; Convenios</h1>
<p class="lead fs-6 mb-3 opacity-90">Aprovecha descuentos exclusivos en cafeterías, librerías, tecnología y comercios presentando tu credencial universitaria digital.</p>
<div class="d-flex flex-wrap gap-2">
<a href="/credential/my-card" class="btn btn-light btn-sm rounded-pill px-4 fw-semibold text-primary shadow-sm">
<i class="bi bi-qr-code me-1"></i> Abrir Mi Credencial QR
</a>
{% if canManage %}
<a href="/benefits/manage" class="btn btn-outline-light btn-sm rounded-pill px-3">
<i class="bi bi-gear me-1"></i> Gestionar Convenios (Bedelía)
</a>
{% endif %}
</div>
</div>
<div class="position-absolute end-0 bottom-0 opacity-25 d-none d-md-block pe-4 pb-2">
<i class="bi bi-bag-heart-fill" style="font-size: 14rem;"></i>
</div>
</div>
<!-- Barra de Búsqueda y Filtros de Categoría -->
<div class="card border-0 shadow-sm rounded-4 p-3 mb-4">
<form method="GET" action="/benefits" class="row g-2 align-items-center">
<div class="col-md-5 col-12">
<div class="input-group">
<span class="input-group-text bg-transparent border-end-0 text-muted"><i class="bi bi-search"></i></span>
<input type="text" name="search" class="form-control border-start-0 ps-0" placeholder="Buscar por cafetería, librería o descuento..." value="{{ searchQuery }}">
</div>
</div>
<div class="col-md-7 col-12">
<div class="d-flex flex-wrap gap-1 align-items-center justify-content-md-end">
<a href="/benefits{% if searchQuery %}?search={{ searchQuery }}{% endif %}" class="btn btn-sm rounded-pill px-3 {% if not currentCategory %}btn-primary{% else %}btn-outline-secondary{% endif %}">
Todos
</a>
{% for cat in categories %}
<a href="/benefits?category={{ cat }}{% if searchQuery %}&search={{ searchQuery }}{% endif %}" class="btn btn-sm rounded-pill px-3 {% if currentCategory == cat %}btn-primary{% else %}btn-outline-secondary{% endif %}">
{% if cat == 'GASTRONOMIA' %}☕ Cafetería
{% elif cat == 'LIBRERIA' %}📚 Librería
{% elif cat == 'TECNOLOGIA' %}💻 Tecnología
{% elif cat == 'SALUD_DEPORTE' %}🏋️ Salud &amp; Deportes
{% elif cat == 'IDIOMAS' %}🌍 Idiomas
{% elif cat == 'CULTURA' %}🎭 Cultura
{% else %}🏷️ {{ cat }}
{% endif %}
</a>
{% endfor %}
</div>
</div>
</form>
</div>
<!-- Grilla de Tarjetas de Beneficios -->
<div class="row g-4" id="benefitsGrid">
{% if benefits and benefits | length > 0 %}
{% for b in benefits %}
<div class="col-12 col-md-6 col-xl-4">
<div class="card border-0 shadow-sm rounded-4 h-100 overflow-hidden benefit-card transition-all" style="transition: transform 0.2s ease, box-shadow 0.2s ease;">
<div class="card-body p-4 d-flex flex-column justify-content-between">
<div>
<!-- Header de Tarjeta -->
<div class="d-flex align-items-start justify-content-between gap-2 mb-3">
<div class="d-flex align-items-center gap-3">
<div class="rounded-4 p-2 bg-primary-subtle text-primary d-flex align-items-center justify-content-center shadow-sm" style="width: 48px; height: 48px;">
{% if b.category == 'GASTRONOMIA' %}
<i class="bi bi-cup-hot fs-4"></i>
{% elif b.category == 'LIBRERIA' %}
<i class="bi bi-book fs-4"></i>
{% elif b.category == 'TECNOLOGIA' %}
<i class="bi bi-laptop fs-4"></i>
{% elif b.category == 'SALUD_DEPORTE' %}
<i class="bi bi-heart-pulse fs-4"></i>
{% else %}
<i class="bi bi-tag fs-4"></i>
{% endif %}
</div>
<div>
<span class="badge bg-secondary-subtle text-secondary-emphasis rounded-pill px-2 py-0 small mb-1">
{{ b.category }}
</span>
<h5 class="fw-bold mb-0 text-dark">{{ b.partner_name }}</h5>
</div>
</div>
<span class="badge bg-danger text-white rounded-pill px-3 py-2 fw-bold fs-6 shadow-sm">
{{ b.discount_label }}
</span>
</div>
<h6 class="fw-semibold text-primary mb-2">{{ b.title }}</h6>
<p class="text-muted small mb-3" style="min-height: 40px;">
{{ b.description or 'Presenta tu credencial universitaria en caja para aplicar el beneficio acordado.' }}
</p>
</div>
<!-- Footer de Tarjeta -->
<div class="pt-3 border-top border-light-subtle d-flex align-items-center justify-content-between">
<span class="text-muted small">
<i class="bi bi-geo-alt-fill text-danger me-1"></i>{{ b.building_name or 'Todas las Sedes' }}
</span>
<button type="button" class="btn btn-primary btn-sm rounded-pill px-3 shadow-sm"
onclick='openRedeemModal({{ b | tojson | safe }})'>
<i class="bi bi-ticket-perforated me-1"></i> Ver Beneficio
</button>
</div>
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="col-12 py-5 text-center text-muted">
<i class="bi bi-tags display-3 text-secondary opacity-50 mb-3 d-block"></i>
<h5>No se encontraron promociones en esta categoría</h5>
<p class="small text-muted mb-3">Intenta cambiar los filtros de búsqueda o consulta a UdeCi para conocer próximos convenios.</p>
<a href="/benefits" class="btn btn-outline-primary btn-sm rounded-pill px-4">Ver Todos los Beneficios</a>
</div>
{% endif %}
</div>
</div>
<!-- Modal de Detalle y Canje -->
<div class="modal fade" id="redeemModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content border-0 shadow-lg rounded-4 overflow-hidden">
<div class="modal-header bg-primary text-white py-3 px-4">
<h5 class="modal-title fw-bold" id="redeemTitle">Detalle del Beneficio</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body p-4 text-center">
<div class="rounded-circle bg-danger-subtle text-danger mx-auto d-flex align-items-center justify-content-center mb-3" style="width: 72px; height: 72px;">
<i class="bi bi-gift-fill fs-2"></i>
</div>
<h4 class="fw-bold mb-1" id="redeemPartner">Comercio</h4>
<div class="badge bg-danger fs-5 px-3 py-1 rounded-pill mb-3" id="redeemDiscount">20% OFF</div>
<p class="text-muted small px-3 mb-3" id="redeemDesc"></p>
<div class="p-3 bg-light rounded-4 border mb-3 text-start" id="couponBox">
<div class="small text-muted text-uppercase fw-bold mb-1">Cupón de Descuento</div>
<div class="d-flex align-items-center justify-content-between">
<code class="fs-5 fw-bold text-primary" id="redeemCoupon">UNICABA-20</code>
<button type="button" class="btn btn-sm btn-outline-primary rounded-pill px-3" onclick="copyCoupon()">
<i class="bi bi-copy me-1"></i> Copiar
</button>
</div>
</div>
<div class="alert alert-info rounded-4 small text-start mb-3">
<i class="bi bi-info-circle-fill me-1"></i> <strong>¿Cómo usar este beneficio?</strong>
<div class="mt-1" id="redeemTerms">Presenta tu Credencial Universitaria Digital UniCABA al momento de solicitar la cuenta o pagar en caja.</div>
</div>
<a href="/credential/my-card" class="btn btn-outline-primary rounded-pill w-100 py-2 fw-semibold">
<i class="bi bi-qr-code me-1"></i> Mostrar Mi Credencial QR al Comercio
</a>
</div>
</div>
</div>
</div>
<script>
function openRedeemModal(b) {
document.getElementById('redeemTitle').innerText = b.title;
document.getElementById('redeemPartner').innerText = b.partner_name;
document.getElementById('redeemDiscount').innerText = b.discount_label;
document.getElementById('redeemDesc').innerText = b.description || 'Promoción exclusiva para la comunidad universitaria de UniCABA.';
document.getElementById('redeemTerms').innerText = b.terms_conditions || 'Válido presentando tu credencial digital con código QR.';
const couponBox = document.getElementById('couponBox');
if (b.coupon_code) {
couponBox.style.display = 'block';
document.getElementById('redeemCoupon').innerText = b.coupon_code;
} else {
couponBox.style.display = 'none';
}
const modal = new bootstrap.Modal(document.getElementById('redeemModal'));
modal.show();
}
function copyCoupon() {
const code = document.getElementById('redeemCoupon').innerText;
if (navigator.clipboard) {
navigator.clipboard.writeText(code).then(() => {
alert('¡Código de cupón copiado al portapapeles!');
});
}
}
</script>
<style>
.benefit-card:hover {
transform: translateY(-4px);
box-shadow: 0 12px 28px rgba(0,0,0,0.08) !important;
}
</style>
{% endblock %}
+403
View File
@@ -0,0 +1,403 @@
{% extends "base.html" %}
{% block title %}Gestión de Convenios & Beneficios — Bedelía{% endblock %}
{% block content %}
<div class="container-fluid py-3 px-lg-4">
<!-- Header de Página -->
<div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-4">
<div>
<div class="d-flex align-items-center gap-2">
<span class="badge bg-warning-subtle text-warning-emphasis border border-warning-subtle rounded-pill px-3 py-1 fw-semibold">
<i class="bi bi-tag-fill me-1"></i> Bedelía &amp; Servicios
</span>
<span class="text-muted small">Módulo SDD-012</span>
</div>
<h1 class="h3 fw-bold mt-1 mb-0">Gestión de Convenios &amp; Beneficios</h1>
<p class="text-muted small mb-0">Administra las promociones comerciales, descuentos en cafeterías, librerías y beneficios para la comunidad UniCABA.</p>
</div>
<div class="d-flex align-items-center gap-2">
<a href="/benefits" class="btn btn-outline-secondary btn-sm rounded-pill px-3">
<i class="bi bi-eye me-1"></i> Ver Catálogo Público
</a>
<button type="button" class="btn btn-primary btn-sm rounded-pill px-3 shadow-sm" data-bs-toggle="modal" data-bs-target="#benefitModal" onclick="openCreateModal()">
<i class="bi bi-plus-lg me-1"></i> Nuevo Convenio
</button>
</div>
</div>
<!-- Alertas de Estado -->
<div id="alertContainer"></div>
<!-- Métricas Rápidas -->
<div class="row g-3 mb-4">
<div class="col-6 col-md-3">
<div class="card border-0 shadow-sm rounded-4 h-100 p-3">
<div class="d-flex align-items-center justify-content-between">
<div>
<span class="text-muted small text-uppercase fw-bold">Total Convenios</span>
<h3 class="fw-bold mb-0 text-primary mt-1">{{ benefits | length }}</h3>
</div>
<div class="p-3 bg-primary-subtle text-primary rounded-circle">
<i class="bi bi-tags fs-4"></i>
</div>
</div>
</div>
</div>
<div class="col-6 col-md-3">
<div class="card border-0 shadow-sm rounded-4 h-100 p-3">
<div class="d-flex align-items-center justify-content-between">
<div>
<span class="text-muted small text-uppercase fw-bold">Activos</span>
<h3 class="fw-bold mb-0 text-success mt-1" id="activeCount">
{% set active_count = 0 %}
{% for b in benefits %}
{% if b.is_active %}{% set active_count = active_count + 1 %}{% endif %}
{% endfor %}
{{ active_count }}
</h3>
</div>
<div class="p-3 bg-success-subtle text-success rounded-circle">
<i class="bi bi-check-circle fs-4"></i>
</div>
</div>
</div>
</div>
<div class="col-6 col-md-3">
<div class="card border-0 shadow-sm rounded-4 h-100 p-3">
<div class="d-flex align-items-center justify-content-between">
<div>
<span class="text-muted small text-uppercase fw-bold">Categorías</span>
<h3 class="fw-bold mb-0 text-info mt-1">{{ categories | length }}</h3>
</div>
<div class="p-3 bg-info-subtle text-info rounded-circle">
<i class="bi bi-grid fs-4"></i>
</div>
</div>
</div>
</div>
<div class="col-6 col-md-3">
<div class="card border-0 shadow-sm rounded-4 h-100 p-3">
<div class="d-flex align-items-center justify-content-between">
<div>
<span class="text-muted small text-uppercase fw-bold">Sedes</span>
<h3 class="fw-bold mb-0 text-warning mt-1">{{ buildings | length }}</h3>
</div>
<div class="p-3 bg-warning-subtle text-warning rounded-circle">
<i class="bi bi-buildings fs-4"></i>
</div>
</div>
</div>
</div>
</div>
<!-- Tabla Principal de Convenios -->
<div class="card border-0 shadow-sm rounded-4 overflow-hidden">
<div class="card-header bg-body border-0 py-3 px-4 d-flex flex-wrap align-items-center justify-content-between gap-3">
<h5 class="fw-bold mb-0">Nómina de Convenios Registrados</h5>
<div class="d-flex align-items-center gap-2">
<input type="text" id="tableFilter" class="form-control form-control-sm rounded-pill px-3" placeholder="Filtrar por comercio o título..." style="min-width: 240px;">
</div>
</div>
<div class="table-responsive">
<table class="table table-hover align-middle mb-0" id="benefitsTable">
<thead class="table-light">
<tr>
<th class="ps-4">Convenio &amp; Comercio</th>
<th>Categoría</th>
<th>Descuento</th>
<th>Sede</th>
<th>Destinatarios</th>
<th>Vigencia</th>
<th>Cupón</th>
<th class="text-center">Estado</th>
<th class="text-end pe-4">Acciones</th>
</tr>
</thead>
<tbody>
{% if benefits and benefits | length > 0 %}
{% for b in benefits %}
<tr id="benefit-row-{{ b.id }}" data-search="{{ b.title | lower }} {{ b.partner_name | lower }} {{ b.category | lower }}">
<td class="ps-4">
<div class="d-flex align-items-center gap-3">
<div class="rounded-3 p-2 bg-primary-subtle text-primary d-flex align-items-center justify-content-center" style="width: 42px; height: 42px;">
{% if b.category == 'GASTRONOMIA' %}
<i class="bi bi-cup-hot fs-5"></i>
{% elif b.category == 'LIBRERIA' %}
<i class="bi bi-book fs-5"></i>
{% elif b.category == 'TECNOLOGIA' %}
<i class="bi bi-laptop fs-5"></i>
{% elif b.category == 'SALUD_DEPORTE' %}
<i class="bi bi-heart-pulse fs-5"></i>
{% else %}
<i class="bi bi-tag fs-5"></i>
{% endif %}
</div>
<div>
<div class="fw-bold text-dark">{{ b.title }}</div>
<div class="small text-muted"><i class="bi bi-shop me-1"></i>{{ b.partner_name }}</div>
</div>
</div>
</td>
<td>
<span class="badge bg-secondary-subtle text-secondary-emphasis rounded-pill px-2 py-1 small">
{{ b.category }}
</span>
</td>
<td>
<span class="badge bg-danger-subtle text-danger border border-danger-subtle rounded-pill px-2 py-1 fw-bold">
{{ b.discount_label }}
</span>
</td>
<td>
<span class="small text-muted">
<i class="bi bi-geo-alt me-1"></i>{{ b.building_name or 'Todas las Sedes' }}
</span>
</td>
<td>
{% if b.target_roles == 'ALL' %}
<span class="badge bg-info-subtle text-info rounded-pill px-2">Todos</span>
{% elif 'ALUMNO' in b.target_roles and 'DOCENTE' in b.target_roles %}
<span class="badge bg-primary-subtle text-primary rounded-pill px-2">Alumnos &amp; Docentes</span>
{% elif 'ALUMNO' in b.target_roles %}
<span class="badge bg-success-subtle text-success rounded-pill px-2">Solo Alumnos</span>
{% elif 'DOCENTE' in b.target_roles %}
<span class="badge bg-warning-subtle text-warning-emphasis rounded-pill px-2">Solo Docentes</span>
{% else %}
<span class="badge bg-secondary-subtle text-secondary rounded-pill px-2">{{ b.target_roles }}</span>
{% endif %}
</td>
<td>
<div class="small">
<div><i class="bi bi-calendar-check me-1 text-success"></i>Desde: {{ b.valid_from }}</div>
{% if b.valid_until %}
<div><i class="bi bi-calendar-x me-1 text-danger"></i>Hasta: {{ b.valid_until }}</div>
{% else %}
<div class="text-muted"><i class="bi bi-infinity me-1"></i>Indefinido</div>
{% endif %}
</div>
</td>
<td>
{% if b.coupon_code %}
<code class="px-2 py-1 bg-light rounded text-primary fw-bold small border">{{ b.coupon_code }}</code>
{% else %}
<span class="text-muted small">Credencial</span>
{% endif %}
</td>
<td class="text-center">
<div class="form-check form-switch d-inline-block">
<input class="form-check-input" type="checkbox" role="switch" id="switch-{{ b.id }}" {% if b.is_active %}checked{% endif %} onchange="toggleStatus({{ b.id }})">
</div>
</td>
<td class="text-end pe-4">
<div class="btn-group btn-group-sm">
<button type="button" class="btn btn-outline-secondary rounded-start-pill" title="Editar" onclick='openEditModal({{ b | tojson | safe }})'>
<i class="bi bi-pencil"></i>
</button>
<button type="button" class="btn btn-outline-danger rounded-end-pill" title="Eliminar" onclick="confirmDelete({{ b.id }}, '{{ b.title }}')">
<i class="bi bi-trash"></i>
</button>
</div>
</td>
</tr>
{% endfor %}
{% else %}
<tr>
<td colspan="9" class="text-center py-5 text-muted">
<i class="bi bi-tags display-4 d-block mb-3 text-secondary opacity-50"></i>
<h5>No hay convenios cargados aún</h5>
<p class="small text-muted mb-3">Comienza creando promociones de cafetería, librerías y comercios para los alumnos y docentes.</p>
<button type="button" class="btn btn-primary btn-sm rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#benefitModal" onclick="openCreateModal()">
<i class="bi bi-plus-lg me-1"></i> Crear Primer Convenio
</button>
</td>
</tr>
{% endif %}
</tbody>
</table>
</div>
</div>
</div>
<!-- Modal de Creación / Edición -->
<div class="modal fade" id="benefitModal" tabindex="-1" aria-labelledby="benefitModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<div class="modal-content border-0 shadow-lg rounded-4 overflow-hidden">
<form id="benefitForm" method="POST" action="/benefits">
<div class="modal-header bg-primary text-white py-3 px-4">
<h5 class="modal-title fw-bold" id="benefitModalLabel">
<i class="bi bi-tag-fill me-2"></i> Nuevo Convenio Comercial
</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body p-4">
<input type="hidden" id="benefitId" name="benefitId">
<div class="row g-3">
<div class="col-md-7">
<label class="form-label small fw-bold">Título de la Promoción *</label>
<input type="text" class="form-control" id="title" name="title" required placeholder="Ej: 20% en Cafetería La Estación">
</div>
<div class="col-md-5">
<label class="form-label small fw-bold">Comercio / Entidad *</label>
<input type="text" class="form-control" id="partner_name" name="partner_name" required placeholder="Ej: Café Martínez Central">
</div>
<div class="col-md-4">
<label class="form-label small fw-bold">Categoría *</label>
<select class="form-select" id="category" name="category" required>
<option value="GASTRONOMIA">☕ Gastronomía / Cafetería</option>
<option value="LIBRERIA">📚 Librería / Fotocopias</option>
<option value="TECNOLOGIA">💻 Tecnología &amp; Software</option>
<option value="SALUD_DEPORTE">🏋️ Salud &amp; Deportes</option>
<option value="IDIOMAS">🌍 Idiomas &amp; Cursos</option>
<option value="CULTURA">🎭 Cultura &amp; Entretenimiento</option>
<option value="GENERAL" selected>🏷️ General / Otros</option>
</select>
</div>
<div class="col-md-4">
<label class="form-label small fw-bold">Etiqueta de Descuento *</label>
<input type="text" class="form-control" id="discount_label" name="discount_label" required placeholder="Ej: 20% OFF / 2x1">
</div>
<div class="col-md-4">
<label class="form-label small fw-bold">Código de Cupón (Opcional)</label>
<input type="text" class="form-control" id="coupon_code" name="coupon_code" placeholder="Ej: UNICABA-20">
</div>
<div class="col-md-6">
<label class="form-label small fw-bold">Sede Aplicable</label>
<select class="form-select" id="building_id" name="building_id">
<option value="">Todas las Sedes</option>
{% for bld in buildings %}
<option value="{{ bld.id }}">{{ bld.name }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-6">
<label class="form-label small fw-bold">Destinatarios *</label>
<select class="form-select" id="target_roles" name="target_roles" required>
<option value="ALL">Todos (Alumnos, Docentes y Personal)</option>
<option value="ALUMNO,DOCENTE">Alumnos y Docentes</option>
<option value="ALUMNO">Solo Estudiantes</option>
<option value="DOCENTE">Solo Docentes</option>
</select>
</div>
<div class="col-md-6">
<label class="form-label small fw-bold">Fecha de Inicio *</label>
<input type="date" class="form-control" id="valid_from" name="valid_from" required>
</div>
<div class="col-md-6">
<label class="form-label small fw-bold">Fecha de Vencimiento (Opcional)</label>
<input type="date" class="form-control" id="valid_until" name="valid_until">
</div>
<div class="col-12">
<label class="form-label small fw-bold">Descripción del Beneficio</label>
<textarea class="form-control" id="description" name="description" rows="2" placeholder="Detalles de cómo aprovechar el beneficio en el local..."></textarea>
</div>
<div class="col-12">
<label class="form-label small fw-bold">Términos &amp; Condiciones</label>
<textarea class="form-control" id="terms_conditions" name="terms_conditions" rows="2" placeholder="Válido de lunes a viernes con credencial universitaria vigente..."></textarea>
</div>
<div class="col-12">
<div class="form-check form-switch mt-2">
<input class="form-check-input" type="checkbox" role="switch" id="is_active" name="is_active" checked>
<label class="form-check-label fw-semibold" for="is_active">Publicar inmediatamente en el catálogo de alumnos y docentes</label>
</div>
</div>
</div>
</div>
<div class="modal-footer bg-light py-3 px-4">
<button type="button" class="btn btn-outline-secondary rounded-pill px-4" data-bs-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary rounded-pill px-4" id="submitBtn">
<i class="bi bi-check-lg me-1"></i> Guardar Convenio
</button>
</div>
</form>
</div>
</div>
</div>
<script>
// Filtro en tiempo real de la tabla
document.getElementById('tableFilter').addEventListener('input', function(e) {
const val = e.target.value.toLowerCase().trim();
const rows = document.querySelectorAll('#benefitsTable tbody tr[data-search]');
rows.forEach(r => {
const txt = r.getAttribute('data-search');
r.style.display = txt.includes(val) ? '' : 'none';
});
});
function openCreateModal() {
document.getElementById('benefitModalLabel').innerHTML = '<i class="bi bi-tag-fill me-2"></i> Nuevo Convenio Comercial';
document.getElementById('benefitForm').action = '/benefits';
document.getElementById('benefitForm').reset();
document.getElementById('benefitId').value = '';
document.getElementById('valid_from').value = new Date().toISOString().split('T')[0];
document.getElementById('is_active').checked = true;
}
function openEditModal(b) {
document.getElementById('benefitModalLabel').innerHTML = '<i class="bi bi-pencil-fill me-2"></i> Editar Convenio Comercial';
document.getElementById('benefitForm').action = `/benefits/${b.id}/edit`;
document.getElementById('benefitId').value = b.id;
document.getElementById('title').value = b.title || '';
document.getElementById('partner_name').value = b.partner_name || '';
document.getElementById('category').value = b.category || 'GENERAL';
document.getElementById('discount_label').value = b.discount_label || '';
document.getElementById('coupon_code').value = b.coupon_code || '';
document.getElementById('building_id').value = b.building_id || '';
document.getElementById('target_roles').value = b.target_roles || 'ALL';
document.getElementById('valid_from').value = b.valid_from ? b.valid_from.split('T')[0] : '';
document.getElementById('valid_until').value = b.valid_until ? b.valid_until.split('T')[0] : '';
document.getElementById('description').value = b.description || '';
document.getElementById('terms_conditions').value = b.terms_conditions || '';
document.getElementById('is_active').checked = b.is_active;
const modal = new bootstrap.Modal(document.getElementById('benefitModal'));
modal.show();
}
async function toggleStatus(id) {
try {
const res = await fetch(`/benefits/${id}/toggle`, { method: 'POST' });
if (!res.ok) throw new Error('Error al cambiar estado');
const data = await res.json();
showAlert('Estado actualizado exitosamente.', 'success');
} catch (err) {
showAlert('No se pudo actualizar el estado: ' + err.message, 'danger');
}
}
async function confirmDelete(id, title) {
if (!confirm(`¿Estás seguro de que deseas eliminar el convenio "${title}"?`)) return;
try {
const res = await fetch(`/benefits/${id}/delete`, { method: 'POST', headers: { 'Accept': 'application/json' } });
if (res.ok) {
const row = document.getElementById(`benefit-row-${id}`);
if (row) row.remove();
showAlert(`Convenio "${title}" eliminado.`, 'info');
} else {
throw new Error('Error al eliminar');
}
} catch (err) {
showAlert('Error: ' + err.message, 'danger');
}
}
function showAlert(msg, type = 'info') {
const container = document.getElementById('alertContainer');
container.innerHTML = `
<div class="alert alert-${type} alert-dismissible fade show rounded-4 shadow-sm" role="alert">
<i class="bi bi-info-circle me-2"></i> ${msg}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
`;
setTimeout(() => { container.innerHTML = ''; }, 4000);
}
</script>
{% endblock %}
+129
View File
@@ -0,0 +1,129 @@
{% extends "base.html" %}
{% block title %}Mi Credencial Digital — UniCABA{% endblock %}
{% block content %}
<div class="container py-4">
<div class="row justify-content-center">
<div class="col-12 col-md-8 col-lg-6 col-xl-5">
<!-- Header -->
<div class="text-center mb-4">
<span class="badge bg-primary-subtle text-primary border border-primary-subtle rounded-pill px-3 py-1 fw-bold text-uppercase small">
<i class="bi bi-shield-check me-1"></i> Identidad Universitaria
</span>
<h1 class="h3 fw-bold mt-2 mb-1">Credencial Digital</h1>
<p class="text-muted small">Utiliza este código QR para ingresar a las sedes de UniCABA y acceder a los convenios comerciales.</p>
</div>
<!-- Tarjeta de Credencial Estilo Carnet Físico -->
<div class="card border-0 rounded-4 overflow-hidden shadow-lg text-white mb-4 position-relative"
style="background: linear-gradient(135deg, #1E1B4B 0%, #4338CA 50%, #B43E8E 100%);">
<!-- Banda Superior -->
<div class="p-3 border-bottom border-white border-opacity-10 d-flex align-items-center justify-content-between">
<div class="d-flex align-items-center gap-2">
<img src="/img/logo_unicaba_mini.png" alt="UniCABA" height="26" class="bg-white rounded-circle p-1">
<span class="fw-bold tracking-wider fs-6">UniCABA</span>
</div>
<span class="badge bg-success-subtle text-success border border-success-subtle rounded-pill px-2 py-0 fw-bold small">
● ACTIVO
</span>
</div>
<div class="p-4 text-center">
<!-- Avatar / Foto -->
<div class="position-relative d-inline-block mb-3">
<div class="rounded-circle bg-white text-primary fw-bold display-6 d-flex align-items-center justify-content-center shadow"
style="width: 84px; height: 84px; border: 3px solid rgba(255,255,255,0.4);">
{{ (user.name or 'U')[0] }}
</div>
</div>
<h4 class="fw-bold mb-0 text-white">{{ user.name }}</h4>
<div class="small opacity-75 mb-3">
{% if user.role == 'docente' or user.role == 'profesor' %}
DOCENTE INSTITUCIONAL
{% elif user.role == 'admin' %}
ADMINISTRACIÓN &amp; GOBIERNO
{% elif user.role == 'bedelia' %}
BEDELÍA &amp; GESTIÓN ÁULICA
{% else %}
ESTUDIANTE REGULAR
{% endif %}
</div>
<!-- Código QR Institucional -->
<div class="p-3 bg-white rounded-4 shadow-sm d-inline-block mb-3" style="min-width: 200px; min-height: 200px;">
<div id="qrcode" class="d-flex justify-content-center align-items-center"></div>
</div>
<div class="d-flex justify-content-center align-items-center gap-3 text-start small opacity-90 mb-2">
<div>
<span class="d-block text-uppercase" style="font-size: 0.65rem;">Documento</span>
<span class="fw-bold fs-6">{{ user.document_number or user.email }}</span>
</div>
<div class="vr bg-white opacity-25"></div>
<div>
<span class="d-block text-uppercase" style="font-size: 0.65rem;">ID Alumno</span>
<span class="fw-bold fs-6">#{{ user.id }}</span>
</div>
</div>
</div>
<!-- Footer de la Credencial -->
<div class="p-3 bg-black bg-opacity-25 border-top border-white border-opacity-10 d-flex align-items-center justify-content-between text-white-50 small">
<span><i class="bi bi-clock-history me-1"></i> QR renovable</span>
<span>Validez: {{ expiresInHours }}hs</span>
</div>
</div>
<!-- Accesos Rápidos -->
<div class="d-grid gap-2 mb-4">
<a href="/benefits" class="btn btn-outline-primary rounded-pill py-2">
<i class="bi bi-tags me-1"></i> Ver Convenios y Beneficios Disponibles
</a>
<a href="/schedule/today_schedule" class="btn btn-light rounded-pill py-2 border text-muted">
<i class="bi bi-calendar-day me-1"></i> Consultar Mis Clases de Hoy
</a>
</div>
<!-- Advertencia / Instructivo de Acceso -->
<div class="card border-0 bg-light rounded-4 p-3 small text-muted">
<div class="d-flex gap-2">
<i class="bi bi-info-circle-fill text-primary fs-5 mt-1"></i>
<div>
<strong class="text-dark">¿Cómo presentar tu credencial?</strong>
<p class="mb-0 mt-1">Al ingresar a la sede, muestra este código QR en la pantalla del lector de Recepción o al personal de Bedelía. El sistema verificará tu matrícula y te indicará en pantalla el aula y piso donde cursas hoy.</p>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Librería QRCode.js via CDN -->
<script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
const qrContainer = document.getElementById('qrcode');
const token = "{{ qrToken }}";
const fallbackText = "UNICABA:USR:{{ user.id }}:DNI:{{ user.document_number or user.email }}";
const textToEncode = token && token.length > 10 ? token : fallbackText;
try {
new QRCode(qrContainer, {
text: textToEncode,
width: 180,
height: 180,
colorDark: "#0F172A",
colorLight: "#FFFFFF",
correctLevel: QRCode.CorrectLevel.M
});
} catch (e) {
console.error('Error generando QR:', e);
qrContainer.innerHTML = '<div class="alert alert-warning p-2 small">Código disponible en modo texto</div>';
}
});
</script>
{% endblock %}
+390
View File
@@ -0,0 +1,390 @@
{% extends "base.html" %}
{% block title %}Consola de Acceso QR — Recepción & Seguridad{% endblock %}
{% block content %}
<div class="container-fluid py-3 px-lg-4">
<!-- Header de Control de Acceso -->
<div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-4">
<div>
<div class="d-flex align-items-center gap-2">
<span class="badge bg-secondary text-white rounded-pill px-3 py-1 fw-semibold">
<i class="bi bi-qr-code-scan me-1"></i> Control de Acceso
</span>
<span class="badge bg-success-subtle text-success border border-success-subtle rounded-pill px-2 py-0">En Línea</span>
</div>
<h1 class="h3 fw-bold mt-1 mb-0">Consola de Recepción &amp; Escáner QR</h1>
<p class="text-muted small mb-0">Identifica a los estudiantes y docentes al ingresar, valida su estado de matrícula e infórmales su aula y piso del día.</p>
</div>
<div class="d-flex align-items-center gap-3">
<div>
<label class="small text-muted fw-bold d-block">Punto de Control / Sede:</label>
<select class="form-select form-select-sm rounded-pill px-3" id="buildingSelect">
<option value="">Todas las Sedes</option>
{% for b in buildings %}
<option value="{{ b.id }}" {% if loop.first %}selected{% endif %}>{{ b.name }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="row g-4">
<!-- Columna Izquierda: Escáner y Entrada Rápida -->
<div class="col-12 col-lg-5">
<div class="card border-0 shadow-sm rounded-4 p-4 mb-4">
<h5 class="fw-bold mb-3 d-flex align-items-center justify-content-between">
<span><i class="bi bi-camera me-2 text-primary"></i>Lector de Cámara</span>
<button type="button" class="btn btn-sm btn-outline-primary rounded-pill px-3" id="toggleCamBtn" onclick="toggleCamera()">
<i class="bi bi-play-circle me-1"></i> Iniciar Cámara
</button>
</h5>
<!-- Visor de Cámara -->
<div id="reader" class="rounded-4 overflow-hidden bg-dark position-relative d-flex align-items-center justify-content-center text-white"
style="width: 100%; min-height: 280px;">
<div id="cameraPlaceholder" class="text-center p-4">
<i class="bi bi-camera-video display-4 text-secondary mb-2 d-block"></i>
<span class="small text-muted">Cámara en espera. Presiona "Iniciar Cámara" o utiliza un lector óptico USB.</span>
</div>
</div>
<!-- Entrada Manual o Pistola Óptica USB -->
<div class="mt-4 pt-3 border-top">
<label class="form-label small fw-bold text-uppercase text-muted">
<i class="bi bi-upc-scan me-1 text-primary"></i> Pistola Óptica USB o Entrada Manual por DNI
</label>
<form id="manualScanForm" onsubmit="handleManualScan(event)">
<div class="input-group">
<input type="text" class="form-control rounded-start-pill ps-3" id="scannerInput"
placeholder="Escanea con la pistola o escribe el DNI..." autofocus autocomplete="off">
<button class="btn btn-primary rounded-end-pill px-4 fw-semibold" type="submit">
Validar
</button>
</div>
<span class="small text-muted d-block mt-1">El lector óptico envía la lectura directamente a este campo con retorno de carro automático.</span>
</form>
</div>
</div>
</div>
<!-- Columna Derecha: Tarjeta de Validación Instantánea y Aulas del Día -->
<div class="col-12 col-lg-7">
<!-- Tarjeta de Resultado en Pantalla Completa -->
<div class="card border-0 shadow-sm rounded-4 overflow-hidden mb-4" id="resultCard" style="min-height: 380px;">
<div class="card-header py-3 px-4 bg-light border-0 d-flex align-items-center justify-content-between" id="resultHeader">
<h5 class="fw-bold mb-0" id="resultStatusText">
<i class="bi bi-person-badge me-2 text-muted"></i> Esperando lectura...
</h5>
<span class="badge bg-secondary rounded-pill px-3 py-1" id="resultTimeBadge">--:--</span>
</div>
<div class="card-body p-4 d-flex flex-column justify-content-center text-center" id="resultBody">
<div class="py-5 text-muted" id="waitingState">
<i class="bi bi-qr-code-scan display-1 opacity-25 text-primary mb-3 d-block"></i>
<h4 class="fw-bold text-secondary">Apunta el código QR a la cámara</h4>
<p class="small text-muted max-w-md mx-auto">
Al detectar la credencial del alumno o docente, el sistema mostrará instantáneamente sus datos de ingreso y las aulas donde cursa hoy.
</p>
</div>
<!-- Contenedor de Resultado Activo (Oculto inicialmente) -->
<div id="activeResultState" class="d-none text-start">
<div class="row align-items-center mb-4">
<div class="col-auto">
<div class="rounded-circle bg-primary text-white display-6 fw-bold d-flex align-items-center justify-content-center shadow-sm"
style="width: 80px; height: 80px;" id="userInitial">
A
</div>
</div>
<div class="col">
<div class="badge bg-success rounded-pill px-3 py-1 mb-1" id="matriculaBadge">REGULAR / ACTIVO</div>
<h3 class="fw-bold mb-0 text-dark" id="userNameText">Nombre del Alumno</h3>
<div class="text-muted small">
<span id="userRoleText">ESTUDIANTE</span> • DNI: <strong id="userDniText">12345678</strong>
</div>
</div>
</div>
<!-- Sección de Aulas y Clases de Hoy -->
<div class="p-3 bg-light rounded-4 border mb-3">
<h6 class="fw-bold text-uppercase text-primary small mb-3">
<i class="bi bi-compass-fill me-1"></i> Cronograma Áulico del Día de Hoy
</h6>
<div id="classesContainer">
<!-- Inyección dinámica de clases -->
</div>
</div>
<div class="d-flex align-items-center justify-content-between text-muted small">
<span id="scanTimestampText"><i class="bi bi-clock me-1"></i> Escaneado a las: --:--</span>
<span class="badge bg-primary-subtle text-primary border border-primary-subtle rounded-pill px-3 py-1">
Check-in Registrado
</span>
</div>
</div>
</div>
</div>
<!-- Tabla de Ingresos Recientes -->
<div class="card border-0 shadow-sm rounded-4 overflow-hidden">
<div class="card-header bg-body border-0 py-3 px-4 d-flex align-items-center justify-content-between">
<h6 class="fw-bold mb-0 text-dark">
<i class="bi bi-clock-history me-2 text-primary"></i> Últimos Ingresos Registrados en Sede
</h6>
<button type="button" class="btn btn-sm btn-link text-decoration-none p-0" onclick="refreshRecentLogs()">
<i class="bi bi-arrow-clockwise me-1"></i> Actualizar
</button>
</div>
<div class="table-responsive" style="max-height: 250px;">
<table class="table table-hover table-sm align-middle mb-0" id="recentLogsTable">
<thead class="table-light small">
<tr>
<th class="ps-4">Usuario</th>
<th>Rol</th>
<th>DNI</th>
<th>Sede</th>
<th>Hora</th>
<th class="text-center">Estado</th>
</tr>
</thead>
<tbody class="small" id="recentLogsBody">
{% if recentLogs and recentLogs | length > 0 %}
{% for log in recentLogs %}
<tr>
<td class="ps-4 fw-semibold">{{ log.user_name }}</td>
<td><span class="badge bg-light text-dark border">{{ log.user_role or 'ALUMNO' }}</span></td>
<td>{{ log.user_dni or '--' }}</td>
<td>{{ log.building_name }}</td>
<td>{{ log.scanned_at | replace('T', ' ') | truncate(16, true, '') }}</td>
<td class="text-center">
{% if log.status == 'AUTORIZADO' %}
<span class="badge bg-success-subtle text-success">OK</span>
{% else %}
<span class="badge bg-danger-subtle text-danger">{{ log.status }}</span>
{% endif %}
</td>
</tr>
{% endfor %}
{% else %}
<tr>
<td colspan="6" class="text-center py-3 text-muted">Aún no se han registrado ingresos hoy.</td>
</tr>
{% endif %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- html5-qrcode Library via CDN -->
<script src="https://cdn.jsdelivr.net/npm/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
<script>
let html5QrCode = null;
let isCameraRunning = false;
let isScanningLocked = false;
// Inicializar o alternar cámara
function toggleCamera() {
const btn = document.getElementById('toggleCamBtn');
const placeholder = document.getElementById('cameraPlaceholder');
if (isCameraRunning) {
if (html5QrCode) {
html5QrCode.stop().then(() => {
isCameraRunning = false;
btn.innerHTML = '<i class="bi bi-play-circle me-1"></i> Iniciar Cámara';
btn.classList.replace('btn-danger', 'btn-outline-primary');
placeholder.classList.remove('d-none');
});
}
} else {
html5QrCode = new Html5Qrcode("reader");
placeholder.classList.add('d-none');
html5QrCode.start(
{ facingMode: "environment" },
{
fps: 10,
qrbox: { width: 250, height: 250 }
},
(decodedText) => {
if (!isScanningLocked) {
isScanningLocked = true;
playBeep(true);
verifyToken(decodedText);
setTimeout(() => { isScanningLocked = false; }, 2500);
}
},
(errorMessage) => {
// Errores normales de lectura frame a frame, se omiten
}
).then(() => {
isCameraRunning = true;
btn.innerHTML = '<i class="bi bi-stop-circle me-1"></i> Detener Cámara';
btn.classList.replace('btn-outline-primary', 'btn-danger');
}).catch(err => {
console.error("Error al iniciar cámara:", err);
placeholder.classList.remove('d-none');
alert("No se pudo acceder a la cámara. Asegúrate de otorgar los permisos en el navegador.");
});
}
}
// Entrada manual o con pistola de código de barras
function handleManualScan(e) {
e.preventDefault();
const input = document.getElementById('scannerInput');
const val = input.value.trim();
if (!val) return;
verifyToken(val);
input.value = '';
}
// Petición AJAX de verificación al Backend BFF
async function verifyToken(token) {
const buildingId = document.getElementById('buildingSelect').value;
try {
const resp = await fetch('/reception/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
qr_token: token,
building_id: buildingId ? parseInt(buildingId, 10) : null
})
});
const data = await resp.json();
displayVerificationResult(data);
refreshRecentLogs();
} catch (err) {
console.error('Error verificando:', err);
displayVerificationResult({
status: 'DENEGADO',
message: 'Error de conexión con el validador.',
todays_classes: []
});
}
}
// Despliegue visual de resultados en pantalla
function displayVerificationResult(data) {
const waitingState = document.getElementById('waitingState');
const activeState = document.getElementById('activeResultState');
const cardHeader = document.getElementById('resultHeader');
const statusText = document.getElementById('resultStatusText');
const timeBadge = document.getElementById('resultTimeBadge');
waitingState.classList.add('d-none');
activeState.classList.remove('d-none');
const now = new Date();
timeBadge.innerText = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
if (data.status === 'AUTORIZADO') {
cardHeader.className = 'card-header py-3 px-4 bg-success text-white border-0 d-flex align-items-center justify-content-between';
statusText.innerHTML = '<i class="bi bi-check-circle-fill me-2"></i> ACCESO AUTORIZADO';
document.getElementById('matriculaBadge').className = 'badge bg-success rounded-pill px-3 py-1 mb-1';
document.getElementById('matriculaBadge').innerText = data.matricula_status || 'ACTIVO';
} else if (data.status === 'RESTRINGIDO') {
cardHeader.className = 'card-header py-3 px-4 bg-warning text-dark border-0 d-flex align-items-center justify-content-between';
statusText.innerHTML = '<i class="bi bi-exclamation-triangle-fill me-2"></i> ACCESO OBSERVADO / RESTRINGIDO';
document.getElementById('matriculaBadge').className = 'badge bg-warning text-dark rounded-pill px-3 py-1 mb-1';
document.getElementById('matriculaBadge').innerText = data.matricula_status || 'OBSERVADO';
} else {
cardHeader.className = 'card-header py-3 px-4 bg-danger text-white border-0 d-flex align-items-center justify-content-between';
statusText.innerHTML = '<i class="bi bi-x-circle-fill me-2"></i> ACCESO DENEGADO';
document.getElementById('matriculaBadge').className = 'badge bg-danger rounded-pill px-3 py-1 mb-1';
document.getElementById('matriculaBadge').innerText = data.matricula_status || 'NO REGISTRADO';
}
document.getElementById('userNameText').innerText = data.user_name || 'Desconocido';
document.getElementById('userRoleText').innerText = (data.user_role || 'NO DEFINIDO').toUpperCase();
document.getElementById('userDniText').innerText = data.user_dni || '--';
document.getElementById('userInitial').innerText = (data.user_name || '?')[0].toUpperCase();
document.getElementById('scanTimestampText').innerHTML = `<i class="bi bi-clock me-1"></i> Escaneado: ${now.toLocaleTimeString()}`;
// Renderizado del cronograma de aulas de hoy
const classesContainer = document.getElementById('classesContainer');
if (data.todays_classes && data.todays_classes.length > 0) {
classesContainer.innerHTML = data.todays_classes.map(c => `
<div class="card border border-primary-subtle rounded-3 p-3 mb-2 bg-white shadow-sm">
<div class="d-flex align-items-start justify-content-between">
<div>
<span class="badge bg-primary text-white rounded-pill px-2 py-0 small mb-1">${c.commission_name}</span>
<h5 class="fw-bold mb-1 text-primary">${c.subject_name}</h5>
<div class="text-muted small">
<i class="bi bi-person me-1"></i> Docente: <strong>${c.teacher_name || 'A designar'}</strong>
</div>
</div>
<div class="text-end">
<span class="badge bg-warning text-dark fs-6 px-3 py-1 rounded-pill fw-bold shadow-sm">
<i class="bi bi-door-open me-1"></i> ${c.classroom_name}
</span>
<div class="fw-semibold text-dark mt-1" style="font-size: 0.85rem;">
Piso: <strong>${c.floor || 1}</strong> (${c.building_name})
</div>
<div class="small text-muted mt-1">
<i class="bi bi-clock me-1"></i> ${c.start_time} a ${c.end_time} hs
</div>
</div>
</div>
</div>
`).join('');
} else {
classesContainer.innerHTML = `
<div class="alert alert-secondary py-2 px-3 rounded-3 small mb-0">
<i class="bi bi-info-circle me-1"></i> No tiene clases presenciales programadas para el día de hoy.
</div>
`;
}
}
// Actualización de la tabla de ingresos recientes
async function refreshRecentLogs() {
const buildingId = document.getElementById('buildingSelect').value;
try {
const res = await fetch(`/reception/recent-logs?building_id=${buildingId || ''}`);
const data = await res.json();
const tbody = document.getElementById('recentLogsBody');
if (data.items && data.items.length > 0) {
tbody.innerHTML = data.items.map(l => `
<tr>
<td class="ps-4 fw-semibold">${l.user_name}</td>
<td><span class="badge bg-light text-dark border">${l.user_role || 'ALUMNO'}</span></td>
<td>${l.user_dni || '--'}</td>
<td>${l.building_name}</td>
<td>${l.scanned_at ? l.scanned_at.replace('T', ' ').substring(11, 16) + ' hs' : '--'}</td>
<td class="text-center">
<span class="badge ${l.status === 'AUTORIZADO' ? 'bg-success-subtle text-success' : 'bg-danger-subtle text-danger'}">
${l.status === 'AUTORIZADO' ? 'OK' : l.status}
</span>
</td>
</tr>
`).join('');
}
} catch (e) {
console.warn('Error refrescando logs:', e);
}
}
// Feedback sonoro opcional vía Web Audio API
function playBeep(success) {
try {
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.connect(gain);
gain.connect(ctx.destination);
osc.frequency.value = success ? 880 : 330;
gain.gain.value = 0.1;
osc.start();
setTimeout(() => { osc.stop(); }, 120);
} catch (e) {}
}
</script>
{% endblock %}