feat(import): estandarizacion de formato de fecha DD/MM/AAAA en importador de google sheets (v3.8.6)
This commit is contained in:
@@ -11,6 +11,21 @@ El formato está basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1
|
|||||||
- **Sincronización Continua Moodle (Fase 6):** Automatización de workers persistentes en background para el procesamiento continuo de la cola de Web Services Moodle 4.1.
|
- **Sincronización Continua Moodle (Fase 6):** Automatización de workers persistentes en background para el procesamiento continuo de la cola de Web Services Moodle 4.1.
|
||||||
- **Pruebas de Carga y Hardening (Fase 6):** Pruebas de estrés de concurrencia y validación final de producción.
|
- **Pruebas de Carga y Hardening (Fase 6):** Pruebas de estrés de concurrencia y validación final de producción.
|
||||||
|
|
||||||
|
## [3.8.6] - 2026-10-21
|
||||||
|
### Added
|
||||||
|
- **Estandarización de Formato de Fecha DD/MM/AAAA en Importador de Google Sheets (Spec 007)**:
|
||||||
|
- Integración de Flatpickr (`flatpickr.min.js` y `flatpickr/dist/l10n/es.js`) con formato regional `d/m/Y` (`DD/MM/AAAA`) para eliminar la dependencia de configuración de idioma del sistema operativo o navegador en inputs nativos.
|
||||||
|
- Soporte de selector interactivo de calendario con botón y edición tipográfica asistida en todos los inputs de la grilla interactiva de previsualización y filtros superiores.
|
||||||
|
- Parseo polimórfico y flexible en backend (`sheets_importer.py`) mediante `parse_flexible_date(val)` con tolerancia a `DD/MM/AAAA`, `DD-MM-AAAA` e ISO `AAAA-MM-DD`.
|
||||||
|
- Inyección de `inferred_date_display` con formato `DD/MM/AAAA` en los metadatos de inspección del Sheet.
|
||||||
|
- Cobertura de pruebas unitarias automatizadas en `backend/tests/test_sheets_import_temporal_scope.py` (`test_sync_with_ddmmaaaa_dates` y `test_sync_with_row_date_ddmmaaaa`).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Interfaz de Usuario del Importador Académico (`/admin/google_sheets_import`)**:
|
||||||
|
- Reemplazados todos los inputs `<input type="date">` por campos de texto monoespaciados `.table-date-input` y `.date-input-picker` con máscara y placeholder `DD/MM/AAAA`.
|
||||||
|
- Encabezado de columna de la grilla actualizado explícitamente a `Fecha Cursada (DD/MM/AAAA)`.
|
||||||
|
- Badges informativos de alcance temporal y modales de confirmación formateados de manera homogénea en `DD/MM/AAAA`.
|
||||||
|
|
||||||
## [3.8.5] - 2026-10-21
|
## [3.8.5] - 2026-10-21
|
||||||
### Added
|
### Added
|
||||||
- **Aislamiento de Login de Emergencia ADMIN en `/adm/login` (Spec 006)**:
|
- **Aislamiento de Login de Emergencia ADMIN en `/adm/login` (Spec 006)**:
|
||||||
|
|||||||
@@ -9,15 +9,14 @@ Memoria del proyecto entre sesiones para la rama `dev`.
|
|||||||
- Libro de Calificaciones (*Gradebook*) con actas de regularidad inmutables.
|
- Libro de Calificaciones (*Gradebook*) con actas de regularidad inmutables.
|
||||||
- Autenticación híbrida (Google OAuth 2.0, Moodle SSO, Local) y Modo Impersonación.
|
- Autenticación híbrida (Google OAuth 2.0, Moodle SSO, Local) y Modo Impersonación.
|
||||||
- Reinicialización segura del sistema con contraseña de Administrador.
|
- Reinicialización segura del sistema con contraseña de Administrador.
|
||||||
- **Sprint Activo: Aislamiento de Login de Emergencia Admin y Despliegue de Auth Único — v3.8.5**:
|
- **Sprint Activo: Estandarización de Formato de Fecha DD/MM/AAAA en Importador Google Sheets — v3.8.6**:
|
||||||
- **Aislamiento de Login Admin de Emergencia**:
|
- **Formato Regional Estricto DD/MM/AAAA (Spec 007)**:
|
||||||
- Creado enrutador y vista `/adm/login` (con redirección `/adm` -> `/adm/login`) para administradores de contingencia, protegido con `authLimiter`.
|
- Reemplazados todos los `<input type="date">` nativos en `/admin/google_sheets_import` por inputs con Flatpickr (`flatpickr.min.js` y `l10n/es.js`) con formato `d/m/Y`, garantizando que en cualquier sistema operativo o navegador se visualicen y carguen fechas en `DD/MM/AAAA` (ej. `21/10/2026`).
|
||||||
- Endpoint REST dedicado `POST /api/v1/auth/adm-login` en FastAPI que restringe estrictamente el acceso a roles `ADMIN` y emite logs de auditoría segregados (`ADMIN_EMERGENCY_LOGIN_SUCCESS`, `ADMIN_EMERGENCY_LOGIN_DENIED`, `ADMIN_EMERGENCY_LOGIN_FAILED`).
|
- Selector interactivo de calendario integrado en cada fila de la grilla de previsualización ("Fecha Cursada (DD/MM/AAAA)") y en el campo "Fecha masiva".
|
||||||
- Eliminados de la vista pública `/auth/login` el mensaje *"El acceso con contraseña local está deshabilitado para usuarios generales"* y el modal *"Acceso de Emergencia ADMIN"*.
|
- Helpers JS `formatToDDMMAAAA(d)` y `parseToIsoDate(d)` para conversión segura y validación cronológica.
|
||||||
- **Despliegue Automático por Proveedor Único**:
|
- Parseo flexible y tolerante en backend (`sheets_importer.py`) mediante `parse_flexible_date(val)` con soporte para `%d/%m/%Y`, `%Y-%m-%d`, etc.
|
||||||
- Detección en BFF (`is_single_provider`). Si únicamente Moodle está habilitado, el formulario de login aparece expandido (`show`) de forma predeterminada, sin divisores redundantes ni pasos extra.
|
- **Suite de Pruebas y Tipado**: 68 pruebas pasando al 100% (68 passed, 0 failed). Cero errores en código (`@[current_problems]`). Pyright `0 errors, 0 warnings`.
|
||||||
- **Suite de Pruebas y Tipado**: 66 pruebas ejecutadas con pytest pasando al 100% (66 passed, 0 failed). Cero errores en código (`@[current_problems]`). Pyright `0 errors, 0 warnings`.
|
- **Versión Consolidada**: `v3.8.6`.
|
||||||
- **Versión Consolidada**: `v3.8.5`.
|
|
||||||
|
|
||||||
## Decisiones (y por qué)
|
## Decisiones (y por qué)
|
||||||
- **Flujo Secuencial de Bedelía (9 Pasos)**: Estandarizar la carga operativa en: 1) Sede -> 2) Aula -> 3) Ciclo Lectivo -> 4) Carrera -> 5) Materia (vinculada a Carrera) -> 6) Comisión (asociada a Materia, Carrera y Ciclo) -> 7) Profesores -> 8) Alumnos -> 9) Reserva de Espacio. Esto asegura consistencia e integridad relacional.
|
- **Flujo Secuencial de Bedelía (9 Pasos)**: Estandarizar la carga operativa en: 1) Sede -> 2) Aula -> 3) Ciclo Lectivo -> 4) Carrera -> 5) Materia (vinculada a Carrera) -> 6) Comisión (asociada a Materia, Carrera y Ciclo) -> 7) Profesores -> 8) Alumnos -> 9) Reserva de Espacio. Esto asegura consistencia e integridad relacional.
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from typing import Any
|
|||||||
from database import db, get_db, engine, SessionLocal, session
|
from database import db, get_db, engine, SessionLocal, session
|
||||||
from config.config import Config
|
from config.config import Config
|
||||||
|
|
||||||
__version__ = "3.8.5"
|
__version__ = "3.8.6"
|
||||||
|
|
||||||
class DummyContext:
|
class DummyContext:
|
||||||
def __enter__(self):
|
def __enter__(self):
|
||||||
|
|||||||
@@ -140,6 +140,28 @@ SHEETS_CONFIG = [
|
|||||||
|
|
||||||
TIME_REGEX = re.compile(r'(\d{1,2})(?::(\d{2}))?\s*(?:a|-|to)\s*(\d{1,2})(?::(\d{2}))?', re.IGNORECASE)
|
TIME_REGEX = re.compile(r'(\d{1,2})(?::(\d{2}))?\s*(?:a|-|to)\s*(\d{1,2})(?::(\d{2}))?', re.IGNORECASE)
|
||||||
|
|
||||||
|
def parse_flexible_date(val: Any) -> Optional[date]:
|
||||||
|
"""
|
||||||
|
Parsea flexiblemente fechas provistas en formato DD/MM/AAAA (%d/%m/%Y),
|
||||||
|
DD-MM-AAAA (%d-%m-%Y), ISO YYYY-MM-DD (%Y-%m-%d) o instancias de date / datetime.
|
||||||
|
"""
|
||||||
|
if not val:
|
||||||
|
return None
|
||||||
|
if isinstance(val, datetime):
|
||||||
|
return val.date()
|
||||||
|
if isinstance(val, date):
|
||||||
|
return val
|
||||||
|
if isinstance(val, str):
|
||||||
|
cleaned = val.strip()
|
||||||
|
if not cleaned:
|
||||||
|
return None
|
||||||
|
for fmt in ('%d/%m/%Y', '%Y-%m-%d', '%d-%m-%Y', '%Y/%m/%d'):
|
||||||
|
try:
|
||||||
|
return datetime.strptime(cleaned, fmt).date()
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return None
|
||||||
|
|
||||||
class GoogleSheetsImporter:
|
class GoogleSheetsImporter:
|
||||||
"""
|
"""
|
||||||
Servicio para descargar, parsear y sincronizar cursadas académicas,
|
Servicio para descargar, parsear y sincronizar cursadas académicas,
|
||||||
@@ -390,15 +412,7 @@ class GoogleSheetsImporter:
|
|||||||
allowed_days = [nd]
|
allowed_days = [nd]
|
||||||
|
|
||||||
# Normalizar fecha manual para fecha inferida base
|
# Normalizar fecha manual para fecha inferida base
|
||||||
manual_dt = None
|
manual_dt = parse_flexible_date(manual_date)
|
||||||
if manual_date:
|
|
||||||
try:
|
|
||||||
if isinstance(manual_date, (datetime, date)):
|
|
||||||
manual_dt = manual_date if isinstance(manual_date, date) else manual_date.date()
|
|
||||||
elif isinstance(manual_date, str) and manual_date.strip():
|
|
||||||
manual_dt = datetime.strptime(manual_date.strip(), '%Y-%m-%d').date()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Referencia de semana base: lunes 5 de octubre de 2026 (semana activa del 2° cuatrimestre)
|
# Referencia de semana base: lunes 5 de octubre de 2026 (semana activa del 2° cuatrimestre)
|
||||||
ref_monday = date(2026, 10, 5)
|
ref_monday = date(2026, 10, 5)
|
||||||
@@ -494,6 +508,7 @@ class GoogleSheetsImporter:
|
|||||||
'horario': r.get('horario', ''),
|
'horario': r.get('horario', ''),
|
||||||
'turno': r.get('turno', 'Mañana'),
|
'turno': r.get('turno', 'Mañana'),
|
||||||
'inferred_date': target_date.strftime('%Y-%m-%d'),
|
'inferred_date': target_date.strftime('%Y-%m-%d'),
|
||||||
|
'inferred_date_display': target_date.strftime('%d/%m/%Y'),
|
||||||
'is_valid': is_valid,
|
'is_valid': is_valid,
|
||||||
'has_warning': has_warning,
|
'has_warning': has_warning,
|
||||||
'warning_msg': warning_msg
|
'warning_msg': warning_msg
|
||||||
@@ -557,42 +572,11 @@ class GoogleSheetsImporter:
|
|||||||
dias_esp = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado', 'Domingo']
|
dias_esp = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado', 'Domingo']
|
||||||
|
|
||||||
# Normalizar fecha manual si fue provista
|
# Normalizar fecha manual si fue provista
|
||||||
manual_dt: Optional[date] = None
|
manual_dt = parse_flexible_date(manual_date)
|
||||||
if manual_date:
|
|
||||||
try:
|
|
||||||
if isinstance(manual_date, datetime):
|
|
||||||
manual_dt = manual_date.date()
|
|
||||||
elif isinstance(manual_date, date):
|
|
||||||
manual_dt = manual_date
|
|
||||||
elif isinstance(manual_date, str) and manual_date.strip():
|
|
||||||
manual_dt = datetime.strptime(manual_date.strip(), '%Y-%m-%d').date()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Normalizar rango de fechas (date_from y date_to)
|
# Normalizar rango de fechas (date_from y date_to)
|
||||||
date_from_dt: Optional[date] = None
|
date_from_dt = parse_flexible_date(date_from)
|
||||||
if date_from:
|
date_to_dt = parse_flexible_date(date_to)
|
||||||
try:
|
|
||||||
if isinstance(date_from, datetime):
|
|
||||||
date_from_dt = date_from.date()
|
|
||||||
elif isinstance(date_from, date):
|
|
||||||
date_from_dt = date_from
|
|
||||||
elif isinstance(date_from, str) and date_from.strip():
|
|
||||||
date_from_dt = datetime.strptime(date_from.strip(), '%Y-%m-%d').date()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
date_to_dt: Optional[date] = None
|
|
||||||
if date_to:
|
|
||||||
try:
|
|
||||||
if isinstance(date_to, datetime):
|
|
||||||
date_to_dt = date_to.date()
|
|
||||||
elif isinstance(date_to, date):
|
|
||||||
date_to_dt = date_to
|
|
||||||
elif isinstance(date_to, str) and date_to.strip():
|
|
||||||
date_to_dt = datetime.strptime(date_to.strip(), '%Y-%m-%d').date()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
if date_from_dt and date_to_dt and date_from_dt > date_to_dt:
|
if date_from_dt and date_to_dt and date_from_dt > date_to_dt:
|
||||||
date_from_dt, date_to_dt = date_to_dt, date_from_dt
|
date_from_dt, date_to_dt = date_to_dt, date_from_dt
|
||||||
@@ -935,18 +919,8 @@ class GoogleSheetsImporter:
|
|||||||
|
|
||||||
# Determinar fechas a generar: específica de la fila (datepicker), puntual o 16 semanas
|
# Determinar fechas a generar: específica de la fila (datepicker), puntual o 16 semanas
|
||||||
dates_to_generate = []
|
dates_to_generate = []
|
||||||
row_specific_date: Optional[date] = None
|
|
||||||
raw_row_date = rec.get('date') or rec.get('inferred_date')
|
raw_row_date = rec.get('date') or rec.get('inferred_date')
|
||||||
if raw_row_date:
|
row_specific_date: Optional[date] = parse_flexible_date(raw_row_date)
|
||||||
try:
|
|
||||||
if isinstance(raw_row_date, datetime):
|
|
||||||
row_specific_date = raw_row_date.date()
|
|
||||||
elif isinstance(raw_row_date, date):
|
|
||||||
row_specific_date = raw_row_date
|
|
||||||
elif isinstance(raw_row_date, str) and raw_row_date.strip():
|
|
||||||
row_specific_date = datetime.strptime(raw_row_date.strip(), '%Y-%m-%d').date()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
if row_specific_date:
|
if row_specific_date:
|
||||||
dates_to_generate = [row_specific_date]
|
dates_to_generate = [row_specific_date]
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
|
|||||||
|
|
||||||
setup(
|
setup(
|
||||||
name="edu-space-admin",
|
name="edu-space-admin",
|
||||||
version="3.8.5",
|
version="3.8.6",
|
||||||
description="Administrative interface for Edu-Space Classroom Management System (FastAPI ASGI Core)",
|
description="Administrative interface for Edu-Space Classroom Management System (FastAPI ASGI Core)",
|
||||||
author="Edu-Space Development Team",
|
author="Edu-Space Development Team",
|
||||||
author_email="admin@edu-space.com",
|
author_email="admin@edu-space.com",
|
||||||
|
|||||||
@@ -150,3 +150,53 @@ def test_sync_sheets_api_date_from_greater_than_date_to_returns_400(init_databas
|
|||||||
assert response.status_code == 400
|
assert response.status_code == 400
|
||||||
assert 'La fecha de inicio (date_from) no puede ser posterior a la fecha de fin (date_to).' in response.json()['detail']
|
assert 'La fecha de inicio (date_from) no puede ser posterior a la fecha de fin (date_to).' in response.json()['detail']
|
||||||
|
|
||||||
|
|
||||||
|
def test_sync_with_ddmmaaaa_dates(init_database, app_context):
|
||||||
|
"""Verifica que fechas provistas en formato DD/MM/AAAA sean parseadas correctamente."""
|
||||||
|
_ensure_seed()
|
||||||
|
importer = GoogleSheetsImporter()
|
||||||
|
row = {
|
||||||
|
'dia': 'Miércoles',
|
||||||
|
'codigo': 'TEST-DDMMAAAA-01',
|
||||||
|
'asignatura': 'Materia Test DD/MM/AAAA',
|
||||||
|
'aula': '101',
|
||||||
|
'carrera': 'DATOS (CCC)',
|
||||||
|
'horario': '08:30 a 11:30hs',
|
||||||
|
'turno': 'Mañana'
|
||||||
|
}
|
||||||
|
stats = importer.sync(
|
||||||
|
selected_rows=[row],
|
||||||
|
manual_date='21/10/2026',
|
||||||
|
single_date_only=True
|
||||||
|
)
|
||||||
|
assert len(stats['errors']) == 0
|
||||||
|
assert stats['reservations_created'] == 1
|
||||||
|
|
||||||
|
res = Reservation.query.filter(Reservation.purpose.like('%TEST-DDMMAAAA-01%')).first()
|
||||||
|
assert res is not None
|
||||||
|
assert res.start_time.date() == date(2026, 10, 21)
|
||||||
|
|
||||||
|
|
||||||
|
def test_sync_with_row_date_ddmmaaaa(init_database, app_context):
|
||||||
|
"""Verifica que fechas en filas individuales en formato DD/MM/AAAA se respeten."""
|
||||||
|
_ensure_seed()
|
||||||
|
importer = GoogleSheetsImporter()
|
||||||
|
row = {
|
||||||
|
'dia': 'Jueves',
|
||||||
|
'codigo': 'TEST-DDMMAAAA-ROW',
|
||||||
|
'asignatura': 'Materia Row DD/MM/AAAA',
|
||||||
|
'aula': '101',
|
||||||
|
'carrera': 'DATOS (CCC)',
|
||||||
|
'horario': '18:30 a 21:30hs',
|
||||||
|
'turno': 'Tarde',
|
||||||
|
'date': '22/10/2026'
|
||||||
|
}
|
||||||
|
stats = importer.sync(selected_rows=[row])
|
||||||
|
assert len(stats['errors']) == 0
|
||||||
|
assert stats['reservations_created'] == 1
|
||||||
|
|
||||||
|
res = Reservation.query.filter(Reservation.purpose.like('%TEST-DDMMAAAA-ROW%')).first()
|
||||||
|
assert res is not None
|
||||||
|
assert res.start_time.date() == date(2026, 10, 22)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "frontend",
|
"name": "frontend",
|
||||||
"version": "3.8.5",
|
"version": "3.8.6",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
+3
-3
@@ -86,9 +86,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Versiones institucionales del sistema
|
// Versiones institucionales del sistema
|
||||||
const APP_VERSION = '3.8.5';
|
const APP_VERSION = '3.8.6';
|
||||||
const FRONTEND_VERSION = '3.8.5';
|
const FRONTEND_VERSION = '3.8.6';
|
||||||
const BACKEND_VERSION = '3.8.5';
|
const BACKEND_VERSION = '3.8.6';
|
||||||
|
|
||||||
env.addGlobal('app_version', APP_VERSION);
|
env.addGlobal('app_version', APP_VERSION);
|
||||||
env.addGlobal('frontend_version', FRONTEND_VERSION);
|
env.addGlobal('frontend_version', FRONTEND_VERSION);
|
||||||
|
|||||||
@@ -2,6 +2,25 @@
|
|||||||
|
|
||||||
{% block title %}Sincronización Google Sheets y Purga Académica - Edu-Space Admin{% endblock %}
|
{% block title %}Sincronización Google Sheets y Purga Académica - Edu-Space Admin{% endblock %}
|
||||||
|
|
||||||
|
{% block extra_css %}
|
||||||
|
<!-- Flatpickr CSS -->
|
||||||
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
|
||||||
|
<style>
|
||||||
|
.flatpickr-calendar {
|
||||||
|
font-family: inherit;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
box-shadow: 0 0.5rem 1.25rem rgba(0, 0, 0, 0.2);
|
||||||
|
z-index: 9999 !important;
|
||||||
|
}
|
||||||
|
.table-date-input {
|
||||||
|
min-width: 125px;
|
||||||
|
text-align: center;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="container-fluid pt-5 mt-4">
|
<div class="container-fluid pt-5 mt-4">
|
||||||
<!-- Header -->
|
<!-- Header -->
|
||||||
@@ -302,10 +321,13 @@
|
|||||||
<!-- Fecha Manual y Control Puntual -->
|
<!-- Fecha Manual y Control Puntual -->
|
||||||
<div class="col-md-4">
|
<div class="col-md-4">
|
||||||
<label for="manual_date" class="form-label fw-semibold small">
|
<label for="manual_date" class="form-label fw-semibold small">
|
||||||
<i class="bi bi-calendar-event me-1 text-danger"></i>Fecha Manual Sugerida:
|
<i class="bi bi-calendar-event me-1 text-danger"></i>Fecha Manual Sugerida (DD/MM/AAAA):
|
||||||
</label>
|
</label>
|
||||||
<input type="date" name="manual_date" id="manual_date" class="form-control form-control-sm"
|
<div class="input-group input-group-sm">
|
||||||
value="{{ manual_date }}">
|
<span class="input-group-text bg-white"><i class="bi bi-calendar-event text-danger"></i></span>
|
||||||
|
<input type="text" name="manual_date" id="manual_date" class="form-control font-monospace text-center date-input-picker"
|
||||||
|
value="{{ manual_date | format_date if manual_date else '' }}" placeholder="DD/MM/AAAA" maxlength="10">
|
||||||
|
</div>
|
||||||
<div class="form-text small">Fecha por defecto para registros sin fecha inferida.</div>
|
<div class="form-text small">Fecha por defecto para registros sin fecha inferida.</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -374,13 +396,21 @@
|
|||||||
<label for="date_from" class="form-label fw-semibold small mb-1">
|
<label for="date_from" class="form-label fw-semibold small mb-1">
|
||||||
<i class="bi bi-calendar-event text-success me-1"></i>Fecha de Inicio (Desde):
|
<i class="bi bi-calendar-event text-success me-1"></i>Fecha de Inicio (Desde):
|
||||||
</label>
|
</label>
|
||||||
<input type="date" class="form-control form-control-sm" id="date_from" name="date_from" value="{{ date_from }}" onchange="onRangeInputChange()">
|
<div class="input-group input-group-sm">
|
||||||
|
<span class="input-group-text bg-white"><i class="bi bi-calendar-event text-success"></i></span>
|
||||||
|
<input type="text" class="form-control font-monospace text-center date-input-picker" id="date_from" name="date_from"
|
||||||
|
value="{{ date_from | format_date if date_from else '' }}" placeholder="DD/MM/AAAA" maxlength="10" onchange="onRangeInputChange()">
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-5">
|
<div class="col-md-5">
|
||||||
<label for="date_to" class="form-label fw-semibold small mb-1">
|
<label for="date_to" class="form-label fw-semibold small mb-1">
|
||||||
<i class="bi bi-calendar-check text-danger me-1"></i>Fecha de Fin (Hasta):
|
<i class="bi bi-calendar-check text-danger me-1"></i>Fecha de Fin (Hasta):
|
||||||
</label>
|
</label>
|
||||||
<input type="date" class="form-control form-control-sm" id="date_to" name="date_to" value="{{ date_to }}" onchange="onRangeInputChange()">
|
<div class="input-group input-group-sm">
|
||||||
|
<span class="input-group-text bg-white"><i class="bi bi-calendar-check text-danger"></i></span>
|
||||||
|
<input type="text" class="form-control font-monospace text-center date-input-picker" id="date_to" name="date_to"
|
||||||
|
value="{{ date_to | format_date if date_to else '' }}" placeholder="DD/MM/AAAA" maxlength="10" onchange="onRangeInputChange()">
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-2 d-flex align-items-end">
|
<div class="col-md-2 d-flex align-items-end">
|
||||||
<button type="button" class="btn btn-sm btn-outline-secondary w-100" onclick="clearDateRange()">
|
<button type="button" class="btn btn-sm btn-outline-secondary w-100" onclick="clearDateRange()">
|
||||||
@@ -411,7 +441,11 @@
|
|||||||
<label for="single_punctual_date" class="form-label fw-semibold small mb-1 text-secondary">
|
<label for="single_punctual_date" class="form-label fw-semibold small mb-1 text-secondary">
|
||||||
Fecha Puntual Asignada:
|
Fecha Puntual Asignada:
|
||||||
</label>
|
</label>
|
||||||
<input type="date" class="form-control form-control-sm" id="single_punctual_date" value="{{ manual_date }}" onchange="syncSingleDateToManualDate(this.value)">
|
<div class="input-group input-group-sm">
|
||||||
|
<span class="input-group-text bg-white"><i class="bi bi-pin-angle-fill text-warning"></i></span>
|
||||||
|
<input type="text" class="form-control font-monospace text-center date-input-picker" id="single_punctual_date"
|
||||||
|
value="{{ manual_date | format_date if manual_date else '' }}" placeholder="DD/MM/AAAA" maxlength="10" onchange="syncSingleDateToManualDate(this.value)">
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -424,9 +458,9 @@
|
|||||||
<div class="d-flex align-items-center gap-2">
|
<div class="d-flex align-items-center gap-2">
|
||||||
<span class="badge bg-secondary-subtle text-secondary border px-3 py-2 fw-semibold" id="temporalSummaryBadge">
|
<span class="badge bg-secondary-subtle text-secondary border px-3 py-2 fw-semibold" id="temporalSummaryBadge">
|
||||||
{% if single_date_only %}
|
{% if single_date_only %}
|
||||||
<i class="bi bi-pin-angle-fill me-1 text-warning"></i>Alcance: 1 sola asignación puntual {{ '(' + manual_date + ')' if manual_date else '' }}
|
<i class="bi bi-pin-angle-fill me-1 text-warning"></i>Alcance: 1 sola asignación puntual {{ '(' + (manual_date | format_date) + ')' if manual_date else '' }}
|
||||||
{% elif date_from and date_to %}
|
{% elif date_from and date_to %}
|
||||||
<i class="bi bi-calendar-range me-1 text-info"></i>Alcance: Rango {{ date_from }} a {{ date_to }}
|
<i class="bi bi-calendar-range me-1 text-info"></i>Alcance: Rango {{ date_from | format_date }} a {{ date_to | format_date }}
|
||||||
{% else %}
|
{% else %}
|
||||||
<i class="bi bi-calendar-week me-1 text-primary"></i>Alcance: {{ weeks_to_generate or 16 }} semanas regulares
|
<i class="bi bi-calendar-week me-1 text-primary"></i>Alcance: {{ weeks_to_generate or 16 }} semanas regulares
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -479,7 +513,7 @@
|
|||||||
<div class="col-md-4">
|
<div class="col-md-4">
|
||||||
<div class="input-group input-group-sm">
|
<div class="input-group input-group-sm">
|
||||||
<span class="input-group-text bg-white small"><i class="bi bi-calendar-event me-1"></i>Fecha masiva:</span>
|
<span class="input-group-text bg-white small"><i class="bi bi-calendar-event me-1"></i>Fecha masiva:</span>
|
||||||
<input type="date" id="bulkDateInput" class="form-control">
|
<input type="text" id="bulkDateInput" class="form-control text-center font-monospace" placeholder="DD/MM/AAAA" maxlength="10">
|
||||||
<button type="button" class="btn btn-outline-secondary" onclick="applyBulkDate()" title="Aplica esta fecha a todos los registros seleccionados">
|
<button type="button" class="btn btn-outline-secondary" onclick="applyBulkDate()" title="Aplica esta fecha a todos los registros seleccionados">
|
||||||
Aplicar
|
Aplicar
|
||||||
</button>
|
</button>
|
||||||
@@ -507,7 +541,7 @@
|
|||||||
<th>Código & Asignatura</th>
|
<th>Código & Asignatura</th>
|
||||||
<th>Carrera(s)</th>
|
<th>Carrera(s)</th>
|
||||||
<th style="width: 150px;">Aula Detectada</th>
|
<th style="width: 150px;">Aula Detectada</th>
|
||||||
<th style="width: 175px;">Fecha Cursada (Editable)</th>
|
<th style="width: 185px;">Fecha Cursada (DD/MM/AAAA)</th>
|
||||||
<th style="width: 130px;">Estado</th>
|
<th style="width: 130px;">Estado</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -923,6 +957,10 @@
|
|||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block extra_js %}
|
{% block extra_js %}
|
||||||
|
<!-- Flatpickr JS y localización en Español -->
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/es.js"></script>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
// Variables globales para el manejo de la previsualización interactiva
|
// Variables globales para el manejo de la previsualización interactiva
|
||||||
window.inspectedRows = [];
|
window.inspectedRows = [];
|
||||||
@@ -930,6 +968,89 @@
|
|||||||
window.previewPageSize = 25;
|
window.previewPageSize = 25;
|
||||||
window.previewSearchTerm = '';
|
window.previewSearchTerm = '';
|
||||||
|
|
||||||
|
// Utilidades de conversión y formateo de fechas en DD/MM/AAAA
|
||||||
|
function formatToDDMMAAAA(dateStr) {
|
||||||
|
if (!dateStr) return '';
|
||||||
|
const trimmed = String(dateStr).trim();
|
||||||
|
if (/^\d{2}\/\d{2}\/\d{4}$/.test(trimmed)) return trimmed;
|
||||||
|
const isoMatch = trimmed.match(/^(\d{4})-(\d{2})-(\d{2})/);
|
||||||
|
if (isoMatch) {
|
||||||
|
return `${isoMatch[3]}/${isoMatch[2]}/${isoMatch[1]}`;
|
||||||
|
}
|
||||||
|
const d = new Date(trimmed);
|
||||||
|
if (!isNaN(d.getTime())) {
|
||||||
|
const day = String(d.getDate()).padStart(2, '0');
|
||||||
|
const month = String(d.getMonth() + 1).padStart(2, '0');
|
||||||
|
const year = d.getFullYear();
|
||||||
|
return `${day}/${month}/${year}`;
|
||||||
|
}
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseToIsoDate(dStr) {
|
||||||
|
if (!dStr) return null;
|
||||||
|
const trimmed = String(dStr).trim();
|
||||||
|
if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) return trimmed;
|
||||||
|
const ddmmaaaa = trimmed.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
|
||||||
|
if (ddmmaaaa) {
|
||||||
|
return `${ddmmaaaa[3]}-${ddmmaaaa[2]}-${ddmmaaaa[1]}`;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inicialización global de Flatpickr en inputs principales
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
const esLocale = (window.flatpickr && window.flatpickr.l10ns && window.flatpickr.l10ns.es) ? window.flatpickr.l10ns.es : 'es';
|
||||||
|
const commonConfig = {
|
||||||
|
dateFormat: 'd/m/Y',
|
||||||
|
allowInput: true,
|
||||||
|
locale: esLocale,
|
||||||
|
disableMobile: true
|
||||||
|
};
|
||||||
|
|
||||||
|
if (document.getElementById('manual_date')) {
|
||||||
|
flatpickr('#manual_date', Object.assign({}, commonConfig, {
|
||||||
|
onChange: function(dates, dateStr) {
|
||||||
|
const sDate = document.getElementById('single_punctual_date');
|
||||||
|
if (sDate && sDate._flatpickr) {
|
||||||
|
sDate._flatpickr.setDate(dateStr, false);
|
||||||
|
} else if (sDate) {
|
||||||
|
sDate.value = dateStr;
|
||||||
|
}
|
||||||
|
const badge = document.getElementById('temporalSummaryBadge');
|
||||||
|
const chkSingle = document.getElementById('single_date_only')?.checked;
|
||||||
|
if (chkSingle && badge) {
|
||||||
|
badge.innerHTML = '<i class="bi bi-pin-angle-fill me-1 text-warning"></i>Alcance: 1 sola asignación puntual' + (dateStr ? ' (' + dateStr + ')' : '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (document.getElementById('date_from')) {
|
||||||
|
flatpickr('#date_from', Object.assign({}, commonConfig, {
|
||||||
|
onChange: function() { onRangeInputChange(); }
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (document.getElementById('date_to')) {
|
||||||
|
flatpickr('#date_to', Object.assign({}, commonConfig, {
|
||||||
|
onChange: function() { onRangeInputChange(); }
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (document.getElementById('single_punctual_date')) {
|
||||||
|
flatpickr('#single_punctual_date', Object.assign({}, commonConfig, {
|
||||||
|
onChange: function(dates, dateStr) {
|
||||||
|
syncSingleDateToManualDate(dateStr);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (document.getElementById('bulkDateInput')) {
|
||||||
|
flatpickr('#bulkDateInput', Object.assign({}, commonConfig));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Gestión de Entidades
|
// Gestión de Entidades
|
||||||
function toggleImportEntities(checked) {
|
function toggleImportEntities(checked) {
|
||||||
document.querySelectorAll('.import-entity-chk').forEach(el => el.checked = checked);
|
document.querySelectorAll('.import-entity-chk').forEach(el => el.checked = checked);
|
||||||
@@ -964,13 +1085,13 @@
|
|||||||
const s = document.getElementById('filter_subject');
|
const s = document.getElementById('filter_subject');
|
||||||
if (s) s.value = '';
|
if (s) s.value = '';
|
||||||
const m = document.getElementById('manual_date');
|
const m = document.getElementById('manual_date');
|
||||||
if (m) m.value = '';
|
if (m) {
|
||||||
|
if (m._flatpickr) m._flatpickr.clear();
|
||||||
|
else m.value = '';
|
||||||
|
}
|
||||||
const single = document.getElementById('single_date_only');
|
const single = document.getElementById('single_date_only');
|
||||||
if (single) single.checked = false;
|
if (single) single.checked = false;
|
||||||
const df = document.getElementById('date_from');
|
clearDateRange();
|
||||||
if (df) df.value = '';
|
|
||||||
const dt = document.getElementById('date_to');
|
|
||||||
if (dt) dt.value = '';
|
|
||||||
const w = document.getElementById('weeks_to_generate');
|
const w = document.getElementById('weeks_to_generate');
|
||||||
if (w) w.value = 16;
|
if (w) w.value = 16;
|
||||||
const radWeeks = document.getElementById('mode_weeks');
|
const radWeeks = document.getElementById('mode_weeks');
|
||||||
@@ -1042,12 +1163,15 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cargar filas en memoria para la grilla interactiva
|
// Cargar filas en memoria para la grilla interactiva normalizando a DD/MM/AAAA
|
||||||
const rawRows = meta.preview_rows || [];
|
const rawRows = meta.preview_rows || [];
|
||||||
|
const fallbackDate = formatToDDMMAAAA(document.getElementById('manual_date')?.value || '');
|
||||||
window.inspectedRows = rawRows.map(function(r) {
|
window.inspectedRows = rawRows.map(function(r) {
|
||||||
|
const rowDate = formatToDDMMAAAA(r.inferred_date_display || r.inferred_date || fallbackDate);
|
||||||
return Object.assign({}, r, {
|
return Object.assign({}, r, {
|
||||||
selected: r.is_valid !== false,
|
selected: r.is_valid !== false,
|
||||||
date: r.inferred_date || document.getElementById('manual_date')?.value || ''
|
date: rowDate,
|
||||||
|
inferred_date: rowDate
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1173,6 +1297,7 @@
|
|||||||
|
|
||||||
// Carrera format
|
// Carrera format
|
||||||
const carText = (row.carreras_list && row.carreras_list.length > 0) ? row.carreras_list.join(', ') : (row.carrera || 'General');
|
const carText = (row.carreras_list && row.carreras_list.length > 0) ? row.carreras_list.join(', ') : (row.carrera || 'General');
|
||||||
|
const curDateVal = formatToDDMMAAAA(row.date || row.inferred_date || '');
|
||||||
|
|
||||||
html += '<tr class="' + rowClass + '">' +
|
html += '<tr class="' + rowClass + '">' +
|
||||||
'<td class="text-center">' +
|
'<td class="text-center">' +
|
||||||
@@ -1191,15 +1316,24 @@
|
|||||||
'<td><small class="text-muted d-block text-truncate" style="max-width: 160px;" title="' + carText + '">' + carText + '</small></td>' +
|
'<td><small class="text-muted d-block text-truncate" style="max-width: 160px;" title="' + carText + '">' + carText + '</small></td>' +
|
||||||
'<td>' + aulaBadge + '</td>' +
|
'<td>' + aulaBadge + '</td>' +
|
||||||
'<td>' +
|
'<td>' +
|
||||||
'<input type="date" class="form-control form-control-sm font-monospace" ' +
|
'<div class="input-group input-group-sm" style="min-width: 140px;">' +
|
||||||
'value="' + (row.date || row.inferred_date || '') + '" ' +
|
'<input type="text" class="form-control form-control-sm font-monospace text-center table-date-input row-date-input" ' +
|
||||||
|
'id="row_date_' + row.id + '" ' +
|
||||||
|
'data-row-id="' + row.id + '" ' +
|
||||||
|
'value="' + curDateVal + '" ' +
|
||||||
|
'placeholder="DD/MM/AAAA" maxlength="10" ' +
|
||||||
'onchange="updateRowDate(\'' + row.id + '\', this.value)">' +
|
'onchange="updateRowDate(\'' + row.id + '\', this.value)">' +
|
||||||
|
'<button class="btn btn-outline-secondary px-2" type="button" tabindex="-1" ' +
|
||||||
|
'onclick="openRowDatePicker(\'' + row.id + '\')" title="Seleccionar fecha">' +
|
||||||
|
'<i class="bi bi-calendar3"></i></button>' +
|
||||||
|
'</div>' +
|
||||||
'</td>' +
|
'</td>' +
|
||||||
'<td>' + estadoBadge + '</td>' +
|
'<td>' + estadoBadge + '</td>' +
|
||||||
'</tr>';
|
'</tr>';
|
||||||
});
|
});
|
||||||
|
|
||||||
tbody.innerHTML = html;
|
tbody.innerHTML = html;
|
||||||
|
initRowDatePickers();
|
||||||
renderPreviewPagination(totalFiltered, totalPages);
|
renderPreviewPagination(totalFiltered, totalPages);
|
||||||
|
|
||||||
// Actualizar checkbox maestro
|
// Actualizar checkbox maestro
|
||||||
@@ -1210,6 +1344,37 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Inicializar Flatpickr en cada celda editable de fecha en la tabla paginada
|
||||||
|
function initRowDatePickers() {
|
||||||
|
const esLocale = (window.flatpickr && window.flatpickr.l10ns && window.flatpickr.l10ns.es) ? window.flatpickr.l10ns.es : 'es';
|
||||||
|
document.querySelectorAll('.row-date-input').forEach(function(el) {
|
||||||
|
if (el._flatpickr) {
|
||||||
|
el._flatpickr.destroy();
|
||||||
|
}
|
||||||
|
flatpickr(el, {
|
||||||
|
dateFormat: 'd/m/Y',
|
||||||
|
allowInput: true,
|
||||||
|
locale: esLocale,
|
||||||
|
disableMobile: true,
|
||||||
|
onChange: function(selectedDates, dateStr) {
|
||||||
|
const rowId = el.getAttribute('data-row-id');
|
||||||
|
if (rowId) {
|
||||||
|
updateRowDate(rowId, dateStr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function openRowDatePicker(rowId) {
|
||||||
|
const el = document.getElementById('row_date_' + rowId);
|
||||||
|
if (el && el._flatpickr) {
|
||||||
|
el._flatpickr.open();
|
||||||
|
} else if (el) {
|
||||||
|
el.focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Paginación visual
|
// Paginación visual
|
||||||
function renderPreviewPagination(totalFiltered, totalPages) {
|
function renderPreviewPagination(totalFiltered, totalPages) {
|
||||||
const infoEl = document.getElementById('previewPaginationInfo');
|
const infoEl = document.getElementById('previewPaginationInfo');
|
||||||
@@ -1254,8 +1419,9 @@
|
|||||||
function updateRowDate(rowId, newDate) {
|
function updateRowDate(rowId, newDate) {
|
||||||
const row = window.inspectedRows.find(r => r.id === rowId);
|
const row = window.inspectedRows.find(r => r.id === rowId);
|
||||||
if (row) {
|
if (row) {
|
||||||
row.date = newDate;
|
const formatted = formatToDDMMAAAA(newDate);
|
||||||
row.inferred_date = newDate;
|
row.date = formatted;
|
||||||
|
row.inferred_date = formatted;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1296,11 +1462,12 @@
|
|||||||
// Aplicar Fecha Masiva a todas las filas seleccionadas
|
// Aplicar Fecha Masiva a todas las filas seleccionadas
|
||||||
function applyBulkDate() {
|
function applyBulkDate() {
|
||||||
const bulkInput = document.getElementById('bulkDateInput');
|
const bulkInput = document.getElementById('bulkDateInput');
|
||||||
const val = bulkInput ? bulkInput.value : '';
|
const rawVal = bulkInput ? bulkInput.value.trim() : '';
|
||||||
if (!val) {
|
if (!rawVal) {
|
||||||
alert('Por favor ingrese una fecha válida en el campo de Fecha masiva.');
|
alert('Por favor ingrese una fecha válida en el campo de Fecha masiva (DD/MM/AAAA).');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const val = formatToDDMMAAAA(rawVal);
|
||||||
let updatedCount = 0;
|
let updatedCount = 0;
|
||||||
window.inspectedRows.forEach(function(r) {
|
window.inspectedRows.forEach(function(r) {
|
||||||
if (r.selected) {
|
if (r.selected) {
|
||||||
@@ -1335,14 +1502,17 @@
|
|||||||
if (chkSingle) chkSingle.checked = false;
|
if (chkSingle) chkSingle.checked = false;
|
||||||
const df = document.getElementById('date_from')?.value;
|
const df = document.getElementById('date_from')?.value;
|
||||||
const dt = document.getElementById('date_to')?.value;
|
const dt = document.getElementById('date_to')?.value;
|
||||||
if (badge) badge.innerHTML = '<i class="bi bi-calendar-range me-1 text-info"></i>Alcance: Rango ' + (df && dt ? (df + ' a ' + dt) : 'personalizado');
|
if (badge) badge.innerHTML = '<i class="bi bi-calendar-range me-1 text-info"></i>Alcance: Rango ' + (df && dt ? (formatToDDMMAAAA(df) + ' a ' + formatToDDMMAAAA(dt)) : 'personalizado');
|
||||||
} else if (mode === 'single') {
|
} else if (mode === 'single') {
|
||||||
if (pSingle) pSingle.classList.remove('d-none');
|
if (pSingle) pSingle.classList.remove('d-none');
|
||||||
if (chkSingle) chkSingle.checked = true;
|
if (chkSingle) chkSingle.checked = true;
|
||||||
const mDate = document.getElementById('manual_date')?.value;
|
const mDate = document.getElementById('manual_date')?.value;
|
||||||
const sDate = document.getElementById('single_punctual_date');
|
const sDate = document.getElementById('single_punctual_date');
|
||||||
if (sDate && mDate) sDate.value = mDate;
|
if (sDate && mDate) {
|
||||||
if (badge) badge.innerHTML = '<i class="bi bi-pin-angle-fill me-1 text-warning"></i>Alcance: 1 sola asignación puntual' + (mDate ? ' (' + mDate + ')' : '');
|
if (sDate._flatpickr) sDate._flatpickr.setDate(mDate, false);
|
||||||
|
else sDate.value = formatToDDMMAAAA(mDate);
|
||||||
|
}
|
||||||
|
if (badge) badge.innerHTML = '<i class="bi bi-pin-angle-fill me-1 text-warning"></i>Alcance: 1 sola asignación puntual' + (mDate ? ' (' + formatToDDMMAAAA(mDate) + ')' : '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1364,14 +1534,20 @@
|
|||||||
const df = document.getElementById('date_from')?.value;
|
const df = document.getElementById('date_from')?.value;
|
||||||
const dt = document.getElementById('date_to')?.value;
|
const dt = document.getElementById('date_to')?.value;
|
||||||
const badge = document.getElementById('temporalSummaryBadge');
|
const badge = document.getElementById('temporalSummaryBadge');
|
||||||
if (badge) badge.innerHTML = '<i class="bi bi-calendar-range me-1 text-info"></i>Alcance: Rango ' + (df && dt ? (df + ' a ' + dt) : 'personalizado');
|
if (badge) badge.innerHTML = '<i class="bi bi-calendar-range me-1 text-info"></i>Alcance: Rango ' + (df && dt ? (formatToDDMMAAAA(df) + ' a ' + formatToDDMMAAAA(dt)) : 'personalizado');
|
||||||
}
|
}
|
||||||
|
|
||||||
function clearDateRange() {
|
function clearDateRange() {
|
||||||
const df = document.getElementById('date_from');
|
const df = document.getElementById('date_from');
|
||||||
const dt = document.getElementById('date_to');
|
const dt = document.getElementById('date_to');
|
||||||
if (df) df.value = '';
|
if (df) {
|
||||||
if (dt) dt.value = '';
|
if (df._flatpickr) df._flatpickr.clear();
|
||||||
|
else df.value = '';
|
||||||
|
}
|
||||||
|
if (dt) {
|
||||||
|
if (dt._flatpickr) dt._flatpickr.clear();
|
||||||
|
else dt.value = '';
|
||||||
|
}
|
||||||
const badge = document.getElementById('temporalSummaryBadge');
|
const badge = document.getElementById('temporalSummaryBadge');
|
||||||
if (badge) badge.innerHTML = '<i class="bi bi-calendar-range me-1 text-info"></i>Alcance: Rango personalizado';
|
if (badge) badge.innerHTML = '<i class="bi bi-calendar-range me-1 text-info"></i>Alcance: Rango personalizado';
|
||||||
}
|
}
|
||||||
@@ -1385,15 +1561,19 @@
|
|||||||
onTemporalModeChange('weeks');
|
onTemporalModeChange('weeks');
|
||||||
} else {
|
} else {
|
||||||
const mDate = document.getElementById('manual_date')?.value;
|
const mDate = document.getElementById('manual_date')?.value;
|
||||||
if (badge) badge.innerHTML = '<i class="bi bi-pin-angle-fill me-1 text-warning"></i>Alcance: 1 sola asignación puntual' + (mDate ? ' (' + mDate + ')' : '');
|
if (badge) badge.innerHTML = '<i class="bi bi-pin-angle-fill me-1 text-warning"></i>Alcance: 1 sola asignación puntual' + (mDate ? ' (' + formatToDDMMAAAA(mDate) + ')' : '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function syncSingleDateToManualDate(val) {
|
function syncSingleDateToManualDate(val) {
|
||||||
|
const formatted = formatToDDMMAAAA(val);
|
||||||
const mDate = document.getElementById('manual_date');
|
const mDate = document.getElementById('manual_date');
|
||||||
if (mDate) mDate.value = val;
|
if (mDate) {
|
||||||
|
if (mDate._flatpickr) mDate._flatpickr.setDate(formatted, false);
|
||||||
|
else mDate.value = formatted;
|
||||||
|
}
|
||||||
const badge = document.getElementById('temporalSummaryBadge');
|
const badge = document.getElementById('temporalSummaryBadge');
|
||||||
if (badge) badge.innerHTML = '<i class="bi bi-pin-angle-fill me-1 text-warning"></i>Alcance: 1 sola asignación puntual' + (val ? ' (' + val + ')' : '');
|
if (badge) badge.innerHTML = '<i class="bi bi-pin-angle-fill me-1 text-warning"></i>Alcance: 1 sola asignación puntual' + (formatted ? ' (' + formatted + ')' : '');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Modal de Confirmación de Sincronización
|
// Modal de Confirmación de Sincronización
|
||||||
@@ -1410,10 +1590,14 @@
|
|||||||
const modeRange = document.getElementById('mode_range')?.checked;
|
const modeRange = document.getElementById('mode_range')?.checked;
|
||||||
const dateFrom = document.getElementById('date_from')?.value;
|
const dateFrom = document.getElementById('date_from')?.value;
|
||||||
const dateTo = document.getElementById('date_to')?.value;
|
const dateTo = document.getElementById('date_to')?.value;
|
||||||
if (modeRange && dateFrom && dateTo && dateFrom > dateTo) {
|
if (modeRange && dateFrom && dateTo) {
|
||||||
alert('Error: La fecha de inicio (Desde: ' + dateFrom + ') no puede ser posterior a la fecha de fin (Hasta: ' + dateTo + ').');
|
const isoFrom = parseToIsoDate(dateFrom);
|
||||||
|
const isoTo = parseToIsoDate(dateTo);
|
||||||
|
if (isoFrom && isoTo && isoFrom > isoTo) {
|
||||||
|
alert('Error: La fecha de inicio (Desde: ' + formatToDDMMAAAA(dateFrom) + ') no puede ser posterior a la fecha de fin (Hasta: ' + formatToDDMMAAAA(dateTo) + ').');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Resumen de entidades marcadas
|
// Resumen de entidades marcadas
|
||||||
const chkRes = document.getElementById('chk_import_reservations')?.checked;
|
const chkRes = document.getElementById('chk_import_reservations')?.checked;
|
||||||
@@ -1437,9 +1621,9 @@
|
|||||||
const manualDate = document.getElementById('manual_date')?.value;
|
const manualDate = document.getElementById('manual_date')?.value;
|
||||||
|
|
||||||
if (chkSingle) {
|
if (chkSingle) {
|
||||||
html += '<li class="mt-2 text-warning fw-semibold"><i class="bi bi-pin-angle-fill me-2"></i>Alcance Temporal: 1 sola asignación puntual' + (manualDate ? ' (' + manualDate + ')' : '') + '</li>';
|
html += '<li class="mt-2 text-warning fw-semibold"><i class="bi bi-pin-angle-fill me-2"></i>Alcance Temporal: 1 sola asignación puntual' + (manualDate ? ' (' + formatToDDMMAAAA(manualDate) + ')' : '') + '</li>';
|
||||||
} else if (dateFrom && dateTo) {
|
} else if (dateFrom && dateTo) {
|
||||||
html += '<li class="mt-2 text-info fw-semibold"><i class="bi bi-calendar-range me-2"></i>Alcance Temporal: Rango de fechas del ' + dateFrom + ' al ' + dateTo + '</li>';
|
html += '<li class="mt-2 text-info fw-semibold"><i class="bi bi-calendar-range me-2"></i>Alcance Temporal: Rango de fechas del ' + formatToDDMMAAAA(dateFrom) + ' al ' + formatToDDMMAAAA(dateTo) + '</li>';
|
||||||
} else {
|
} else {
|
||||||
html += '<li class="mt-2 text-primary fw-semibold"><i class="bi bi-calendar-week me-2"></i>Alcance Temporal: ' + weeks + ' semanas consecutivas</li>';
|
html += '<li class="mt-2 text-primary fw-semibold"><i class="bi bi-calendar-week me-2"></i>Alcance Temporal: ' + weeks + ' semanas consecutivas</li>';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,8 +29,7 @@
|
|||||||
<!-- Design System & Custom Theme -->
|
<!-- Design System & Custom Theme -->
|
||||||
<link href="/css/theme.css" rel="stylesheet">
|
<link href="/css/theme.css" rel="stylesheet">
|
||||||
<link href="/css/style.css" rel="stylesheet">
|
<link href="/css/style.css" rel="stylesheet">
|
||||||
|
{% block extra_css %}{% endblock %}
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
body {
|
body {
|
||||||
font-family: 'Inter', sans-serif;
|
font-family: 'Inter', sans-serif;
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# Plan: 007-formato-fechas-ddmmaaaa - Estandarización de Formato de Fecha DD/MM/AAAA en Importador de Google Sheets
|
||||||
|
|
||||||
|
## 1. Arquitectura y Enfoque de Solución
|
||||||
|
La pantalla `/admin/google_sheets_import` requiere que todas las fechas visibles se formateen estrictamente como `DD/MM/AAAA`. Los `<input type="date">` nativos serán sustituidos por inputs formateados vinculados a Flatpickr (`dateFormat: 'd/m/Y'`), asegurando consistencia visual independiente del locale del sistema operativo. A su vez, el backend FastAPI incorporará un parseador de fechas tolerante para procesar `DD/MM/AAAA` y `YYYY-MM-DD`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Fases de Implementación
|
||||||
|
|
||||||
|
### Fase 1: Backend Resiliente (`backend/app/services/sheets_importer.py`)
|
||||||
|
- Crear la función utilitaria `parse_flexible_date(val)` que soporte `%d/%m/%Y`, `%d-%m-%Y` y `%Y-%m-%d`.
|
||||||
|
- Aplicar `parse_flexible_date` a `manual_date`, `date_from`, `date_to` y a las filas individuales `date` / `inferred_date` en `sync_google_sheets`.
|
||||||
|
- Agregar pruebas unitarias en `backend/tests/test_sheets_import_temporal_scope.py`.
|
||||||
|
|
||||||
|
### Fase 2: Vista Frontend Nunjucks & Flatpickr (`frontend/views/admin/import.html`)
|
||||||
|
- Cargar recursos CSS y JS de Flatpickr (`flatpickr.min.css`, `flatpickr.js`, `l10n/es.js`).
|
||||||
|
- Implementar helpers JS `formatToDDMMAAAA(d)` y `parseToIsoDate(d)`.
|
||||||
|
- Reemplazar `<input type="date">` en:
|
||||||
|
- "Fecha masiva": input de texto con Flatpickr (`#bulkDateInput`).
|
||||||
|
- Columna "Fecha Cursada (Editable)": input de texto con Flatpickr por fila e ícono de calendario.
|
||||||
|
- "Fecha Manual Sugerida": input con Flatpickr (`#manual_date`).
|
||||||
|
- "Fecha de Inicio (Desde)" y "Fecha de Fin (Hasta)": inputs con Flatpickr (`#date_from`, `#date_to`).
|
||||||
|
- "Fecha Puntual Asignada": input con Flatpickr (`#single_punctual_date`).
|
||||||
|
- Formatear badges y textos en modal de confirmación a `DD/MM/AAAA`.
|
||||||
|
|
||||||
|
### Fase 3: Pruebas, Verificación y Despliegue
|
||||||
|
- Validar `npx pyright` -> 0 errores.
|
||||||
|
- Ejecutar `pytest tests -v` -> 100% pasando.
|
||||||
|
- Bump de versión a `v3.8.6` en todos los archivos pertinentes.
|
||||||
|
- `git commit` y `git push origin dev`.
|
||||||
|
- Desplegar en producción `10.0.0.217` y verificar en vivo.
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# Espec: 007-formato-fechas-ddmmaaaa - Estandarización de Formato de Fecha DD/MM/AAAA en Importador de Google Sheets
|
||||||
|
|
||||||
|
## 1. Visión General y Propósito
|
||||||
|
En la vista `/admin/google_sheets_import` (`import.html`), los campos de entrada de fecha nativos de HTML5 (`<input type="date">`) delegan el formato de presentación visual a la configuración regional (locale) del sistema operativo del cliente. En entornos con Windows o navegadores configurados en inglés, estos inputs forzaban la visualización en formato anglosajón `MM/DD/YYYY` (ej: `10/21/2026`), generando confusión operativa en el personal de Bedelía de UniCABA acostumbrado al estándar nacional argentino **DD/MM/AAAA**.
|
||||||
|
|
||||||
|
El propósito de esta especificación es:
|
||||||
|
1. **Estandarizar la Visualización**: Asegurar que todos los campos de fecha en `/admin/google_sheets_import` (Fecha masiva, Fecha cursada editable en la grilla, Fecha manual sugerida, Rango de fechas Desde-Hasta y Fecha puntual) muestren explícita e invariablemente el formato **DD/MM/AAAA** (ej: `21/10/2026`).
|
||||||
|
2. **Interactividad y Usabilidad (Flatpickr)**: Incorporar el selector de fechas interactivo en español con formato `d/m/Y`, permitiendo tanto la selección visual por calendario como el tipeo manual validado.
|
||||||
|
3. **Resiliencia Bidireccional en Backend**: Asegurar que tanto el Frontend BFF como el Backend FastAPI procesen flexiblemente fechas provistas en formato `DD/MM/AAAA` o ISO `YYYY-MM-DD`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Requisitos en Sintaxis EARS (Español Estricto)
|
||||||
|
|
||||||
|
### 2.1. Visualización en Grilla y Formularios
|
||||||
|
- **RF-01 (Ubicuo)**: EL SISTEMA presentará todas las fechas de la pantalla `/admin/google_sheets_import` en formato `DD/MM/AAAA` (`d/m/Y`), incluyendo:
|
||||||
|
1. El campo "Fecha masiva" de la grilla interactiva.
|
||||||
|
2. La columna "Fecha Cursada (Editable)" para cada una de las filas en la tabla de inspección previa.
|
||||||
|
3. Los campos de filtro y alcance temporal ("Fecha Manual Sugerida", "Fecha de Inicio (Desde)", "Fecha de Fin (Hasta)" y "Fecha Puntual Asignada").
|
||||||
|
4. Los badges de resumen temporal y los textos informativos en los modales de confirmación.
|
||||||
|
- **RF-02 (Ubicuo)**: EL SISTEMA integrará Flatpickr localizado en español (`es`) con máscara y formato visible `d/m/Y` (`DD/MM/AAAA`) para todos los selectores de fecha en la vista.
|
||||||
|
|
||||||
|
### 2.2. Entrada de Datos y Edición Masiva
|
||||||
|
- **RF-03 (Basado en Eventos)**: CUANDO el usuario ingrese una fecha en "Fecha masiva" y presione "Aplicar", EL SISTEMA formateará el valor a `DD/MM/AAAA` y lo replicará en todas las filas seleccionadas de la grilla mostrando `DD/MM/AAAA`.
|
||||||
|
- **RF-04 (Basado en Eventos)**: CUANDO el usuario edite o seleccione una fecha en una fila individual de la grilla, EL SISTEMA actualizará el valor en memoria y conservará la representación visual en `DD/MM/AAAA`.
|
||||||
|
|
||||||
|
### 2.3. Resiliencia en Ingesta y Procesamiento Backend
|
||||||
|
- **RF-05 (Ubicuo)**: EL SISTEMA procesará de manera transparente en `sheets_importer.py` fechas enviadas en formato `DD/MM/AAAA` (`%d/%m/%Y`), `DD-MM-AAAA` (`%d-%m-%Y`) o ISO `AAAA-MM-DD` (`%Y-%m-%d`), normalizándolas al tipo canónico `datetime.date`.
|
||||||
|
- **RF-06 (No Deseado / Excepciones)**: SI el usuario ingresa una fecha con sintaxis inválida, ENTONCES EL SISTEMA alertará al usuario y mantendrá el último valor válido sin corromper el estado de la grilla ni interrumpir la sincronización.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Criterios de Aceptación y Finalización (DoD)
|
||||||
|
1. En `/admin/google_sheets_import`, el campo "Fecha masiva" y todos los inputs de la columna "Fecha Cursada (Editable)" muestran fechas con formato `DD/MM/AAAA` (ej: `21/10/2026`).
|
||||||
|
2. Flatpickr operativo en español con apertura de calendario al hacer clic en el botón de calendario o foco del input.
|
||||||
|
3. Rango de fechas Desde / Hasta y Fecha puntual muestran `DD/MM/AAAA` y actualizan sus badges en `DD/MM/AAAA`.
|
||||||
|
4. El backend parsea flexiblemente formatos `DD/MM/AAAA` y `YYYY-MM-DD`.
|
||||||
|
5. Pruebas automatizadas en `backend/tests/test_sheets_import_temporal_scope.py` verificando el parseo flexible de fechas.
|
||||||
|
6. Pyright con 0 errores y suite `pytest` pasando al 100%.
|
||||||
|
7. Bump semántico a `v3.8.6`, commit, `git push origin dev` y despliegue a producción verificado.
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Tareas: 007-formato-fechas-ddmmaaaa - Estandarización de Formato de Fecha DD/MM/AAAA en Importador de Google Sheets
|
||||||
|
|
||||||
|
## Tareas
|
||||||
|
|
||||||
|
- [x] **T01: Parseo Flexible de Fechas en Backend (`sheets_importer.py`)**
|
||||||
|
- **Descripción**: Implementar `parse_flexible_date(val)` en `backend/app/services/sheets_importer.py` para parsear fechas tanto en `DD/MM/AAAA` (`%d/%m/%Y`), `DD-MM-AAAA` (`%d-%m-%Y`) como en ISO `AAAA-MM-DD` (`%Y-%m-%d`). Aplicarlo en `manual_date`, `date_from`, `date_to` y filas de `selected_rows`.
|
||||||
|
- **Hecho cuando**: Las llamadas a sincronización procesen correctamente fechas provistas en `DD/MM/AAAA`.
|
||||||
|
- **Estimación**: 15 min.
|
||||||
|
|
||||||
|
- [x] **T02: Pruebas Automatizadas de Fechas DD/MM/AAAA en Backend**
|
||||||
|
- **Descripción**: Agregar tests en `backend/tests/test_sheets_import_temporal_scope.py` verificando sincronizaciones con fechas enviadas en formato `DD/MM/AAAA` tanto puntual como en rangos.
|
||||||
|
- **Hecho cuando**: `pytest backend/tests/test_sheets_import_temporal_scope.py` pase al 100%.
|
||||||
|
- **Estimación**: 15 min.
|
||||||
|
|
||||||
|
- [x] **T03: Integración de Flatpickr y Helpers de Fecha en `import.html`**
|
||||||
|
- **Descripción**: Cargar Flatpickr (CSS + JS + `l10n/es.js`) en `frontend/views/admin/import.html`. Definir las funciones `formatToDDMMAAAA(d)` y `parseToIsoDate(d)` en la sección de scripts.
|
||||||
|
- **Hecho cuando**: Flatpickr esté disponible en la página y las funciones de conversión operen correctamente.
|
||||||
|
- **Estimación**: 15 min.
|
||||||
|
|
||||||
|
- [x] **T04: Actualización de la Grilla Interactiva y "Fecha Masiva" a DD/MM/AAAA**
|
||||||
|
- **Descripción**: Reemplazar `<input type="date">` en `#bulkDateInput` y en cada fila de `renderPreview()` por inputs de texto monoespaciados formateados en `DD/MM/AAAA` (`d/m/Y`) con Flatpickr y selector de calendario. Actualizar `applyBulkDate()` y `updateRowDate()` para manejar `DD/MM/AAAA`.
|
||||||
|
- **Hecho cuando**: La grilla previsualice e inserte siempre fechas en `DD/MM/AAAA` (ej. `21/10/2026`).
|
||||||
|
- **Estimación**: 20 min.
|
||||||
|
|
||||||
|
- [x] **T05: Actualización de Filtros Superiores y Badges a DD/MM/AAAA**
|
||||||
|
- **Descripción**: Configurar Flatpickr en `#manual_date`, `#date_from`, `#date_to` y `#single_punctual_date`. Asegurar que los badges informativos y modales de confirmación muestren las fechas en `DD/MM/AAAA`.
|
||||||
|
- **Hecho cuando**: Ningún input en la pantalla muestre `MM/DD/YYYY` y todos usen `DD/MM/AAAA`.
|
||||||
|
- **Estimación**: 15 min.
|
||||||
|
|
||||||
|
- [x] **T06: Verificación de Código, Pyright y Suite de Pruebas**
|
||||||
|
- **Descripción**: Ejecutar `npx pyright` (0 errores) y la suite completa de pruebas `pytest tests -v`.
|
||||||
|
- **Hecho cuando**: Cero diagnósticos y todos los tests aprobados.
|
||||||
|
- **Estimación**: 10 min.
|
||||||
|
|
||||||
|
- [x] **T07: Bump Semántico a v3.8.6, Git Push y Despliegue en Producción**
|
||||||
|
- **Descripción**: Incrementar versión a `3.8.6`, actualizar `CHANGELOG.md` y `MEMORY.md`, hacer commit, `git push origin dev` y desplegar en `10.0.0.217` verificando HTTP 200 en vivo.
|
||||||
|
- **Hecho cuando**: `https://eduspace.oemspot.com.ar/version` responda `3.8.6` y `/admin/google_sheets_import` esté operativo en vivo.
|
||||||
|
- **Estimación**: 15 min.
|
||||||
Reference in New Issue
Block a user