feat: alcance temporal configurable en importador y fix multi-carrera en ORM (v3.8.3)

This commit is contained in:
2026-10-19 17:27:36 -03:00
parent 4dd3e30698
commit c14ab0d49f
17 changed files with 682 additions and 39 deletions
+10 -1
View File
@@ -626,6 +626,9 @@ class DashboardService:
filter_days = data.get('filter_days')
manual_date = data.get('manual_date')
single_date_only = bool(data.get('single_date_only', False))
weeks_to_generate = data.get('weeks_to_generate', 16)
date_from = data.get('date_from')
date_to = data.get('date_to')
custom_url = data.get('sheets_url') or data.get('base_url')
import_careers = data.get('import_careers', True)
@@ -646,6 +649,9 @@ class DashboardService:
filter_days=filter_days,
manual_date=manual_date,
single_date_only=single_date_only,
weeks_to_generate=weeks_to_generate,
date_from=date_from,
date_to=date_to,
import_careers=import_careers,
import_subjects=import_subjects,
import_commissions=import_commissions,
@@ -666,7 +672,10 @@ class DashboardService:
'filter_day': filter_day,
'filter_days': filter_days,
'single_date_only': single_date_only,
'manual_date': manual_date
'manual_date': manual_date,
'weeks_to_generate': weeks_to_generate,
'date_from': date_from,
'date_to': date_to
},
status='success'
)
+74 -5
View File
@@ -518,15 +518,35 @@ class GoogleSheetsImporter:
'preview_rows': preview_rows
}
def sync(self, filter_career=None, filter_subject=None, filter_day=None, filter_days=None, manual_date=None, single_date_only=False, import_careers=True, import_subjects=True, import_commissions=True, import_classrooms=True, import_reservations=True, selected_rows=None):
def sync(
self,
filter_career=None,
filter_subject=None,
filter_day=None,
filter_days=None,
manual_date=None,
single_date_only=False,
weeks_to_generate=16,
date_from=None,
date_to=None,
import_careers=True,
import_subjects=True,
import_commissions=True,
import_classrooms=True,
import_reservations=True,
selected_rows=None
):
"""
Proceso principal de sincronización con soporte de filtros, entidades granulares y filas seleccionadas:
Proceso principal de sincronización con soporte de filtros, entidades granulares y alcance temporal:
:param filter_career: Filtrar por carrera específica (ej. 'DATOS (CCC)')
:param filter_subject: Filtrar por código o nombre de materia (ej. 'ASIG00113')
:param filter_day: Filtrar por día específico ('Lunes'..'Sábado' o 'ALL')
:param filter_days: Lista o cadena de días específicos (ej. ['Lunes', 'Martes'])
:param manual_date: Fecha manual específica (YYYY-MM-DD o objeto date)
:param single_date_only: Si es True y hay manual_date, crea reserva solo para esa fecha puntual
:param weeks_to_generate: Número de semanas consecutivas a generar (1..30, defecto 16)
:param date_from: Fecha de inicio de rango (YYYY-MM-DD)
:param date_to: Fecha de fin de rango (YYYY-MM-DD)
:param import_careers: Booleano para importar/crear carreras
:param import_subjects: Booleano para importar/crear asignaturas
:param import_commissions: Booleano para importar/crear comisiones
@@ -547,6 +567,38 @@ class GoogleSheetsImporter:
except Exception:
pass
# Normalizar rango de fechas (date_from y date_to)
date_from_dt = None
if date_from:
try:
if isinstance(date_from, (datetime, date)):
date_from_dt = date_from if isinstance(date_from, date) else date_from.date()
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 = None
if date_to:
try:
if isinstance(date_to, (datetime, date)):
date_to_dt = date_to if isinstance(date_to, date) else date_to.date()
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:
date_from_dt, date_to_dt = date_to_dt, date_from_dt
# Normalizar número de semanas a generar
num_weeks = 16
if weeks_to_generate is not None:
try:
num_weeks = max(1, min(30, int(weeks_to_generate)))
except (ValueError, TypeError):
num_weeks = 16
# Normalizar días permitidos
allowed_days = None
if filter_days:
@@ -585,6 +637,10 @@ class GoogleSheetsImporter:
'days': allowed_days or ['Todos los Días'],
'manual_date': manual_dt.strftime('%Y-%m-%d') if manual_dt else None,
'single_date_only': bool(single_date_only and manual_dt),
'weeks_to_generate': num_weeks,
'date_from': date_from_dt.strftime('%Y-%m-%d') if date_from_dt else None,
'date_to': date_to_dt.strftime('%Y-%m-%d') if date_to_dt else None,
'temporal_scope': 'single_date' if (single_date_only and manual_dt) else ('date_range' if (date_from_dt and date_to_dt) else 'weeks'),
'entities': {
'careers': bool(import_careers),
'subjects': bool(import_subjects),
@@ -674,11 +730,13 @@ class GoogleSheetsImporter:
classrooms_cache = {(c.building.strip().upper(), c.code.strip().upper()): c for c in Classroom.query.all()}
subjects_cache = {s.code.strip().upper(): s for s in Subject.query.all()}
# Calculate semester dates (anchored on academic year 2026 or manual date base)
# Calculate semester dates (anchored on academic year 2026, manual date, or date_from)
base_monday = date(2026, 8, 31)
if manual_dt and not single_date_only:
base_monday = manual_dt - timedelta(days=manual_dt.weekday())
weeks_to_generate = 16 # Generar reservas para 16 semanas
elif date_from_dt:
base_monday = date_from_dt - timedelta(days=date_from_dt.weekday())
weeks_to_generate = num_weeks
for rec, day_idx in all_raw_records:
try:
@@ -886,8 +944,17 @@ class GoogleSheetsImporter:
dates_to_generate = [row_specific_date]
elif single_date_only and manual_dt:
dates_to_generate = [manual_dt]
elif date_from_dt and date_to_dt:
# Rango de fechas: calcular todos los días correspondientes a effective_day_idx entre date_from_dt y date_to_dt
days_ahead = (effective_day_idx - date_from_dt.weekday()) % 7
first_date = date_from_dt + timedelta(days=days_ahead)
dates_to_generate = []
cur = first_date
while cur <= date_to_dt:
dates_to_generate.append(cur)
cur += timedelta(days=7)
else:
dates_to_generate = [base_monday + timedelta(days=effective_day_idx, weeks=w) for w in range(weeks_to_generate)]
dates_to_generate = [base_monday + timedelta(days=effective_day_idx, weeks=w) for w in range(num_weeks)]
for class_date in dates_to_generate:
dt_start = datetime.combine(class_date, t_start)
@@ -944,6 +1011,8 @@ class GoogleSheetsImporter:
})
except Exception as row_err:
import traceback
traceback.print_exc()
stats['errors'].append(f"Error en fila '{rec.get('codigo', '?')}': {str(row_err)}")
db.session.commit()