horarios_new.php 15 KB

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