horarios_otro.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. <?php
  2. /*
  3. idPeriodo: identificador del periodo a consultar (obligatorio, número entero)
  4. claveFacultad: clave de la facultad a consultar (opcional, cadena)
  5. claveCarrera: clave de la carrera a consultar (opcional, cadena)
  6. claveProfesor: clave del empleado a consultar (opcional, cadena)
  7. fecha: fecha de la clase (opcional, cadena en formato yyyy-MM-dd)
  8. */
  9. ini_set('display_errors', 1);
  10. ini_set('display_startup_errors', 1);
  11. ini_set('post_max_size', 1);
  12. ini_set('max_execution_time', 8*60);
  13. error_reporting(E_ALL);
  14. date_default_timezone_set('America/Mexico_City');
  15. $ruta = "../";
  16. $ruta_superior = dirname(__DIR__);
  17. require_once $ruta_superior."/include/bd_pdo.php";
  18. require_once __DIR__."/token.php";
  19. require_once __DIR__."/LogCambios.php";
  20. require_once __DIR__."/include/mailer.php";
  21. require_once __DIR__.'/include/phpmailer/PHPMailerAutoload.php';
  22. //--------------ACTUALIZA HORARIOS--------------------------
  23. if(!empty($_GET["fecha"])){
  24. $hoy = $_GET["fecha"];
  25. }else{
  26. $hoy = date("Y-m-d");
  27. }
  28. $dia_hoy = date("w", strtotime($hoy));
  29. function compareByHash($a, $b) {
  30. return strcmp($a['hash'], $b['hash']);
  31. }
  32. $debug = false;
  33. if(isset($_GET["debug"])){
  34. $debug = true;
  35. print_r( $db->querySingle('select now()'));
  36. }
  37. $periodo_sgu_old = 0;
  38. $log_desc = "";
  39. //------------------ACTUALIZA SALONES----------------------
  40. $pag = "https://portal.ulsa.edu.mx/servicios/AuditoriaAsistencialRest/AuditoriaAsistencialService.svc/auditoriaAsistencial/catalogos/espacios/seleccionar";
  41. $curl = curl_init();
  42. curl_setopt_array($curl, [
  43. CURLOPT_URL => $pag,
  44. CURLOPT_RETURNTRANSFER => true,
  45. //CURLOPT_ENCODING => "",
  46. //CURLOPT_MAXREDIRS => 10,
  47. // CURLOPT_TIMEOUT => 0,
  48. //CURLOPT_CUSTOMREQUEST => "POST",
  49. CURLOPT_POSTFIELDS => json_encode([]),
  50. CURLOPT_HTTPHEADER => [
  51. "token: ".$token,
  52. "username: SGU_APSA_AUD_ASIST",
  53. "Content-Type: application/json",
  54. 'Transfer-Encoding: chunked'
  55. ],
  56. ]);
  57. $response = curl_exec($curl);
  58. $err = curl_error($curl);
  59. curl_close($curl);
  60. if ($err)
  61. die("cURL Error #:$err");
  62. $salonesData = json_decode($response, true);
  63. //$salonesTotal_rs = $db->count('salon');
  64. $salonesTotal_rs = $db->where('salon_id', 0, '>')->count('salon');
  65. echo "BD $salonesTotal_rs vs SGU " . count($salonesData) . " salones<br>";
  66. if($salonesTotal_rs < count($salonesData)){//faltan salones en BD
  67. echo "Actualizar salones<br>";
  68. $salones_rs = $db->query('SELECT id_espacio_sgu FROM salon');
  69. //claves de espacios
  70. $arreglo_espacios = array_map(function ($item) {
  71. return $item['id_espacio_sgu'];
  72. }, $salones_rs);
  73. foreach($salonesData as $data){
  74. if( !in_array($data["IdEspacio"], $arreglo_espacios)){
  75. //Insertar espacio
  76. if($debug){
  77. echo "Espacio nuevo: ".$data["NombreEspacio"]."<br>";
  78. }else{
  79. $db->query('INSERT INTO SALON (salon, id_espacio_sgu, id_espacio_padre) VALUES (:salon, :id, :id_padre)',
  80. [":salon"=>$data["NombreEspacio"], ":id"=>$data["IdEspacio"], ":id_padre"=>$data["IdEspacioPadre"]]);
  81. }
  82. }
  83. }
  84. }
  85. // -----------------------------
  86. $pag = "https://portal.ulsa.edu.mx/servicios/AuditoriaAsistencialRest/AuditoriaAsistencialService.svc/auditoriaAsistencial/seleccionar";
  87. $elementos_bd_total = [];
  88. $elementos_sgu_total = [];
  89. $periodo_sgu_old = 0;
  90. try{
  91. $pdo->beginTransaction();
  92. $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',
  93. [":hoy"=>$hoy]);
  94. foreach ($periodos_rs as $per){
  95. //Verifica si el día de hoy es festivo
  96. $vacacion_rs = $db->querySingle('select es_festivo(:per, :hoy)', [":per"=>$per["periodo_id"], ":hoy"=>$hoy]);
  97. if($vacacion_rs["es_festivo"]){
  98. if($debug){
  99. echo "<h3>Dia festivo en Periodo: ".$per["id_periodo_sgu"]."[".$per["periodo_id"]."]</h3>";
  100. }
  101. continue;
  102. }
  103. $carreras_rs = $db->query('SELECT c.clave_carrera, c.carrera_id FROM carrera c WHERE nivel_id = :nivel',
  104. [":nivel"=>$per["nivel_id"]]);
  105. if($debug){
  106. echo "<h3>Periodo: ".$per["id_periodo_sgu"]."[".$per["periodo_id"]."] nivel: ".$per["nivel_id"]."</h3>";
  107. //print_r($carreras_rs);
  108. }
  109. if ($periodo_sgu_old != $per["id_periodo_sgu"]){
  110. $periodo_sgu_old = $per["id_periodo_sgu"];
  111. $params = [
  112. 'idPeriodo'=>$per["id_periodo_sgu"],
  113. 'fecha'=>$hoy
  114. ];
  115. $curl = curl_init();
  116. curl_setopt_array($curl, [
  117. CURLOPT_URL => $pag,
  118. CURLOPT_RETURNTRANSFER => true,
  119. //CURLOPT_ENCODING => "",
  120. //CURLOPT_MAXREDIRS => 10,
  121. //CURLOPT_TIMEOUT => 0,
  122. //CURLOPT_CUSTOMREQUEST => "POST",
  123. CURLOPT_POSTFIELDS => json_encode($params),
  124. CURLOPT_HTTPHEADER => [
  125. "token: ".$token,
  126. "username: SGU_APSA_AUD_ASIST",
  127. "Content-Type: application/json"
  128. ],
  129. ]);
  130. $response = curl_exec($curl);
  131. $err = curl_error($curl);
  132. curl_close($curl);
  133. if ($err)
  134. die("cURL Error #:$err");
  135. }
  136. $selectedData = json_decode($response, true);
  137. //claves de carreras en el periodo
  138. $arreglo_claves = array_map(function ($item) {
  139. return $item['clave_carrera'];
  140. }, $carreras_rs);
  141. //print_r($selectedData); exit();
  142. $sguHash = array();
  143. if(!empty($selectedData)){
  144. //Recorre SGU y genera hash
  145. foreach( $selectedData as $row ){
  146. if(!$row["EsMateriaPorReposicion"]){
  147. $sguHash[] = array(
  148. "hash"=>( trim($row["HoraInicio"]."|".($row["NombreMateria"])."|".(trim($row["ClaveProfesor"])==""?"000000":trim($row["ClaveProfesor"]))."|".$row["IdEspacio"]) ),
  149. "data"=>$row
  150. );
  151. }else{//reposición
  152. if(in_array($row["ClaveCarrera"] , $arreglo_claves)){
  153. //busca yyyy-mm-dd hh:mm:ss en la cadena
  154. if (preg_match("/\d{4}-\d{2}-\d{2} de \d{2}:\d{2}:\d{2}/", $row["Observaciones"], $matches)) {
  155. $fecha_orig = str_replace(" de", "", $matches[0]);
  156. $fecha_nueva = $row["FechaStr"]." ".$row["HoraInicio"];
  157. $hora_fin_nueva = $row["HoraFin"];
  158. if($debug){
  159. echo "<br>SELECT * FROM fi_reposicion_sgu($fecha_orig, ".$hora_fin_nueva.",".$fecha_nueva." ,".$row["ClaveProfesor"].", ".$per["periodo_id"].", ".$row["IdEspacio"].")";
  160. }else{
  161. $db->query('SELECT * FROM fi_reposicion_sgu(:fecha_orig, :hora_fin, :fecha_rep, :prof, :per, :salon)',
  162. [":fecha_orig"=>$fecha_orig, ":hora_fin"=>$hora_fin_nueva, ":fecha_rep"=>$fecha_nueva, ":prof"=>$row["ClaveProfesor"], ":per"=>$per["periodo_id"], ":salon"=>$row["IdEspacio"] ]);
  163. $log_desc .="SELECT * FROM fi_reposicion_sgu($fecha_orig, ".$hora_fin_nueva.",".$fecha_nueva." ,".$row["ClaveProfesor"].", ".$per["periodo_id"].", ".$row["IdEspacio"].") ## ";
  164. }
  165. }else{
  166. if($debug)
  167. echo "No se encontró fecha y hora en: ".$row["Observaciones"]."<br>";
  168. }
  169. }
  170. }
  171. }
  172. unset($selectedData);
  173. }
  174. $horarios_sgu = [];
  175. /*
  176. print_r($carreras_rs);
  177. echo "<br><hr><br>";*/
  178. print_r($arreglo_claves);
  179. echo "<br><hr><br>";
  180. //$areacomun = array();
  181. foreach($sguHash as $sgu){
  182. if(in_array($sgu["data"]["ClaveCarrera"] , $arreglo_claves) /*&& !in_array($sgu["data"]["ClaveMateria"], $areacomun)*/){
  183. $horarios_sgu[] = $sgu;
  184. }
  185. }
  186. //print_r($horarios_sgu);exit();
  187. unset($sguHash);
  188. $elementos_sgu_total = array_merge($elementos_sgu_total, $horarios_sgu);
  189. //Recorre BD y genera hash
  190. $horarios_rs = $db->query('SELECT * FROM fs_horarios_hash(:dia, :periodo, :fecha)',
  191. [':dia' => $dia_hoy, ':periodo' => $per["periodo_id"], ':fecha'=>$hoy]);
  192. //echo "**** SELECT * FROM fs_horarios_hash($dia_hoy, ".$per["periodo_id"].")<br>";
  193. //usort($horarios_rs, 'compareByHash');
  194. $elementos_bd_total = array_merge($elementos_bd_total, $horarios_rs);
  195. }//foreach periodo
  196. //print_r($elementos_sgu_total);
  197. //exit();
  198. if($debug){
  199. echo "<h3>Resumen</h3>";
  200. echo "<h5>SGU [".count($elementos_sgu_total)."]</h5>";
  201. echo "<h5>BD [".count($elementos_bd_total)."]</h5>";
  202. }
  203. // Extraer los "hash" de $lista y $lista2 en arreglos separados
  204. $hashes_sgu = array_column($elementos_sgu_total, 'hash');
  205. $hashes_bd = array_column($elementos_bd_total, 'hash');
  206. //------------------
  207. // Encontrar los "hash" que están en $sgu pero no están en $bd
  208. $hashes_no_en_sgu = array_diff($hashes_bd, $hashes_sgu);
  209. if($debug) echo "hashes_no_en_sgu ".count($hashes_no_en_sgu)."<br>";
  210. if(count($hashes_no_en_sgu)>0){
  211. // Ahora puedes obtener los elementos completos que cumplen la condición original
  212. $elementos_no_en_sgu = array_filter($elementos_bd_total, function ($item) use ($hashes_no_en_sgu) {
  213. return in_array($item['hash'], $hashes_no_en_sgu);
  214. });
  215. if($debug){
  216. print_r($elementos_no_en_sgu);
  217. echo "Sobran ".count($elementos_no_en_sgu)." en BD<br>";
  218. }
  219. //Update fecha_fin
  220. $log_desc = "";
  221. foreach($elementos_no_en_sgu as $row){
  222. if($debug){
  223. echo "<br>SELECT * FROM fu_horario_deshabilita(".$row["horario_id"].")";
  224. }else{
  225. $db->query('SELECT * FROM fu_horario_deshabilita(:horario)', [":horario"=>$row["horario_id"]]);
  226. $log_desc .="SELECT * FROM fu_horario_deshabilita(".$row["horario_id"].") ## ";
  227. }
  228. }
  229. if(!$debug && !empty($log_desc)){
  230. $log = new LogCambios(__DIR__."/log/");
  231. $log->appendLog($log_desc);
  232. }
  233. }
  234. // Encontrar los "hash" que están en $sgu pero no están en $bd
  235. $hashes_no_en_bd = array_diff($hashes_sgu, $hashes_bd);
  236. //echo "hashes_no_en_bd ".count($hashes_no_en_bd)."<br>";
  237. if(count($hashes_no_en_bd)>0){
  238. // Ahora puedes obtener los elementos completos que cumplen la condición original
  239. $elementos_no_en_bd = array_filter($elementos_sgu_total, function ($item) use ($hashes_no_en_bd) {
  240. return in_array($item['hash'], $hashes_no_en_bd);
  241. });
  242. if($debug){
  243. echo "<br>Faltan ".count($elementos_no_en_bd)." en BD<br>";
  244. print_r($elementos_no_en_bd); echo "<br>";
  245. }
  246. //Inserts
  247. foreach($elementos_no_en_bd as $row){
  248. if($debug){
  249. echo "<br>SELECT * FROM fi_horario($dia_hoy, '".$row["data"]["HoraInicio"]."','".$row["data"]["HoraFin"]."','"
  250. .$row["data"]["ClaveDependencia"]."','"
  251. .$row["data"]["ClaveCarrera"]."','"
  252. .$row["data"]["NombreMateria"]."','"
  253. .$row["data"]["ClaveMateria"]."','"
  254. .$row["data"]["ClaveProfesor"]."','"
  255. .$row["data"]["NombreProfesor"]."','"
  256. .$row["data"]["CorreoElectronico"]."','"
  257. .$row["data"]["Grupo"]."',"
  258. .$row["data"]["IdEspacio"].","
  259. .$per["periodo_id"].");";
  260. if($row["data"]["EsMateriaPorAsignacion"]){ echo " ***Asignacion directa***";}
  261. }else{
  262. $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)',
  263. [":hoy"=>$dia_hoy,
  264. ":ini"=>$row["data"]["HoraInicio"],
  265. ":fin"=>$row["data"]["HoraFin"],
  266. ":dep"=>$row["data"]["ClaveDependencia"],
  267. ":carr"=>$row["data"]["ClaveCarrera"],
  268. ":nom_mat"=>$row["data"]["NombreMateria"],
  269. ":cve_mat"=>$row["data"]["ClaveMateria"],
  270. ":cve_prof"=>$row["data"]["ClaveProfesor"]==""?"000000":$row["data"]["ClaveProfesor"],
  271. ":nom_prof"=>$row["data"]["NombreProfesor"],
  272. ":correo"=>$row["data"]["CorreoElectronico"],
  273. ":gpo"=>$row["data"]["Grupo"],
  274. ":espacio"=>$row["data"]["IdEspacio"],
  275. ":periodo"=>$per["periodo_id"]
  276. ]
  277. );
  278. //echo $horario_new_rs["fi_horario"]."<br>";
  279. if($horario_new_rs["fi_horario"] > 0){
  280. if($row["data"]["EsMateriaPorAsignacion"]){
  281. $matasig_rs = $db->querySingle('SELECT * FROM fi_materia_asignacion(:hor,:mat,:carr, :prof)',
  282. [":hor"=>$horario_new_rs["fi_horario"],
  283. ":mat"=>$row["data"]["NombreMateria"],
  284. ":carr"=>$row["data"]["Carrera"],
  285. ":prof"=>$row["data"]["NombreProfesor"]
  286. ]
  287. );
  288. }
  289. $log_desc .="SELECT * FROM fi_horario($dia_hoy, '".$row["data"]["HoraInicio"]."','".$row["data"]["HoraFin"]."','"
  290. .$row["data"]["ClaveDependencia"]."','"
  291. .$row["data"]["ClaveCarrera"]."','"
  292. .$row["data"]["NombreMateria"]."','"
  293. .$row["data"]["ClaveMateria"]."','"
  294. .$row["data"]["ClaveProfesor"]."','"
  295. .$row["data"]["NombreProfesor"]."','"
  296. .$row["data"]["CorreoElectronico"]."','"
  297. .$row["data"]["Grupo"]."',"
  298. .$row["data"]["IdEspacio"]."); [ID=".$horario_new_rs["fi_horario"]."] ##";
  299. }
  300. }
  301. }
  302. if(!$debug && !empty($log_desc)){
  303. $log = new LogCambios(__DIR__."/log/");
  304. $log->appendLog($log_desc);
  305. }
  306. }
  307. $stmt = null; // cierra conexion
  308. if($debug) {
  309. echo "<br><br><hr><br><br>";
  310. usort($elementos_sgu_total, 'compareByHash');
  311. usort($elementos_bd_total, 'compareByHash');
  312. echo "<table><tr>";
  313. echo "<td valign='top'>";
  314. echo "<h5>SGU [".count($elementos_sgu_total)."]</h5>";
  315. foreach($elementos_sgu_total as $sgu){
  316. echo $sgu["hash"]."<br>";
  317. }
  318. echo "</td>";
  319. echo "<td valign='top'>";
  320. echo "<h5>BD [".count($elementos_bd_total)."]</h5>";
  321. foreach($elementos_bd_total as $sgu){
  322. echo $sgu["hash"]." [".$sgu["horario_id"]."]<br>";
  323. }
  324. echo "</td>";
  325. echo "</tr></table>";
  326. }else{
  327. $pdo->commit();
  328. echo "Commit";
  329. }
  330. } catch(PDOException $e) {
  331. echo "Error";
  332. "ERROR BD! ".$e->getMessage();
  333. $pdo->rollBack();
  334. if(!$debug){
  335. $log = new LogCambios(__DIR__."/log/");
  336. $log->appendLog("ERROR BD! ".$e->getMessage());
  337. $texto = "<h1>ERROR BD</h1><p>".$e->getMessage()."</p>";
  338. $asunto = "Error correo automático";
  339. Mailer::enviarCorreo("alejandro.lara@lasalle.mx", $asunto, $texto, true);
  340. }
  341. print_r($e->getMessage());
  342. } catch(Exception $e2){
  343. echo "Error";
  344. print_r($e2->getMessage());
  345. $texto = "<h1>EXCEPTION</h1><p>".$e2->getMessage()."</p>";
  346. $asunto = "Error correo automático";
  347. Mailer::enviarCorreo("alejandro.lara@lasalle.mx", $asunto, $texto, true);
  348. }
  349. ?>