horarios.php 17 KB

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