querySingle('select now()'));
}
$periodo_sgu_old = 0;
$log_desc = "";
//------------------ACTUALIZA SALONES----------------------
$pag = "https://portal.ulsa.edu.mx/servicios/AuditoriaAsistencialRest/AuditoriaAsistencialService.svc/auditoriaAsistencial/catalogos/espacios/seleccionar";
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $pag,
CURLOPT_RETURNTRANSFER => true,
//CURLOPT_ENCODING => "",
//CURLOPT_MAXREDIRS => 10,
// CURLOPT_TIMEOUT => 0,
//CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([]),
CURLOPT_HTTPHEADER => [
"token: ".$token,
"username: SGU_APSA_AUD_ASIST",
"Content-Type: application/json",
'Transfer-Encoding: chunked'
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err)
die("cURL Error #:$err");
$salonesData = json_decode($response, true);
//$salonesTotal_rs = $db->count('salon');
$salonesTotal_rs = $db->where('salon_id', 0, '>')->count('salon');
echo "BD $salonesTotal_rs vs SGU " . count($salonesData) . " salones
";
if($salonesTotal_rs < count($salonesData)){//faltan salones en BD
echo "Actualizar salones
";
$salones_rs = $db->query('SELECT id_espacio_sgu FROM salon');
//claves de espacios
$arreglo_espacios = array_map(function ($item) {
return $item['id_espacio_sgu'];
}, $salones_rs);
foreach($salonesData as $data){
if( !in_array($data["IdEspacio"], $arreglo_espacios)){
//Insertar espacio
if($debug){
echo "Espacio nuevo: ".$data["NombreEspacio"]."
";
}else{
$db->query('INSERT INTO SALON (salon, id_espacio_sgu, id_espacio_padre) VALUES (:salon, :id, :id_padre)',
[":salon"=>$data["NombreEspacio"], ":id"=>$data["IdEspacio"], ":id_padre"=>$data["IdEspacioPadre"]]);
}
}
}
}
// -----------------------------
$pag = "https://portal.ulsa.edu.mx/servicios/AuditoriaAsistencialRest/AuditoriaAsistencialService.svc/auditoriaAsistencial/seleccionar";
$elementos_bd_total = [];
$elementos_sgu_total = [];
$periodo_sgu_old = 0;
try{
$pdo->beginTransaction();
$periodos_rs = $db->query('SELECT periodo_id, id_periodo_sgu, nivel_id FROM periodo WHERE :hoy BETWEEN periodo_fecha_inicio AND periodo_fecha_fin AND id_periodo_sgu != 0 ORDER BY periodo_id',
[":hoy"=>$hoy]);
foreach ($periodos_rs as $per){
//Verifica si el día de hoy es festivo
$vacacion_rs = $db->querySingle('select es_festivo(:per, :hoy)', [":per"=>$per["periodo_id"], ":hoy"=>$hoy]);
if($vacacion_rs["es_festivo"]){
if($debug){
echo "
Dia festivo en Periodo: ".$per["id_periodo_sgu"]."[".$per["periodo_id"]."]
";
}
continue;
}
$carreras_rs = $db->query('SELECT c.clave_carrera, c.carrera_id FROM carrera c WHERE nivel_id = :nivel',
[":nivel"=>$per["nivel_id"]]);
if($debug){
echo "Periodo: ".$per["id_periodo_sgu"]."[".$per["periodo_id"]."] nivel: ".$per["nivel_id"]."
";
//print_r($carreras_rs);
}
if ($periodo_sgu_old != $per["id_periodo_sgu"]){
$periodo_sgu_old = $per["id_periodo_sgu"];
$params = [
'idPeriodo'=>$per["id_periodo_sgu"],
'fecha'=>$hoy
];
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $pag,
CURLOPT_RETURNTRANSFER => true,
//CURLOPT_ENCODING => "",
//CURLOPT_MAXREDIRS => 10,
//CURLOPT_TIMEOUT => 0,
//CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($params),
CURLOPT_HTTPHEADER => [
"token: ".$token,
"username: SGU_APSA_AUD_ASIST",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err)
die("cURL Error #:$err");
}
$selectedData = json_decode($response, true);
//claves de carreras en el periodo
$arreglo_claves = array_map(function ($item) {
return $item['clave_carrera'];
}, $carreras_rs);
//print_r($selectedData); exit();
$sguHash = array();
if(!empty($selectedData)){
//Recorre SGU y genera hash
foreach( $selectedData as $row ){
if(!$row["EsMateriaPorReposicion"]){
$sguHash[] = array(
"hash"=>( trim($row["HoraInicio"]."|".($row["NombreMateria"])."|".(trim($row["ClaveProfesor"])==""?"000000":trim($row["ClaveProfesor"]))."|".$row["IdEspacio"]) ),
"data"=>$row
);
}else{//reposición
if(in_array($row["ClaveCarrera"] , $arreglo_claves)){
//busca yyyy-mm-dd hh:mm:ss en la cadena
if (preg_match("/\d{4}-\d{2}-\d{2} de \d{2}:\d{2}:\d{2}/", $row["Observaciones"], $matches)) {
$fecha_orig = str_replace(" de", "", $matches[0]);
$fecha_nueva = $row["FechaStr"]." ".$row["HoraInicio"];
$hora_fin_nueva = $row["HoraFin"];
if($debug){
echo "
SELECT * FROM fi_reposicion_sgu($fecha_orig, ".$hora_fin_nueva.",".$fecha_nueva." ,".$row["ClaveProfesor"].", ".$per["periodo_id"].", ".$row["IdEspacio"].")";
}else{
$db->query('SELECT * FROM fi_reposicion_sgu(:fecha_orig, :hora_fin, :fecha_rep, :prof, :per, :salon)',
[":fecha_orig"=>$fecha_orig, ":hora_fin"=>$hora_fin_nueva, ":fecha_rep"=>$fecha_nueva, ":prof"=>$row["ClaveProfesor"], ":per"=>$per["periodo_id"], ":salon"=>$row["IdEspacio"] ]);
$log_desc .="SELECT * FROM fi_reposicion_sgu($fecha_orig, ".$hora_fin_nueva.",".$fecha_nueva." ,".$row["ClaveProfesor"].", ".$per["periodo_id"].", ".$row["IdEspacio"].") ## ";
}
}else{
if($debug)
echo "No se encontró fecha y hora en: ".$row["Observaciones"]."
";
}
}
}
}
unset($selectedData);
}
$horarios_sgu = [];
/*
print_r($carreras_rs);
echo "
";*/
print_r($arreglo_claves);
echo "
";
//$areacomun = array();
foreach($sguHash as $sgu){
if(in_array($sgu["data"]["ClaveCarrera"] , $arreglo_claves) /*&& !in_array($sgu["data"]["ClaveMateria"], $areacomun)*/){
$horarios_sgu[] = $sgu;
}
}
//print_r($horarios_sgu);exit();
unset($sguHash);
$elementos_sgu_total = array_merge($elementos_sgu_total, $horarios_sgu);
//Recorre BD y genera hash
$horarios_rs = $db->query('SELECT * FROM fs_horarios_hash(:dia, :periodo, :fecha)',
[':dia' => $dia_hoy, ':periodo' => $per["periodo_id"], ':fecha'=>$hoy]);
//echo "**** SELECT * FROM fs_horarios_hash($dia_hoy, ".$per["periodo_id"].")
";
//usort($horarios_rs, 'compareByHash');
$elementos_bd_total = array_merge($elementos_bd_total, $horarios_rs);
}//foreach periodo
//print_r($elementos_sgu_total);
//exit();
if($debug){
echo "Resumen
";
echo "SGU [".count($elementos_sgu_total)."]
";
echo "BD [".count($elementos_bd_total)."]
";
}
// Extraer los "hash" de $lista y $lista2 en arreglos separados
$hashes_sgu = array_column($elementos_sgu_total, 'hash');
$hashes_bd = array_column($elementos_bd_total, 'hash');
//------------------
// Encontrar los "hash" que están en $sgu pero no están en $bd
$hashes_no_en_sgu = array_diff($hashes_bd, $hashes_sgu);
if($debug) echo "hashes_no_en_sgu ".count($hashes_no_en_sgu)."
";
if(count($hashes_no_en_sgu)>0){
// Ahora puedes obtener los elementos completos que cumplen la condición original
$elementos_no_en_sgu = array_filter($elementos_bd_total, function ($item) use ($hashes_no_en_sgu) {
return in_array($item['hash'], $hashes_no_en_sgu);
});
if($debug){
print_r($elementos_no_en_sgu);
echo "Sobran ".count($elementos_no_en_sgu)." en BD
";
}
//Update fecha_fin
$log_desc = "";
foreach($elementos_no_en_sgu as $row){
if($debug){
echo "
SELECT * FROM fu_horario_deshabilita(".$row["horario_id"].")";
}else{
$db->query('SELECT * FROM fu_horario_deshabilita(:horario)', [":horario"=>$row["horario_id"]]);
$log_desc .="SELECT * FROM fu_horario_deshabilita(".$row["horario_id"].") ## ";
}
}
if(!$debug && !empty($log_desc)){
$log = new LogCambios(__DIR__."/log/");
$log->appendLog($log_desc);
}
}
// Encontrar los "hash" que están en $sgu pero no están en $bd
$hashes_no_en_bd = array_diff($hashes_sgu, $hashes_bd);
//echo "hashes_no_en_bd ".count($hashes_no_en_bd)."
";
if(count($hashes_no_en_bd)>0){
// Ahora puedes obtener los elementos completos que cumplen la condición original
$elementos_no_en_bd = array_filter($elementos_sgu_total, function ($item) use ($hashes_no_en_bd) {
return in_array($item['hash'], $hashes_no_en_bd);
});
if($debug){
echo "
Faltan ".count($elementos_no_en_bd)." en BD
";
print_r($elementos_no_en_bd); echo "
";
}
//Inserts
foreach($elementos_no_en_bd as $row){
if($debug){
echo "
SELECT * FROM fi_horario($dia_hoy, '".$row["data"]["HoraInicio"]."','".$row["data"]["HoraFin"]."','"
.$row["data"]["ClaveDependencia"]."','"
.$row["data"]["ClaveCarrera"]."','"
.$row["data"]["NombreMateria"]."','"
.$row["data"]["ClaveMateria"]."','"
.$row["data"]["ClaveProfesor"]."','"
.$row["data"]["NombreProfesor"]."','"
.$row["data"]["CorreoElectronico"]."','"
.$row["data"]["Grupo"]."',"
.$row["data"]["IdEspacio"].","
.$per["periodo_id"].");";
if($row["data"]["EsMateriaPorAsignacion"]){ echo " ***Asignacion directa***";}
}else{
$horario_new_rs = $db->querySingle('SELECT * FROM fi_horario(:hoy, :ini, :fin, :dep, :carr, :nom_mat, :cve_mat, :cve_prof, :nom_prof, :correo, :gpo, :espacio, :periodo)',
[":hoy"=>$dia_hoy,
":ini"=>$row["data"]["HoraInicio"],
":fin"=>$row["data"]["HoraFin"],
":dep"=>$row["data"]["ClaveDependencia"],
":carr"=>$row["data"]["ClaveCarrera"],
":nom_mat"=>$row["data"]["NombreMateria"],
":cve_mat"=>$row["data"]["ClaveMateria"],
":cve_prof"=>$row["data"]["ClaveProfesor"]==""?"000000":$row["data"]["ClaveProfesor"],
":nom_prof"=>$row["data"]["NombreProfesor"],
":correo"=>$row["data"]["CorreoElectronico"],
":gpo"=>$row["data"]["Grupo"],
":espacio"=>$row["data"]["IdEspacio"],
":periodo"=>$per["periodo_id"]
]
);
//echo $horario_new_rs["fi_horario"]."
";
if($horario_new_rs["fi_horario"] > 0){
if($row["data"]["EsMateriaPorAsignacion"]){
$matasig_rs = $db->querySingle('SELECT * FROM fi_materia_asignacion(:hor,:mat,:carr, :prof)',
[":hor"=>$horario_new_rs["fi_horario"],
":mat"=>$row["data"]["NombreMateria"],
":carr"=>$row["data"]["Carrera"],
":prof"=>$row["data"]["NombreProfesor"]
]
);
}
$log_desc .="SELECT * FROM fi_horario($dia_hoy, '".$row["data"]["HoraInicio"]."','".$row["data"]["HoraFin"]."','"
.$row["data"]["ClaveDependencia"]."','"
.$row["data"]["ClaveCarrera"]."','"
.$row["data"]["NombreMateria"]."','"
.$row["data"]["ClaveMateria"]."','"
.$row["data"]["ClaveProfesor"]."','"
.$row["data"]["NombreProfesor"]."','"
.$row["data"]["CorreoElectronico"]."','"
.$row["data"]["Grupo"]."',"
.$row["data"]["IdEspacio"]."); [ID=".$horario_new_rs["fi_horario"]."] ##";
}
}
}
if(!$debug && !empty($log_desc)){
$log = new LogCambios(__DIR__."/log/");
$log->appendLog($log_desc);
}
}
$stmt = null; // cierra conexion
if($debug) {
echo "
";
usort($elementos_sgu_total, 'compareByHash');
usort($elementos_bd_total, 'compareByHash');
echo "";
echo "";
echo "SGU [".count($elementos_sgu_total)."]";
foreach($elementos_sgu_total as $sgu){
echo $sgu["hash"]." ";
}
echo " | ";
echo "";
echo "BD [".count($elementos_bd_total)."]";
foreach($elementos_bd_total as $sgu){
echo $sgu["hash"]." [".$sgu["horario_id"]."] ";
}
echo " | ";
echo "
";
}else{
$pdo->commit();
echo "Commit";
}
} catch(PDOException $e) {
echo "Error";
"ERROR BD! ".$e->getMessage();
$pdo->rollBack();
if(!$debug){
$log = new LogCambios(__DIR__."/log/");
$log->appendLog("ERROR BD! ".$e->getMessage());
$texto = "ERROR BD
".$e->getMessage()."
";
$asunto = "Error correo automático";
Mailer::enviarCorreo("alejandro.lara@lasalle.mx", $asunto, $texto, true);
}
print_r($e->getMessage());
} catch(Exception $e2){
echo "Error";
print_r($e2->getMessage());
$texto = "EXCEPTION
".$e2->getMessage()."
";
$asunto = "Error correo automático";
Mailer::enviarCorreo("alejandro.lara@lasalle.mx", $asunto, $texto, true);
}
?>