diff --git a/backend/modules/cobranza/processor.py b/backend/modules/cobranza/processor.py index 5747134..ee7f814 100644 --- a/backend/modules/cobranza/processor.py +++ b/backend/modules/cobranza/processor.py @@ -111,14 +111,24 @@ class CobranzaProcessor: if isinstance(fecha_raw, datetime): return fecha_raw if not fecha_raw: return None s_fecha = str(fecha_raw).strip() - if len(s_fecha) == 10 and s_fecha[2] == '-': + if len(s_fecha) == 10 and s_fecha[2] == '-': return datetime.strptime(s_fecha, '%d-%m-%Y') - if ' ' in s_fecha: + if ' ' in s_fecha: return datetime.strptime(s_fecha.split('.')[0], '%Y-%m-%d %H:%M:%S') return datetime.strptime(s_fecha, '%Y-%m-%d') except: return None + def parse_corte_venc(self, venc_hasta): + """Convierte el corte del filtro (dd/mm/yyyy del calendario, o ISO) a datetime. + Devuelve None si no aplica (TODOS/vacío).""" + if venc_hasta in (None, "", "TODOS", "NONE"): return None + s = str(venc_hasta).strip() + try: + if '/' in s: return datetime.strptime(s, '%d/%m/%Y') + except: pass + return self.parse_fecha(s) + def obtener_fechas_filtro(self, ano, mes_numero): ano_int = int(ano) mes_int = int(mes_numero) @@ -344,9 +354,45 @@ class CobranzaProcessor: # DATOS PROCESADOS (TABLA PRINCIPAL CON VISTA DE ASESORES) # ========================================================================= - def obtener_datos_procesados(self, ano, mes, sectorista_filtro="TODOS", agrupacion="SEDE"): + def _meta_full(self): + """JSON completo REPLACE_META (con clasificacion_filtro_programa).""" + md = getattr(self.data_manager, "meta_data", None) + if isinstance(md, dict) and md: + return md + return self.config_sedes or {} + + def clasificar_filtro_programa(self, dsc_programa): + """TEAC/TERC/SEMINARIOS/OTROS desde clasificacion_filtro_programa (REPLACE_META). + Respeta el orden del JSON (primer patrón que coincide gana).""" + up = str(dsc_programa or "").upper() + data = self._meta_full().get("clasificacion_filtro_programa", {}) + for cat, cfg in data.items(): + if cat == "DEFAULT": + continue + for pat in cfg.get("patrones", []): + if str(pat).upper() in up: + return cat + return data.get("DEFAULT", "OTROS") + + def clasificar_sede_meta(self, dsc_programa): + """Sede desde clasificacion_sedes del REPLACE_META (LIMA por defecto).""" + up = str(dsc_programa or "").upper() + data = self._meta_full().get("clasificacion_sedes", {}) + for sede, cfg in data.items(): + if sede == "DEFAULT": + continue + for pat in cfg.get("patrones", []): + if str(pat).upper() in up: + return sede + return data.get("DEFAULT", "LIMA") + + def obtener_datos_procesados(self, ano, mes, sectorista_filtro="TODOS", agrupacion="SEDE", + sede_filtro="TODOS", prog_filtro="TODOS", venc_hasta=None): fecha_filtro, fecha_filtro_siguiente = self.obtener_fechas_filtro(ano, mes) hoy = datetime.now() + # Filtro adicional por F. Vencimiento: solo cuotas con vencimiento <= venc_hasta. + # Las cuotas sin fecha de vencimiento se incluyen SIEMPRE. + venc_corte = self.parse_corte_venc(venc_hasta) datos_agrupados = {} frecuencias_cuota = {} @@ -400,7 +446,23 @@ class CobranzaProcessor: mat = str(fila.get('num_matricula', '')).strip() - if agrupacion == "SEDE": + # Filtro por SEDE y PROGRAMA (REPLACE_META) — se aplica en cualquier + # agrupación cuando se pide (usado sobre todo en ASESOR). + _prog = fila.get('dsc_programa', '') + if str(sede_filtro).upper() not in ("TODOS", "", "NONE"): + if str(self.clasificar_sede_meta(_prog)).upper() != str(sede_filtro).upper(): + continue + if str(prog_filtro).upper() not in ("TODOS", "", "NONE"): + if str(self.clasificar_filtro_programa(_prog)).upper() != str(prog_filtro).upper(): + continue + + # Filtro por F. Vencimiento (<=). Sin fecha => se incluye siempre. + if venc_corte is not None: + _fv = self.parse_fecha(fila.get('fch_vencimiento')) + if _fv is not None and _fv > venc_corte: + continue + + if agrupacion == "SEDE": llave = self.clasificar_sede(fila.get('dsc_programa', '')) elif agrupacion == "ASESOR": llave = mapa_sectorista.get(idx, "SIN ASESOR") @@ -444,9 +506,25 @@ class CobranzaProcessor: if idx_factura not in indices_cronograma: continue mat_factura = str(fila.get('num_matricula', '')).strip() - tc_correcto = mapa_tc.get(mat_factura, 1.0) - - if agrupacion == "SEDE": + tc_correcto = mapa_tc.get(mat_factura, 1.0) + + # Mismo filtro SEDE/PROGRAMA (REPLACE_META) que en el cronograma. + _progF = fila.get('dsc_programa', '') + if str(sede_filtro).upper() not in ("TODOS", "", "NONE"): + if str(self.clasificar_sede_meta(_progF)).upper() != str(sede_filtro).upper(): + continue + if str(prog_filtro).upper() not in ("TODOS", "", "NONE"): + if str(self.clasificar_filtro_programa(_progF)).upper() != str(prog_filtro).upper(): + continue + + # Filtro por F. Vencimiento (<=). En facturas la fecha es fch_vencimiento_cuota. + # Sin fecha => se incluye siempre. + if venc_corte is not None: + _fvF = self.parse_fecha(fila.get('fch_vencimiento_cuota')) + if _fvF is not None and _fvF > venc_corte: + continue + + if agrupacion == "SEDE": llave = self.clasificar_sede(fila.get('dsc_programa', '')) elif agrupacion == "ASESOR": # AQUÍ ESTÁ LA MAGIA: usa el asesor guardado desde el cronograma @@ -564,9 +642,11 @@ class CobranzaProcessor: # ========================================================================= # DESGLOSE POR ALUMNO/MATRÍCULA # ========================================================================= - def obtener_detalle_programa(self, ano, mes, sectorista_filtro, programa_nombre): + def obtener_detalle_programa(self, ano, mes, sectorista_filtro, programa_nombre, venc_hasta=None): fecha_filtro, fecha_filtro_siguiente = self.obtener_fechas_filtro(ano, mes) hoy = datetime.now() + # Filtro por F. Vencimiento (<=). Sin fecha => se incluye siempre. + venc_corte = self.parse_corte_venc(venc_hasta) try: cronograma_raw, facturas_raw = self._obtener_datos_cached(ano) @@ -655,6 +735,9 @@ class CobranzaProcessor: fch_venc_raw = fila.get('fch_vencimiento') fch_venc_dt = self.parse_fecha(fch_venc_raw) + # Filtro por F. Vencimiento (<=). Sin fecha => se incluye siempre. + if venc_corte is not None and fch_venc_dt is not None and fch_venc_dt > venc_corte: + continue if fch_venc_dt and (fecha_filtro <= fch_venc_dt < fecha_filtro_siguiente): try: datos_agrupados[mat]["Cuota_Mes"] = str(int(fila.get('num_cuota', -1))) except: pass @@ -671,18 +754,25 @@ class CobranzaProcessor: if idx_factura not in indices_cronograma: continue mat_factura = str(fila.get('num_matricula', '')).strip() - tc_correcto = mapa_tc.get(mat_factura, 1.0) + tc_correcto = mapa_tc.get(mat_factura, 1.0) + + # Filtro por F. Vencimiento (<=). En facturas la fecha es fch_vencimiento_cuota. + # Sin fecha => se incluye siempre. + if venc_corte is not None: + _fvD = self.parse_fecha(fila.get('fch_vencimiento_cuota')) + if _fvD is not None and _fvD > venc_corte: + continue if mat_factura not in datos_agrupados: prog_info = mapa_programa_frec.get(mat_factura, {"prog": "-", "frec": "-"}) datos_agrupados[mat_factura] = { - "Alumno": mapa_alumnos.get(mat_factura, "SIN NOMBRE"), + "Alumno": mapa_alumnos.get(mat_factura, "SIN NOMBRE"), "Programa": prog_info["prog"], "Frecuencia": prog_info["frec"], "Suma_Ant": 0.0, "Suma_Cur": 0.0, "Resta_Ant": 0.0, "Resta_Cur": 0.0, "Cob_Ant": 0.0, "Cob_Cur": 0.0, "Cuota_Mes": "-", "Fch_Venc_Mes": "-" } - + resta_ant, resta_cur, cobrado_ant, cobrado_curso = self.evaluar_ctaxcob_resta( fila, fecha_filtro, fecha_filtro_siguiente, hoy, stats_resta, tc_correcto )