Add new files and make code improvements

This commit is contained in:
2024-03-06 15:14:39 +00:00
parent 113ac2aedd
commit 0a712e1864
55 changed files with 9390 additions and 973 deletions

57
rest/LogCambios.php Normal file
View File

@@ -0,0 +1,57 @@
<?php
/*
* Objeto para escribir los cambios
*/
class LogCambios {
//put your code here
private $file, $month, $year;
private $dir;
function __construct($ruta = "/log/"){
$this->month = date("m");
$this->year = date("Y");
//$this->dir = $_SERVER['DOCUMENT_ROOT'].$ruta;
$this->dir = $ruta;
$this->updateFilename();
}
function setMes($mes){
$this->month = $mes;
$this->updateFilename();
}
function setAno($ano){
$this->year = $ano;
$this->updateFilename();
}
private function updateFilename(){
$this->file = "cambios_".$this->year."_".$this->month.".log";
}
private function cleanLog($text){//remueve || de los textos para no afectar estructura
return trim(str_ireplace( "||" , "" , $text));
}
function appendLog($desc){
$filename = $this->dir.$this->file;
/*
if (file_exists($this->dir)){
$data = date('Y-m-d H:i:s')."||".$this->cleanLog($desc)."\n";
//echo $filename;
$res = file_put_contents($filename, $data, FILE_APPEND);
//echo " result: $res<br>";
}*/
}
/*
function getLog($mes ="", $ano = ""){
if($mes != "") $this->setMes($mes);
if($ano != "") $this->setAno($ano);
$filename = $this->dir.$this->file;
if (file_exists($filename)){
return file ($filename , FILE_SKIP_EMPTY_LINES);
}else{
return array();
}
}*/
}

430
rest/horarios.php Normal file
View File

@@ -0,0 +1,430 @@
<?php
/*
idPeriodo: identificador del periodo a consultar (obligatorio, número entero)
claveFacultad: clave de la facultad a consultar (opcional, cadena)
claveCarrera: clave de la carrera a consultar (opcional, cadena)
claveProfesor: clave del empleado a consultar (opcional, cadena)
fecha: fecha de la clase (opcional, cadena en formato yyyy-MM-dd)
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('post_max_size', 1);
ini_set('max_execution_time', 8*60);
error_reporting(E_ALL);
date_default_timezone_set('America/Mexico_City');
$ruta = "../";
$ruta_superior = dirname(__DIR__);
require_once $ruta_superior."/include/bd_pdo_rest.php";
require_once __DIR__."/token.php";
require_once __DIR__."/LogCambios.php";
//--------------ACTUALIZA HORARIOS--------------------------
if(!empty($_GET["fecha"])){
$hoy = $_GET["fecha"];
}else{
$hoy = date("Y-m-d");
}
$dia_hoy = date("w", strtotime($hoy));
function compareByHash($a, $b) {
return strcmp($a['hash'], $b['hash']);
}
$debug = false;
if(isset($_GET["debug"])){
$debug = true;
print_r( $db->querySingle('select now()'));
}
$periodo_sgu_old = 0;
$log_desc = "";
/*$cambiocarreras_rs = $db->query('SELECT CLAVE_MATERIA, clave_carrera FROM materia join carrera using(carrera_id)');
function getCarrera($claveBuscar){
global $cambiocarreras_rs;
$i = array_search($claveBuscar, array_column($cambiocarreras_rs, 'clave_materia'));
if($i>=0)
return $cambiocarreras_rs[$i]["clave_carrera"];
return $cambiocarreras_rs[0]["clave_carrera"];
}*/
//------------------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 "$salonesTotal_rs tiene " . count($salonesData) . " salones<br>";
//if($salonesTotal_rs < count($salonesData)){//faltan salones en BD
$salones_rs = $db->query('SELECT id_espacio_sgu, salon FROM salon');
//claves de espacios
$arreglo_espacios = array_map(function ($item) {
return $item['id_espacio_sgu'];
}, $salones_rs);
$arreglo_nombres = array_map(function ($item) {
return $item['salon'];
}, $salones_rs);
foreach($salonesData as $data){
if( !in_array($data["IdEspacio"], $arreglo_espacios) || !in_array($data["NombreEspacio"], $arreglo_nombres)){
//Insertar espacio
if($debug){
echo "Espacio nuevo: ".$data["NombreEspacio"]."<br>";
}else{
$db->query('INSERT INTO SALON (salon, id_espacio_sgu, id_espacio_padre) VALUES (:salon, :id, :id_padre)
ON CONFLICT (id_espacio_sgu) DO UPDATE SET salon = :salon',
[":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 "<h3>Dia festivo en Periodo: ".$per["id_periodo_sgu"]."[".$per["periodo_id"]."]</h3>";
}
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 "<h3>Periodo: ".$per["id_periodo_sgu"]."[".$per["periodo_id"]."] nivel: ".$per["nivel_id"]."</h3>";
//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);
/*echo "Response<br>";
print_r($response);*/
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"]){
$carrera = $row["ClaveCarrera"];
if(is_null($carrera) || empty($carrera))
$carrera = '0';
/*else{
if(!$row["EsMateriaPorAsignacion"])
$carrera = getCarrera($row["ClaveMateria"]);
}*/
$sguHash[] = array(
"hash"=>( trim($row["HoraInicio"]."|".($row["NombreMateria"])."|".(trim($row["ClaveProfesor"])==""?"000000":trim($row["ClaveProfesor"]))."|".$row["IdEspacio"]."|".$per["periodo_id"]) ),
"data"=>$row,
"per"=>$per["periodo_id"]
);
}else{//reposición
try{
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 "<br>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, ".$fecha_nueva.", ".$row["ClaveProfesor"].", ".$per["periodo_id"].") ## ";
}
}else{
if($debug)
echo "No se encontró fecha y hora en: ".$row["Observaciones"]."<br>";
}
}
}catch(Exception $e){
echo "ERROR Reposición<br>".$e->getMessage();
}
}
}
unset($selectedData);
}
echo count($sguHash)."Total <br>";
$horarios_sgu = [];
/*
print_r($carreras_rs);
echo "<br><hr><br>";*/
print_r($arreglo_claves);
echo "<br><hr><br>";
//$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"].")<br>";
//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 "<h3>Resumen</h3>";
echo "<h5>SGU [".count($elementos_sgu_total)."]</h5>";
echo "<h5>BD [".count($elementos_bd_total)."]</h5>";
}
// 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');
//print_r($elementos_sgu_total);
//------------------
// 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)."<br>";
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<br>";
}
//Update fecha_fin
$log_desc = "";
foreach($elementos_no_en_sgu as $row){
try{
if($debug){
echo "<br>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"].") ## ";
}
}catch(Exception $e){
echo "ERROR horario deshabilita<br>".$e->getMessage();
}
}
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)."<br>";
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 "<br>Faltan ".count($elementos_no_en_bd)." en BD<br>";
print_r($elementos_no_en_bd); echo "<br>";
}
//Inserts
foreach($elementos_no_en_bd as $row){
if($row["data"]["ClaveMateria"] == "-")
$row["data"]["ClaveMateria"] = "";
if($debug){
echo "<br>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"].","
.$row["per"].");";
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"=>$row["per"]
]
);
//echo $horario_new_rs["fi_horario"]."<br>";
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 "<br><br><hr><br><br>";
usort($elementos_sgu_total, 'compareByHash');
usort($elementos_bd_total, 'compareByHash');
echo "<table><tr>";
echo "<td valign='top'>";
echo "<h5>SGU [".count($elementos_sgu_total)."]</h5>";
foreach($elementos_sgu_total as $sgu){
echo $sgu["hash"]."<br>";
}
echo "</td>";
echo "<td valign='top'>";
echo "<h5>BD [".count($elementos_bd_total)."]</h5>";
foreach($elementos_bd_total as $sgu){
echo $sgu["hash"]." [".$sgu["horario_id"]."]<br>";
}
echo "</td>";
echo "</tr></table>";
}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());
}
print_r($e->getMessage());
} catch(Exception $e2){
echo "Error";
print_r($e2->getMessage());
}
?>

364
rest/horarios_new.php Normal file
View File

@@ -0,0 +1,364 @@
<?php
/*
idPeriodo: identificador del periodo a consultar (obligatorio, número entero)
claveFacultad: clave de la facultad a consultar (opcional, cadena)
claveCarrera: clave de la carrera a consultar (opcional, cadena)
claveProfesor: clave del empleado a consultar (opcional, cadena)
fecha: fecha de la clase (opcional, cadena en formato yyyy-MM-dd)
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('post_max_size', 1);
ini_set('max_execution_time', 8*60);
error_reporting(E_ALL);
date_default_timezone_set('America/Mexico_City');
$ruta = "../";
$ruta_superior = dirname(__DIR__);
require_once $ruta_superior."/include/bd_pdo.php";
require_once __DIR__."/token.php";
require_once __DIR__."/LogCambios.php";
//------------------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($params),
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);
print_r($response);
$salonesTotal_rs = $db->querySingle('SELECT count(1) as total FROM salon');
echo $salonesTotal_rs["total"];
exit();
//--------------ACTUALIZA HORARIOS--------------------------
if(!empty($_GET["fecha"])){
$hoy = $_GET["fecha"];
}else{
$hoy = date("Y-m-d");
}
$dia_hoy = date("w", strtotime($hoy));
$pag = "https://portal.ulsa.edu.mx/servicios/AuditoriaAsistencialRest/AuditoriaAsistencialService.svc/auditoriaAsistencial/seleccionar";
function compareByHash($a, $b) {
return strcmp($a['hash'], $b['hash']);
}
$elementos_bd_total = [];
$elementos_sgu_total = [];
$periodo_sgu_old = 0;
$debug = false;
if(isset($_GET["debug"])){
$debug = true;
print_r( $db->querySingle('select now()'));
}
$periodo_sgu_old = 0;
$log_desc = "";
try{
$pdo->beginTransaction();
$periodos_rs = $db->query('SELECT periodo_id, id_periodo_sgu 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 "<h3>Dia festivo en Periodo: ".$per["id_periodo_sgu"]."[".$per["periodo_id"]."]</h3>";
}
continue;
}
$carreras_rs = $db->query('SELECT c.clave_carrera, c.carrera_id FROM carrera c INNER JOIN periodo_carrera pc ON c.carrera_id = pc.carrera_id WHERE pc.periodo_id = :per',
[":per"=>$per["periodo_id"]]);
if($debug)
echo "<h3>Periodo: ".$per["id_periodo_sgu"]."[".$per["periodo_id"]."]</h3>";
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);
$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"];
if($debug){
echo "<br>SELECT * FROM fi_reposicion_sgu($fecha_orig, ".$fecha_nueva.", ".$row["ClaveProfesor"].", ".$per["periodo_id"].", ".$row["IdEspacio"].")";
}else{
$db->query('SELECT * FROM fi_reposicion_sgu(:fecha_orig, :fecha_rep, :prof, :per, :salon)',
[":fecha_orig"=>$fecha_orig, ":fecha_rep"=>$fecha_nueva, ":prof"=>$row["ClaveProfesor"], ":per"=>$per["periodo_id"], ":salon"=>$row["IdEspacio"] ]);
$log_desc .="SELECT * FROM fi_reposicion_sgu($fecha_orig, ".$fecha_nueva.", ".$row["ClaveProfesor"].", ".$per["periodo_id"].") ## ";
}
}else{
if($debug)
echo "No se encontró fecha y hora en: ".$row["Observaciones"]."<br>";
}
}
}
}
unset($selectedData);
}
$horarios_sgu = [];
/*
print_r($carreras_rs);
echo "<br><hr><br>";
print_r($arreglo_claves);
echo "<br><hr><br>";*/
//$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"].")<br>";
//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 "<h3>Resumen</h3>";
echo "<h5>SGU [".count($elementos_sgu_total)."]</h5>";
echo "<h5>BD [".count($elementos_bd_total)."]</h5>";
}
// 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)."<br>";
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<br>";
}
//Update fecha_fin
$log_desc = "";
foreach($elementos_no_en_sgu as $row){
if($debug){
echo "<br>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)."<br>";
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 "<br>Faltan ".count($elementos_no_en_bd)." en BD<br>";
print_r($elementos_no_en_bd); echo "<br>";
}
//Inserts
foreach($elementos_no_en_bd as $row){
if($debug){
echo "<br>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"].");";
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)',
[":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"]]
);
echo $horario_new_rs["fi_horario"]."<br>";
if( !empty($horario_new_rs["fi_horario"]) ){
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 "<br><br><hr><br><br>";
usort($elementos_sgu_total, 'compareByHash');
usort($elementos_bd_total, 'compareByHash');
echo "<table><tr>";
echo "<td valign='top'>";
echo "<h5>SGU [".count($elementos_sgu_total)."]</h5>";
foreach($elementos_sgu_total as $sgu){
echo $sgu["hash"]."<br>";
}
echo "</td>";
echo "<td valign='top'>";
echo "<h5>BD [".count($elementos_bd_total)."]</h5>";
foreach($elementos_bd_total as $sgu){
echo $sgu["hash"]." [".$sgu["horario_id"]."]<br>";
}
echo "</td>";
echo "</tr></table>";
}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());
}
print_r($e->getMessage());
} catch(Exception $e2){
echo "Error";
print_r($e2->getMessage());
}
?>

403
rest/horarios_otro.php Normal file
View File

@@ -0,0 +1,403 @@
<?php
/*
idPeriodo: identificador del periodo a consultar (obligatorio, número entero)
claveFacultad: clave de la facultad a consultar (opcional, cadena)
claveCarrera: clave de la carrera a consultar (opcional, cadena)
claveProfesor: clave del empleado a consultar (opcional, cadena)
fecha: fecha de la clase (opcional, cadena en formato yyyy-MM-dd)
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('post_max_size', 1);
ini_set('max_execution_time', 8*60);
error_reporting(E_ALL);
date_default_timezone_set('America/Mexico_City');
$ruta = "../";
$ruta_superior = dirname(__DIR__);
require_once $ruta_superior."/include/bd_pdo.php";
require_once __DIR__."/token.php";
require_once __DIR__."/LogCambios.php";
require_once __DIR__."/include/mailer.php";
require_once __DIR__.'/include/phpmailer/PHPMailerAutoload.php';
//--------------ACTUALIZA HORARIOS--------------------------
if(!empty($_GET["fecha"])){
$hoy = $_GET["fecha"];
}else{
$hoy = date("Y-m-d");
}
$dia_hoy = date("w", strtotime($hoy));
function compareByHash($a, $b) {
return strcmp($a['hash'], $b['hash']);
}
$debug = false;
if(isset($_GET["debug"])){
$debug = true;
print_r( $db->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<br>";
if($salonesTotal_rs < count($salonesData)){//faltan salones en BD
echo "Actualizar salones<br>";
$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"]."<br>";
}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 "<h3>Dia festivo en Periodo: ".$per["id_periodo_sgu"]."[".$per["periodo_id"]."]</h3>";
}
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 "<h3>Periodo: ".$per["id_periodo_sgu"]."[".$per["periodo_id"]."] nivel: ".$per["nivel_id"]."</h3>";
//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 "<br>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"]."<br>";
}
}
}
}
unset($selectedData);
}
$horarios_sgu = [];
/*
print_r($carreras_rs);
echo "<br><hr><br>";*/
print_r($arreglo_claves);
echo "<br><hr><br>";
//$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"].")<br>";
//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 "<h3>Resumen</h3>";
echo "<h5>SGU [".count($elementos_sgu_total)."]</h5>";
echo "<h5>BD [".count($elementos_bd_total)."]</h5>";
}
// 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)."<br>";
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<br>";
}
//Update fecha_fin
$log_desc = "";
foreach($elementos_no_en_sgu as $row){
if($debug){
echo "<br>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)."<br>";
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 "<br>Faltan ".count($elementos_no_en_bd)." en BD<br>";
print_r($elementos_no_en_bd); echo "<br>";
}
//Inserts
foreach($elementos_no_en_bd as $row){
if($debug){
echo "<br>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"]."<br>";
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 "<br><br><hr><br><br>";
usort($elementos_sgu_total, 'compareByHash');
usort($elementos_bd_total, 'compareByHash');
echo "<table><tr>";
echo "<td valign='top'>";
echo "<h5>SGU [".count($elementos_sgu_total)."]</h5>";
foreach($elementos_sgu_total as $sgu){
echo $sgu["hash"]."<br>";
}
echo "</td>";
echo "<td valign='top'>";
echo "<h5>BD [".count($elementos_bd_total)."]</h5>";
foreach($elementos_bd_total as $sgu){
echo $sgu["hash"]." [".$sgu["horario_id"]."]<br>";
}
echo "</td>";
echo "</tr></table>";
}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 = "<h1>ERROR BD</h1><p>".$e->getMessage()."</p>";
$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 = "<h1>EXCEPTION</h1><p>".$e2->getMessage()."</p>";
$asunto = "Error correo automático";
Mailer::enviarCorreo("alejandro.lara@lasalle.mx", $asunto, $texto, true);
}
?>

95
rest/include/mailer.php Normal file
View File

@@ -0,0 +1,95 @@
<?php
//https://github.com/PHPMailer/PHPMailer
//require_once('../include/phpmailer/PHPMailerAutoload.php');
class Mailer{
private const FROM = "academia@lasalle.mx";
private const FROM_NAME = "Vicerrectoría Académica";
private const FROM_PASS = "Foy25193";
private const FOOTER = "<p style='margin-top:5em; color:#aaa;font-style:italics'><small>Este es un correo automatizado, esta cuenta no recibe correos.<small></p>";
//private $lista_to, $asunto, $texto;
/**
* Función estática para mandar correos. Los destinatarios pueden ser arreglo o cadena separada por ; incluir: include/phpmailer/PHPMailerAutoload.php
*
* @param array|string $lista_to El destinatario o lista de destinatarios. Puede ser un arreglo de direcciones de correo electrónico o una cadena de texto con direcciones de correo separadas por ;.
* @param string $asunto El asunto del correo.
* @param string $texto El cuerpo del mensaje del correo en HTML.
* @param bool $bcc Indica si se debe enviar el correo como copia oculta (true) o no (false). Valor por defecto: false.
*
* @return bool True si el correo se envió exitosamente, false en caso contrario.
*/
public static function enviarCorreo($lista_to, $asunto, $texto, $bcc = false){
try{
//SMTP Settings
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'TLS';
$mail->Host = "smtp.office365.com";
$mail->Port = 587;
$mail->Username = self::FROM;
$mail->Password = self::FROM_PASS;
$mail->SetFrom(self::FROM, self::FROM_NAME); //from (verified email address)
$mail->Subject = $asunto; //subject
$mail->IsHTML(true);
$mail->MsgHTML($texto.self::FOOTER);//adjunta footer
//recipient
if(is_array($lista_to)){
foreach($lista_to as $correo){
if(trim($correo)!="")
if($bcc)
$mail->addBCC($correo);
else
$mail->AddAddress($correo);
}
}else{//cadena de texto separada por ;
if(strpos($lista_to, ";")!==false){
$toArr = explode(";", $lista_to);
foreach($toArr as $correo){
if(trim($correo)!=""){
if($bcc)
$mail->addBCC($correo);
else
$mail->AddAddress($correo);
}
}
}elseif(strpos($lista_to, ",")!==false){
$toArr = explode(",", $lista_to);
foreach($toArr as $correo){
if(trim($correo)!=""){
if($bcc)
$mail->addBCC($correo);
else
$mail->AddAddress($correo);
}
}
}else{
if(trim($lista_to)!=""){
if($bcc)
$mail->addBCC($lista_to);
else
$mail->AddAddress($lista_to);
}
}
}
//Success
if ($mail->Send()) {
return true;
}
}catch(phpmailerException $e){
echo $mail->ErrorInfo;
return false;
}catch(Exception $e2){
echo $mail->ErrorInfo;
return false;
}
return false;
}
}

View File

@@ -0,0 +1,50 @@
<?php
/**
* PHPMailer SPL autoloader.
* PHP Version 5
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2014 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
/**
* PHPMailer SPL autoloader.
* @param string $classname The name of the class to load
*/
function PHPMailerAutoload($classname)
{
//Can't use __DIR__ as it's only in PHP 5.3+
$filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php';
if (is_readable($filename)) {
require $filename;
}
}
if (version_compare(PHP_VERSION, '5.1.2', '>=')) {
//SPL autoloading was introduced in PHP 5.1.2
if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
spl_autoload_register('PHPMailerAutoload', true, true);
} else {
spl_autoload_register('PHPMailerAutoload');
}
} else {
/**
* Fall back to traditional autoload for old PHP versions
* @param string $classname The name of the class to load
*/
spl_autoload_register($classname);
/*function __autoload($classname)
{
PHPMailerAutoload($classname);
}*/
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

3
rest/info.php Normal file
View File

@@ -0,0 +1,3 @@
<?php
phpinfo();
?>

File diff suppressed because one or more lines are too long

252
rest/materias.php Normal file
View File

@@ -0,0 +1,252 @@
<style>
details {
border: 1px solid #aaa;
border-radius: 4px;
padding: 0.5em 0.5em 0;
margin: 0.5em 0;
}
summary {
font-weight: bold;
margin: -0.5em -0.5em 0;
padding: 0.5em;
}
details[open] {
padding: 0.5em;
}
details[open] summary {
border-bottom: 1px solid #aaa;
margin-bottom: 0.5em;
}
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
th,
td {
padding: 8px;
border: 1px solid #ccc;
text-align: left;
}
th {
background-color: #f2f2f2;
}
tr:nth-child(even):not(.empty):not(.area-comun) {
background-color: #f9f9f9;
}
.json-container {
white-space: pre-wrap;
/* Since JSON is formatted with whitespace, this will keep formatting */
word-break: break-word;
/* To prevent horizontal scrolling */
max-height: 150px;
/* Set a max-height and add scroll to prevent very long JSON from cluttering the table */
overflow-y: auto;
}
.empty {
/* rosa pastel */
background-color: #ffe8f4;
}
.area-comun {
/* naranja pastel */
background-color: #ffe9d4;
}
</style>
<?php
/*
idPeriodo: identificador del periodo a consultar (obligatorio, número entero)
claveFacultad: clave de la facultad a consultar (opcional, cadena)
claveCarrera: clave de la carrera a consultar (opcional, cadena)
claveProfesor: clave del empleado a consultar (opcional, cadena)
fecha: fecha de la clase (opcional, cadena en formato yyyy-MM-dd)
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('post_max_size', 1);
ini_set('max_execution_time', 8 * 60);
error_reporting(E_ALL);
date_default_timezone_set('America/Mexico_City');
$ruta = "../";
$ruta_superior = dirname(__DIR__);
require_once $ruta_superior . "/include/bd_pdo.php";
require_once __DIR__ . "/token.php";
require_once __DIR__ . "/LogCambios.php";
$fecha = isset($_GET["fecha"]) ? $_GET["fecha"] : date("Y-m-d");
$periodos = $db
->where("id_periodo_sgu", 0, ">")
->where("periodo_fecha_inicio", $fecha, "<=")
->where("periodo_fecha_fin", $fecha, ">=")
->orderBy("periodo_id")
->get("periodo");
?>
<nav>
<form action="" method="get">
<label for="fecha">Fecha</label>
<input type="date" name="fecha" id="fecha" value="<?= $fecha ?>">
<button type="submit">Buscar</button>
</form>
<details>
<summary>Periodos</summary>
<pre>
<code><?= json_encode($periodos, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?></code>
</pre>
</details>
<?php
$horarios = array();
foreach (array_column($periodos, "id_periodo_sgu") as $idPeriodo) {
$curl = curl_init();
$params = array(
'idPeriodo' => $idPeriodo,
'fecha' => $fecha,
);
curl_setopt_array($curl, [
CURLOPT_URL => 'https://portal.ulsa.edu.mx/servicios/AuditoriaAsistencialRest/AuditoriaAsistencialService.svc/auditoriaAsistencial/seleccionar',
CURLOPT_RETURNTRANSFER => true,
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);
$response = json_decode($response, true, 512, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$horarios = array_merge($horarios, $response);
?>
<details>
<summary>Periodo
<?= $idPeriodo ?>
</summary>
<pre><code><?= json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?></code></pre>
</details>
<?php } ?>
</nav>
<main>
<p>
<?= count($horarios) ?> horarios encontrados para
<?= $fecha ?>
</p>
<table>
<thead>
<tr>
<th>Materia en SGU</th>
<th>Materia en Postgres</th>
</tr>
</thead>
<tbody>
<?php
// $horarios with unique "NombreMateria" field
$horarios = array_map("unserialize", array_unique(array_map("serialize", $horarios)));
foreach ($horarios as $horario) {
$materias = $db
->where("materia_nombre", trim($horario["NombreMateria"]), "ILIKE")
->join("carrera", "carrera.carrera_id = materia.carrera_id")
->join("facultad", "facultad.facultad_id = carrera.facultad_id")
->get("materia");
if (
count(array_filter($materias, fn($m) =>
$m["clave_materia"] == trim($horario["ClaveMateria"]) and
$m["clave_carrera"] == trim($horario["ClaveCarrera"]))) > 0
) {
continue;
}
// si de las materias alguna tiene carrera_id entre 1 y 4 entonces es de área común
$area_comun = count(array_filter($materias, fn($m) => $m["carrera_id"] >= 1 and $m["carrera_id"] <= 4)) > 0;
$vacío = count($materias) == 0;
?>
<!-- si es vacío ponle la clase empty y si es área común ponle la clase area-comun -->
<tr class="<?= $vacío ? "empty" : "" ?> <?= $area_comun ? "area-comun" : "" ?>">
<td class="json-container">
<details>
<summary>Horario</summary>
<pre><code><?= json_encode($horario, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?></code></pre>
</details>
<?= json_encode(array_intersect_key($horario, array_flip(["ClaveMateria", "NombreMateria", "ClaveCarrera", "Dependencia"])), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>
</td>
<td class="json-container">
<?php if ($vacío) { ?>
<p>No se encontraron materias</p>
<?php } else { ?>
<details>
<summary>Materias</summary>
<pre><code><?= json_encode($materias, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?></code></pre>
</details>
<table>
<thead>
<tr>
<th>Materia</th>
<th>Carrera</th>
<th>Facultad</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<script>
async function copiar_seleccionados() {
// en mi clipboard quiero (join con ,)
const materias_seleccionadas = Array.from(document.querySelectorAll("input[name='materia_id']:checked"))
.map(input => input.value)
.join(",");
// copiar al clipboard
await navigator.clipboard.writeText(materias_seleccionadas);
// mostrar mensaje de éxito
alert("Copiado al portapapeles");
}
</script>
<?php foreach ($materias as $materia) { ?>
<tr>
<td>
<input type="checkbox" name="materia_id" id="materia_id"
value="<?= $materia["materia_id"] ?>">
</td>
<td>
<?= $materia["materia_id"] ?>
<small>
(
<?= $materia["clave_materia"] ?>)
</small>
<?= $materia["materia_nombre"] ?>
</td>
<td>
<small>
(
<?= $materia["clave_carrera"] ?>)
</small>
<?= $materia["carrera_nombre"] ?>
</td>
<td>
<small>
(
<?= $materia["clave_dependencia"] ?>)
</small>
<?= $materia["facultad_nombre"] ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</main>

149
rest/salon.php Normal file
View File

@@ -0,0 +1,149 @@
<style>
details {
border: 1px solid #aaa;
border-radius: 4px;
padding: 0.5em 0.5em 0;
margin: 0.5em 0;
}
summary {
font-weight: bold;
margin: -0.5em -0.5em 0;
padding: 0.5em;
}
details[open] {
padding: 0.5em;
}
details[open] summary {
border-bottom: 1px solid #aaa;
margin-bottom: 0.5em;
}
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
th,
td {
padding: 8px;
border: 1px solid #ccc;
text-align: left;
}
th {
background-color: #f2f2f2;
}
.json-container {
white-space: pre-wrap;
/* Since JSON is formatted with whitespace, this will keep formatting */
word-break: break-word;
/* To prevent horizontal scrolling */
max-height: 150px;
/* Set a max-height and add scroll to prevent very long JSON from cluttering the table */
overflow-y: auto;
}
.empty {
/* rosa pastel */
background-color: #ffe8f4;
}
.no-igual {
/* púrpura pastel */
background-color: #f4e8ff;
}
</style>
<?php
/*
idPeriodo: identificador del periodo a consultar (obligatorio, número entero)
claveFacultad: clave de la facultad a consultar (opcional, cadena)
claveCarrera: clave de la carrera a consultar (opcional, cadena)
claveProfesor: clave del empleado a consultar (opcional, cadena)
fecha: fecha de la clase (opcional, cadena en formato yyyy-MM-dd)
*/
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('post_max_size', 1);
ini_set('max_execution_time', 8 * 60);
error_reporting(E_ALL);
date_default_timezone_set('America/Mexico_City');
$ruta = "../";
$ruta_superior = dirname(__DIR__);
require_once $ruta_superior . "/include/bd_pdo.php";
require_once __DIR__ . "/token.php";
require_once __DIR__ . "/LogCambios.php";
$salon = array();
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL =>
'https://portal.ulsa.edu.mx/servicios/AuditoriaAsistencialRest/AuditoriaAsistencialService.svc/auditoriaAsistencial/catalogos/espacios/seleccionar',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode([]),
CURLOPT_HTTPHEADER => [
"token: $token",
'username: SGU_APSA_AUD_ASIST',
'Content-Type: application/json',
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$json_flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT;
$salones = json_decode($response, true, 512, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
?>
<main>
<p>
<?= count($salones) ?> salones encontrados
</p>
<table>
<thead>
<tr>
<th>Salones en SGU</th>
<th>SALONES en Postgres</th>
</tr>
</thead>
<tbody>
<?php
foreach ($salones as $salon) {
$salon_db = $db->where("id_espacio_sgu", $salon["IdEspacio"])->get("salon");
// si de el salon es igual NombreEspacio == salon
$vacío = empty($salon_db);
$igual = $salon["NombreEspacio"] == ($salon["salon"] ?? "");
if ($vacío) {
$db->insert("salon", [
"id_espacio_sgu" => $salon["IdEspacio"],
"salon" => $salon["NombreEspacio"],
"id_espacio_padre" => $salon["IdEspacioPadre"] > 0 ? $salon["IdEspacioPadre"] : null,
]);
} else if (!$igual) {
$db->where("id_espacio_sgu", $salon["IdEspacio"])->update("salon", [
"salon" => $salon["NombreEspacio"],
// "id_espacio_padre" => $salon["IdEspacioPadre"] > 0 ? $salon["IdEspacioPadre"] : null,
]);
}
?>
<tr class="<?= $igual ? "empty" : "no-igual" ?>">
<td class="json-container">
<?= json_encode($salon, $json_flags) ?>
</td>
<td class="json-container">
<?= json_encode($salon_db, $json_flags) ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</main>

35
rest/token.php Normal file
View File

@@ -0,0 +1,35 @@
<?php
/*
idPeriodo: identificador del periodo a consultar (obligatorio, número entero)
*/
$ruta = "https://portal.ulsa.edu.mx/servicios/AuditoriaAsistencialRest/AuditoriaAsistencialService.svc/auditoriaAsistencial/inicioSesion/seleccionar";
$required_params = [
"username"=>"SGU_APSA_AUD_ASIST",
"password"=>"B4qa594JFPr2ufHrZdHS8A=="
];
try{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $ruta,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($required_params),
CURLOPT_HTTPHEADER => array('Content-Type:application/json'),
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err)
die("cURL Error #:$err");
$token = json_decode($response, true);
//echo "token $token";
}catch(Exception $e){
echo $e->getMessage();
exit();
}
?>

41
rest/token.php.save Normal file
View File

@@ -0,0 +1,41 @@
<?php
/*
idPeriodo: identificador del periodo a consultar (obligatorio, número entero)
*/
$ruta = "https://portal.ulsa.edu.mx/servicios/AuditoriaAsistencialRest/AuditoriaAsistencialService.svc/auditoriaAsistencial/inicioSesion/seleccionar";
$required_params = [
"username"=>"SGU_APSA_AUD_ASIST",
"password"=>"B4qa594JFPr2ufHrZdHS8A=="
];
try{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $ruta,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($required_params),
CURLOPT_HTTPHEADER => [
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
print_r($response);
$err = curl_error($curl);
curl_close($curl);
if ($err)
die("cURL Error #:$err");
$token = json_decode($response, true);
echo "token $token";
}catch(Exception $e){
echo $e->getMessage();
exit();
}
?>

41
rest/token.php.save.1 Normal file
View File

@@ -0,0 +1,41 @@
<?php
/*
idPeriodo: identificador del periodo a consultar (obligatorio, número entero)
*/
$ruta = "https://portal.ulsa.edu.mx/servicios/AuditoriaAsistencialRest/AuditoriaAsistencialService.svc/auditoriaAsistencial/inicioSesion/seleccionar";
$required_params = [
"username"=>"SGU_APSA_AUD_ASIST",
"password"=>"B4qa594JFPr2ufHrZdHS8A=="
];
try{
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $ruta,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($required_params),
CURLOPT_HTTPHEADER => [
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
print_r($response);
$err = curl_error($curl);
curl_close($curl);
if ($err)
die("cURL Error #:$err");
$token = json_decode($response, true);
echo "token $token";
}catch(Exception $e){
echo $e->getMessage();
exit();
}
?>