horarios.php 16 KB

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