feat(sheets): add online career, subject, day filtering and manual date assignment controls
This commit is contained in:
@@ -48,6 +48,21 @@ CANONICAL_CAREERS = {
|
||||
'POSG. INCLUSIVAS': 'POSG. INCLUSIVAS',
|
||||
}
|
||||
|
||||
def normalize_day_name(day_str):
|
||||
"""Normaliza cualquier variante de día a su nombre canónico en español (Lunes..Sábado)"""
|
||||
if not day_str:
|
||||
return ''
|
||||
d = day_str.strip().lower()
|
||||
d = d.replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u')
|
||||
if 'lun' in d: return 'Lunes'
|
||||
if 'mar' in d: return 'Martes'
|
||||
if 'mie' in d: return 'Miércoles'
|
||||
if 'jue' in d: return 'Jueves'
|
||||
if 'vie' in d: return 'Viernes'
|
||||
if 'sab' in d: return 'Sábado'
|
||||
if 'dom' in d: return 'Domingo'
|
||||
return day_str.strip()
|
||||
|
||||
def map_day_to_idx(day_str):
|
||||
"""Mapea el nombre del día (o prefijo) a su índice numérico 0..6 (Lunes=0)"""
|
||||
d = (day_str or '').lower()
|
||||
@@ -337,16 +352,101 @@ class GoogleSheetsImporter:
|
||||
except Exception:
|
||||
return None, None
|
||||
|
||||
def sync(self):
|
||||
def inspect_sheet_content(self):
|
||||
"""
|
||||
Proceso principal de sincronización:
|
||||
1. Descarga las 6 hojas de cálculo semanales (Lunes a Sábado).
|
||||
2. Normaliza carreras individuales y asignaturas compartidas (Many-to-Many).
|
||||
3. Upserts Aulas, Carreras, Asignaturas, Comisiones.
|
||||
4. Genera Reservas en el calendario para el semestre académico.
|
||||
Descarga e inspecciona las hojas del Sheet online para extraer:
|
||||
- Días disponibles con cantidad de filas
|
||||
- Carreras únicas
|
||||
- Materias únicas con sus códigos, nombres y carreras
|
||||
"""
|
||||
sheets_to_process = self.get_sheets_config()
|
||||
days_info = []
|
||||
careers_set = set()
|
||||
subjects_map = {}
|
||||
total_rows = 0
|
||||
|
||||
for sheet_cfg in sheets_to_process:
|
||||
day_name = sheet_cfg['name']
|
||||
try:
|
||||
csv_data = self.fetch_sheet_csv(sheet_cfg['gid'])
|
||||
rows = self.parse_sheet_rows(csv_data, day_name)
|
||||
total_rows += len(rows)
|
||||
days_info.append({
|
||||
'name': day_name,
|
||||
'gid': sheet_cfg['gid'],
|
||||
'day_idx': sheet_cfg['day_idx'],
|
||||
'rows_count': len(rows),
|
||||
'status': 'OK'
|
||||
})
|
||||
for r in rows:
|
||||
carreras = parse_careers_list(r.get('carrera', ''))
|
||||
for c in carreras:
|
||||
if c and c != 'General':
|
||||
careers_set.add(c)
|
||||
|
||||
code = r.get('codigo', '').strip()
|
||||
name = r.get('asignatura', '').strip()
|
||||
if code and name:
|
||||
if code not in subjects_map:
|
||||
subjects_map[code] = {
|
||||
'code': code,
|
||||
'name': name,
|
||||
'careers': carreras,
|
||||
'day': day_name
|
||||
}
|
||||
except Exception as e:
|
||||
days_info.append({
|
||||
'name': day_name,
|
||||
'gid': sheet_cfg['gid'],
|
||||
'day_idx': sheet_cfg.get('day_idx', 0),
|
||||
'rows_count': 0,
|
||||
'status': 'Error',
|
||||
'error': str(e)
|
||||
})
|
||||
|
||||
return {
|
||||
'total_rows': total_rows,
|
||||
'days': days_info,
|
||||
'careers': sorted(list(careers_set)),
|
||||
'subjects': sorted(list(subjects_map.values()), key=lambda x: x['code'])
|
||||
}
|
||||
|
||||
def sync(self, filter_career=None, filter_subject=None, filter_day=None, manual_date=None, single_date_only=False):
|
||||
"""
|
||||
Proceso principal de sincronización con soporte de filtros y fechas manuales:
|
||||
: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 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
|
||||
"""
|
||||
dias_esp = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado', 'Domingo']
|
||||
|
||||
# Normalizar fecha manual si fue provista
|
||||
manual_dt = None
|
||||
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 as e:
|
||||
pass
|
||||
|
||||
# Normalizar día filtro si fue provisto
|
||||
norm_filter_day = normalize_day_name(filter_day) if filter_day else None
|
||||
if norm_filter_day and norm_filter_day.upper() in ['ALL', 'TODOS', 'TODOS LOS DÍAS', 'TODOS LOS DIAS', '']:
|
||||
norm_filter_day = None
|
||||
|
||||
# Si el usuario no especificó filter_day pero ingresó fecha manual puntual, inferir día
|
||||
if not norm_filter_day and manual_dt and single_date_only:
|
||||
manual_w = manual_dt.weekday()
|
||||
if manual_w < 6:
|
||||
norm_filter_day = dias_esp[manual_w]
|
||||
|
||||
stats = {
|
||||
'total_rows_processed': 0,
|
||||
'matching_rows': 0,
|
||||
'careers_created': 0,
|
||||
'careers_updated': 0,
|
||||
'classrooms_created': 0,
|
||||
@@ -357,11 +457,23 @@ class GoogleSheetsImporter:
|
||||
'reservations_created': 0,
|
||||
'by_day': {},
|
||||
'errors': [],
|
||||
'sample_records': []
|
||||
'sample_records': [],
|
||||
'filters_applied': {
|
||||
'career': filter_career.strip() if filter_career else None,
|
||||
'subject': filter_subject.strip() if filter_subject else None,
|
||||
'day': norm_filter_day 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)
|
||||
}
|
||||
}
|
||||
|
||||
all_raw_records = []
|
||||
sheets_to_process = self.get_sheets_config()
|
||||
|
||||
# Filtrar pestañas si se especificó un día específico
|
||||
if norm_filter_day:
|
||||
sheets_to_process = [s for s in sheets_to_process if normalize_day_name(s['name']) == norm_filter_day]
|
||||
|
||||
for sheet_cfg in sheets_to_process:
|
||||
day_name = sheet_cfg['name']
|
||||
try:
|
||||
@@ -424,9 +536,11 @@ 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 current semester dates (anchored on academic year 2026)
|
||||
# Calculate semester dates (anchored on academic year 2026 or manual date base)
|
||||
base_monday = date(2026, 8, 31)
|
||||
weeks_to_generate = 16 # Generar reservas para 16 semanas (cuatrimestre completo Ago - Dic 2026)
|
||||
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
|
||||
|
||||
for rec, day_idx in all_raw_records:
|
||||
try:
|
||||
@@ -435,11 +549,32 @@ class GoogleSheetsImporter:
|
||||
aula_raw = rec['aula']
|
||||
carrera_raw = rec['carrera'].strip()
|
||||
horario_raw = rec['horario']
|
||||
dia = rec['dia']
|
||||
dia = rec['dia'] or (dias_esp[manual_dt.weekday()] if manual_dt else 'Lunes')
|
||||
turno = rec.get('turno', 'Mañana')
|
||||
|
||||
# 1. Upsert Careers (Desglosar carreras múltiples normalizadas)
|
||||
# Si el registro no traía día pero hay fecha manual, asignar día de la fecha
|
||||
if day_idx is None and manual_dt:
|
||||
day_idx = manual_dt.weekday()
|
||||
|
||||
# --- FILTRO 1: Filtrar por Carrera si fue especificada ---
|
||||
carreras_list = parse_careers_list(carrera_raw)
|
||||
if filter_career:
|
||||
fc = filter_career.strip().upper()
|
||||
match_c = any(fc in c.upper() or c.upper() in fc for c in carreras_list) or (fc in carrera_raw.upper())
|
||||
if not match_c:
|
||||
continue
|
||||
|
||||
# --- FILTRO 2: Filtrar por Materia si fue especificada ---
|
||||
sub_codes = parse_subject_codes(codigo)
|
||||
if filter_subject:
|
||||
fs = filter_subject.strip().upper()
|
||||
match_s = (fs in codigo.upper()) or (fs in asignatura.upper()) or any(fs in sc.upper() for sc in sub_codes)
|
||||
if not match_s:
|
||||
continue
|
||||
|
||||
stats['matching_rows'] += 1
|
||||
|
||||
# 1. Upsert Careers (Desglosar carreras múltiples normalizadas)
|
||||
career_objs = []
|
||||
for c_name in carreras_list:
|
||||
c_key = c_name.upper()
|
||||
@@ -484,7 +619,6 @@ class GoogleSheetsImporter:
|
||||
|
||||
# 3. Upsert Subject (Soporte Many-to-Many con múltiples carreras y subcódigos)
|
||||
subject_key = codigo.upper()
|
||||
sub_codes = parse_subject_codes(codigo)
|
||||
subject = subjects_cache.get(subject_key)
|
||||
if not subject:
|
||||
for sc in sub_codes:
|
||||
@@ -571,7 +705,9 @@ class GoogleSheetsImporter:
|
||||
|
||||
# 5. Generar Reservas de Calendario
|
||||
t_start, t_end = self.parse_time_range(horario_raw)
|
||||
if classroom and t_start and t_end and day_idx is not None:
|
||||
effective_day_idx = day_idx if day_idx is not None else (manual_dt.weekday() if manual_dt else 0)
|
||||
|
||||
if classroom and t_start and t_end:
|
||||
is_room_virtual = bool(classroom.is_virtual or 'VIRTUAL' in (classroom.code or '').upper())
|
||||
|
||||
v_link = None
|
||||
@@ -582,8 +718,14 @@ class GoogleSheetsImporter:
|
||||
if not commission.virtual_link:
|
||||
commission.virtual_link = v_link
|
||||
|
||||
for w in range(weeks_to_generate):
|
||||
class_date = base_monday + timedelta(days=day_idx, weeks=w)
|
||||
# Determinar fechas a generar: puntual o 16 semanas
|
||||
dates_to_generate = []
|
||||
if single_date_only and manual_dt:
|
||||
dates_to_generate = [manual_dt]
|
||||
else:
|
||||
dates_to_generate = [base_monday + timedelta(days=effective_day_idx, weeks=w) for w in range(weeks_to_generate)]
|
||||
|
||||
for class_date in dates_to_generate:
|
||||
dt_start = datetime.combine(class_date, t_start)
|
||||
dt_end = datetime.combine(class_date, t_end)
|
||||
|
||||
@@ -602,6 +744,8 @@ class GoogleSheetsImporter:
|
||||
).first()
|
||||
|
||||
c_desc = ", ".join([c.name for c in career_objs]) if career_objs else 'General'
|
||||
note_suffix = f" [Fecha asignada: {class_date.strftime('%d/%m/%Y')}]" if (manual_dt and single_date_only) else ""
|
||||
note_text = f"Clase {'puntual ' if (single_date_only and manual_dt) else 'semanal '}{dia} ({turno}) - Carreras: {c_desc}{note_suffix}"
|
||||
|
||||
if not existing_res:
|
||||
res = Reservation(
|
||||
@@ -615,13 +759,13 @@ class GoogleSheetsImporter:
|
||||
expected_attendees=min(classroom.capacity, 30) if not is_room_virtual else 35,
|
||||
shift=turno,
|
||||
virtual_link=v_link,
|
||||
notes=f"Clase semanal {dia} ({turno}) - Carreras: {c_desc}"
|
||||
notes=note_text
|
||||
)
|
||||
db.session.add(res)
|
||||
stats['reservations_created'] += 1
|
||||
else:
|
||||
existing_res.shift = turno
|
||||
existing_res.notes = f"Clase semanal {dia} ({turno}) - Carreras: {c_desc}"
|
||||
existing_res.notes = note_text
|
||||
if is_room_virtual and not existing_res.virtual_link:
|
||||
existing_res.virtual_link = v_link
|
||||
|
||||
|
||||
Reference in New Issue
Block a user