Browse Source

My changes

Cloud User 1 năm trước cách đây
mục cha
commit
0e123fe70f

+ 26 - 0
.github/workflows/main.yml

@@ -0,0 +1,26 @@
+name: Deploy Pruebas
+
+on:
+  push:
+    branches:
+      - Pruebas
+
+jobs:
+  deploy:
+    runs-on: ubuntu-latest
+    environment: 
+      name: pruebasPAAD
+    steps:
+    - name: Checkout code
+      uses: actions/checkout@v2
+
+    - name: Deploy to Server
+      uses: appleboy/ssh-action@master
+      with:
+        host: ${{ secrets.SERVER_IP }}
+        username: ${{ secrets.SERVER_USER }}
+        key: ${{ secrets.SSH_PRIVATE_KEY }}
+        script: |
+          cd /usr/share/nginx/html/paad/
+          git fetch --all
+          git reset --hard origin/Pruebas

+ 3 - 0
.gitignore

@@ -10,7 +10,10 @@ composer.phar
 /concept/
 /backup/
 /.vscode/
+<<<<<<< HEAD
 /export/
+=======
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
 /log/
 
 /include/.env

BIN
.swp


+ 4 - 4
action/action_diasfestivos_insert.php

@@ -23,12 +23,12 @@ if (isset($_POST['rango'])) {
     $cantidad = $diaFin->diff($diaInicio);
     $date = date("Y-m-d", strtotime(str_replace("/", "-", $_POST['diaFestivo'])));
     for ($dias = 0; $dias <= $cantidad->days; $dias++) {
-        foreach($periodoArr as $periodo){
-            $db->querySingle('SELECT fi_diasfestivos(:periodo, :dia)', [':periodo' => $periodo, ':dia' => $date]);
+        
+        $db->querySingle('SELECT fi_diasfestivos({'.implode(",",$fieldName).'}, :dia)', [':dia' => $date]);
             /*$sql = "SELECT fi_diasfestivos(:periodo, :dia)";
             $params = [':periodo' => $periodo, ':dia' => $date];
             query($sql, $params, false);*/
-        }
+        
         $date = date("Y-m-d", strtotime($date . "+ 1 days"));
     }
     header("Location: ../días_festivos.php");
@@ -42,7 +42,7 @@ if (isset($_POST['rango'])) {
     $dia = query($sql, $params, false);*/
     //if (!$dia && !$dia_general) { //no hay repetidos
     foreach($periodoArr as $periodo){
-        $db->querySingle('SELECT fi_diasfestivos(:periodo, :dia)', [':periodo' => $periodo, ':dia' => $_POST['diaFestivo']]);
+        $db->querySingle('SELECT fi_diasfestivos({'.implode(",",$fieldName).'}, :dia)', [':dia' => $_POST['diaFestivo']]);
         /*$sql = "SELECT fi_diasfestivos(:periodo, :dia)";
         $params = [':periodo' => $periodo, ":dia" => $_POST['diaFestivo']];
         $id = query($sql, $params, false);*/

+ 8 - 6
action/action_materias_select.php

@@ -1,8 +1,10 @@
 <?php
-    $ruta = "../";
-    require_once "../include/bd_pdo.php";
-    global $pdo;
-    $sql="SELECT * FROM materia WHERE materia_id = :idMateria";
-    $params = ['idMateria' => $_POST['idmateria']];
-    echo json_encode(query($sql, $params, false));
+$ruta = "../";
+require_once "../include/bd_pdo.php";
+global $pdo;
+$sql = "SELECT * FROM materia
+JOIN carrera using (carrera_id)
+WHERE materia_id = :idMateria";
+$params = ['idMateria' => $_POST['idmateria']];
+echo json_encode(query($sql, $params, false));
 ?>

+ 8 - 8
action/action_materias_update.php

@@ -1,11 +1,11 @@
 <?php
-    $ruta = "../";
-    require_once "../include/bd_pdo.php";
-    global $pdo;
+$ruta = "../";
+require_once "../include/bd_pdo.php";
+global $pdo;
 
-    $sql = "UPDATE materia SET materia_nombre = :nombre WHERE materia_id = :id";
-    $params = array(':nombre' => mb_strtoupper($_POST["nombre"]), ':id' => $_POST["id"]);
-    $hecho = query($sql, $params, false);
-    header("Location: ../materias.php");
-    exit();
+$sql = "UPDATE materia SET materia_nombre = :nombre, carrera_id = :carrera WHERE materia_id = :id";
+$params = array(':nombre' => mb_strtoupper($_POST["nombre"]), ':id' => $_POST["id"], ':carrera' => $_POST["carrera"]);
+$hecho = query($sql, $params, false);
+header("Location: ../materias.php");
+exit();
 ?>

+ 33 - 0
action/asignacion_delete.php

@@ -0,0 +1,33 @@
+<?php
+/* 
+ * Borra reposición
+ */
+$pag = "../reposiciones_crear.php";
+$ruta = "../";
+require_once "../class/c_login.php";
+
+// check if the session is started
+if (!isset($_SESSION['user']))
+    die('No se ha iniciado sesión');
+
+$user = unserialize($_SESSION['user']);
+
+//--- Objeto para validar usuario. El id de usuario lo lee desde sesión
+if(!isset($_POST["id"])){
+    $return["error"] = "Error! No se recibió la información necesaria.";
+}else{
+    $id = filter_input(INPUT_POST, "id", FILTER_SANITIZE_NUMBER_INT);//limpia texto
+    $creador = $user->user["id"];
+
+    try{
+        $db->query('SELECT * from fd_asignacion_solicitud(:id, :creador)', [":id"=> $id, ":creador"=>$creador]);
+        $return["ok"] = "La solicitud se borró correctamente";
+    
+    }catch(Exception $e){
+        $return["error"] = "Ocurrió un error al borrar la solicitud de salón.";
+    }
+
+    
+}
+echo json_encode($return);
+?>

+ 111 - 91
action/asignacion_insert.php

@@ -2,7 +2,7 @@
 /* 
  * Inserta reposición
  */
-$pag = "../reposiciones_crear.php";
+$pag = "../asignacion_crear.php";
 $ruta = "../";
 require_once "../class/c_login.php";
 require_once "../class/mailer.php";
@@ -19,11 +19,12 @@ $user = unserialize($_SESSION['user']);
 
 $duracion_id = filter_input(INPUT_POST, "duracion", FILTER_SANITIZE_NUMBER_INT);//Id reposicion
 $fecha = trim(htmlspecialchars($_POST["fecha_inicial"], ENT_QUOTES, "UTF-8"));//limpia texto
-$fecha_cambio = trim(htmlspecialchars($_POST["fecha_cambio"], ENT_QUOTES, "UTF-8"));//limpia texto
 $hora_ini = filter_input(INPUT_POST, "hora_ini", FILTER_SANITIZE_NUMBER_INT);//limpia texto
 $min_ini = filter_input(INPUT_POST, "min_ini", FILTER_SANITIZE_NUMBER_INT);//limpia texto
 $alumnos = filter_input(INPUT_POST, "alumnos", FILTER_SANITIZE_NUMBER_INT);//limpia texto
 $aula = filter_input(INPUT_POST, "aula", FILTER_SANITIZE_NUMBER_INT);//1 regular , 2 sala computo, 3 otro facultad
+if(isset($_POST["salon"]) && $_POST["salon"] != "")
+    $salon = filter_input(INPUT_POST, "salon", FILTER_SANITIZE_NUMBER_INT);//limpia texto
 
 if(empty($_POST["prof"]))
     $prof = $user["id"];
@@ -33,119 +34,139 @@ else
 //$salon = trim(filter_input(INPUT_POST, "salon", FILTER_SANITIZE_STRING,array('flags' => FILTER_FLAG_STRIP_LOW)));//limpia texto
 $comentario = trim(htmlspecialchars($_POST["comentario"], ENT_QUOTES, "UTF-8"));//limpia texto
 
+$aula_rs = $db->querySingle("select tipoaula_nombre, tipoaula_supervisor from tipoaula where tipoaula_id = :id", [":id"=>$aula]);
 
 
 $duracion_rs = $db->querySingle("select * from duracion where duracion_id = :id", [":id"=>$duracion_id]);
 $duracion_tiempo = $duracion_rs["duracion_interval"];
 
 //-- Obtiene datos de horario regular de clase
-$horario_rs = $db->querySingle('SELECT * from horario_view where horario_id = :hor',
-        [':hor' => $hor]
-    );
-    
-$materia = $horario_rs["materia_id"];
-$dia = $horario_rs["horario_dia"];
 
 $hora = $hora_ini.":".$min_ini.":00";
 $fecha_new =  DateTime::createFromFormat('d/m/Y', $fecha)->format('Y-m-d')." ".$hora;
 $fecha_fin_new = date("Y-m-d", strtotime($fecha_new))." ".$duracion_tiempo;
 $dia_new = date('w', strtotime($fecha_new));
 
-$fecha_falta = DateTime::createFromFormat('d/m/Y', $fecha_falta)->format('Y-m-d');
-$dia_falta = date('w', strtotime($fecha_falta));
+//Datos de dependencia de usuario
+$fac_rs = $db->querySingle("SELECT facultad_nombre, clave_dependencia from facultad where facultad_id = :id_fac",[':id_fac' => $user->facultad["facultad_id"]] );
+
+$salon_desc = "Pendiente";
+if(!empty($salon)){
+    $salon_rs = $db->querySingle('SELECT s.salon_id, s.salon_array FROM salon_view s where s.salon_id  = :id_salon',
+            [':id_salon' => $salon]
+        );
+    if($salon_rs["salon_id"] == "" || $salon_rs["salon_id"] == NULL){
+        $salon_desc = "Pendiente";
+    }else{
+        $salon_json = json_decode($salon_rs["salon_array"], true);
+        if($salon_json[0]== "UNIVERSIDAD LA SALLE"){
+            unset($salon_json[0]);
+        }
+        $salon_desc = join(" / ",$salon_json);
+    }
+}
+
+//Obtiene correos
+$correos_rs = $db->query('SELECT coor.usuario_correo as coordinador_correo 
+        from reposicion_solicitud rs 
+        inner join profesor p on rs.profesor_id =p.profesor_id 
+        inner join usuario u on u.usuario_id = rs.usuario_id
+        inner join horario_view hv on hv.horario_id  = rs.horario_id 
+        inner join usuario coor on hv.facultad_id = coor.facultad_id and coor.rol_id = :rol_coord
+        where hv.facultad_id = :id_fac',
+            [':rol_coord' => COORDINADOR, ':id_fac' => $user->facultad["facultad_id"]]
+        );
+$coord_correos=[];
+foreach($correos_rs as $correo){
+    if( count($coord_correos)==0 && $correo["coordinador_correo"]!=""){
+        if(!isset($coord_correos["correo"]) || !in_array($correo["coordinador_correo"], $coord_correos["correo"])){
+            array_push($coord_correos, $correo["coordinador_correo"]);
+        }
+    }
+}
+
+$correosSup_rs = $db->querySingle("SELECT DISTINCT sup.usuario_correo as coordinador_correo
+    FROM horario_supervisor hs
+    inner join usuario sup on sup.usuario_id =hs.usuario_id 
+    where :id_fac = ANY(hs.facultad_id_array)
+        and sup.usuario_correo is not null and sup.usuario_correo != ''",
+    [':id_fac' => $user->facultad["facultad_id"]] );
 
 
-//Valida que tenga clase en la fecha de falta
-if(intval($dia) != intval($dia_falta)){
-    header("Location:".$pag."?error=11");
-    /*print_r($_POST);
-    echo 'SELECT * from horario_view where horario_id = '.$hor;
-    echo intval($dia)." != ".intval($dia_falta);*/
+// Valida que grupo no tenga clases
+/*$result = validaConflictoHoras($pdo, $gpo, $dia_new, $hora, $materia, "-", $fecha_new, $fecha_fin_new, $duracion);
+if($result != ""){//error
+    //echo $result;
+    header("Location:".$pag."?error=7");
+    exit();
+}
+*/
+//Valida que profesor no este en 2 reposiciones al mismo tiempo en la fecha nueva
+
+$traslape = $db->querySingle('SELECT * from traslape_profesor_reposicion(:prof, :fecha, :hora, :dur)',
+    [':prof' => $prof, ':fecha'=>DateTime::createFromFormat('d/m/Y', $fecha)->format('Y-m-d'), ':hora'=>$hora, ':dur'=>$duracion_tiempo]
+)["traslape_profesor_reposicion"];
+if($traslape){
+    //print_r($_POST);
+    //echo "SELECT * from traslape_profesor_reposicion($prof,'".DateTime::createFromFormat('d/m/Y', $fecha)->format('Y-m-d')."' , '$hora', $duracion)";
+    
+    header("Location:".$pag."?error=9");
     exit();
 }
 
-//Obtiene materia
-$materia_rs = $db->querySingle('SELECT materia_nombre  from materia where materia_id = :mat',[':mat' => $materia]);
+try{
+    $edo = 1;
+    if(!$user->jefe_carrera)
+        $edo = 2;
 
-//Obtiene correo
-$correos_rs = $db->querySingle('SELECT coor.usuario_correo, coor.usuario_nombre  from usuario coor where rol_id = :rol_coord and facultad_id = (
-	select coalesce(facultad_id,0) from usuario u where u.usuario_id = :id_usr)',[':rol_coord' => COORDINADOR, ':id_usr' => $user->user["id"]]
-);
-if( count($correos_rs) > 0 ){
-    $to = $correos_rs["usuario_correo"];
+    //echo "SELECT * from fi_asignacion_solicitud( $fecha_new,  $hora, $prof, $edo, $comentario, $alumnos, $aula, $duracion_tiempo, ".$user->user["id"].")"; exit();
+    $db->query('SELECT * from fi_asignacion_solicitud(:f_nueva, :hora_nueva, :prof, :edo, :desc, :alumnos, :aula, :duracion, :usr)',
+        [':f_nueva' => $fecha_new, ':hora_nueva' => $hora, 
+        ':prof' => $prof, ':edo'=>$edo, ':desc' => $comentario, ':alumnos' => $alumnos, ':aula' => $aula, ':duracion' => $duracion_tiempo, ':usr'=>$user->user["id"]
+        ]
+    );
+}catch(Exception $e){
+    echo $e->getMessage();
+    //header("Location: ".$pag."?error=1");
+    exit();
 }
 
-if($tipo == 1){//Reposición
-    // Valida que grupo no tenga clases
-    /*$result = validaConflictoHoras($pdo, $gpo, $dia_new, $hora, $materia, "-", $fecha_new, $fecha_fin_new, $duracion);
-    if($result != ""){//error
-        //echo $result;
-        header("Location:".$pag."?error=7");
-        exit();
-    }
-    */
-    //Valida que profesor no este en 2 reposiciones al mismo tiempo en la fecha nueva
-    
-    $traslape = $db->querySingle('SELECT * from traslape_profesor_reposicion(:prof, :fecha, :hora, :dur)',
-        [':prof' => $prof, ':fecha'=>DateTime::createFromFormat('d/m/Y', $fecha)->format('Y-m-d'), ':hora'=>$hora, ':dur'=>$duracion_tiempo]
-    )["traslape_profesor_reposicion"];
-    if($traslape){
-        //print_r($_POST);
-        //echo "SELECT * from traslape_profesor_reposicion($prof,'".DateTime::createFromFormat('d/m/Y', $fecha)->format('Y-m-d')."' , '$hora', $duracion)";
-        
-        header("Location:".$pag."?error=9");
-        exit();
-    }
+$asunto = "";
+$texto = "";
+$to = "";
+switch($edo){
+    case 1://Correo a coordinador
+        if( count($coord_correos) > 0 ){
+            $to = join(",", $coord_correos);
+        }
+        $asunto = "Solicitud de salon nueva";
+        $texto = "<p>Se creó una solicitud de asignación de salón nueva.</p>";
+        $texto .= "<p><b>Se solicita un espacio de tipo ".mb_strtoupper($aula_rs["tipoaula_nombre"])."</b> para el día <b>".$fecha." a las ".$hora." hrs. </b>";
+        $texto .= "<p>Ingresa al <a href='https://paad.lci.ulsa.mx'>sistema PAAD</a> para autorizarla.</p>";
+    break;
+    case 2://Correo a supervisor
+        $asunto = "Solicitud de salon nueva - ".$fac_rs["clave_dependencia"]." ".$fac_rs["facultad_nombre"];
+        //crear plantilla
+        $texto = "<p>Se creó una solicitud de asignación de salón nueva para: <b>".$fac_rs["clave_dependencia"]." ".$fac_rs["facultad_nombre"]."</b>.</p>";
+        $texto .= "<p>Para el día <b>".$fecha." a las ".$hora." hrs. </b>";
+        if(!$aula_rs["tipoaula_supervisor"]){
+            $texto .= " en el salón: <b>".$salon_desc."</b></p>";
+        }else{
+            $texto .= " en un salón de tipo: <b>".mb_strtoupper($aula_rs["tipoaula_nombre"])."</b></p>";
+        }
+        $texto .= "<p>Ingresa al <a href='https://paad.lci.ulsa.mx'>sistema PAAD</a> para autorizarla.</p>";
+        $to = join(",", $correosSup_rs);
+    break;
+}
 
-    try{
-        $db->query('SELECT * from fi_asignacion_solicitud(:f_nueva, :hora_nueva, :prof, 1, :desc, :alumnos, :aula, :duracion, :usr)',
-            [':f_nueva' => $fecha_new, ':hora_nueva' => $hora, 
-            ':prof' => $prof, ':desc' => $comentario, ':alumnos' => $alumnos, ':aula' => $aula, ':duracion' => $duracion_tiempo, ':usr'=>$user->user["id"]
-            ]
-        );
-    }catch(Exception $e){
-        echo $e->getMessage();
-        //header("Location: ".$pag."?error=1");
-        exit();
-    }
-    $texto = "<p>Se creó una reposición nueva.</p>";
-    $texto .= "<p><b>".mb_strtoupper($materia_rs["materia_nombre"])."</b> del día <b>".$fecha_falta." a las ".$hor." hrs. </b> se propone reponer el <b>".$fecha_new." a las ".$hora." hrs.</b>";
-    $texto .= "<p>Ingresa al <a href='https://paad.lci.ulsa.mx'>sistema PAAD</a> para autorizarla.</p>";
-    
 /*
-    $log = new LogActividad();
-    $desc_log = "Inserta reposición nueva ID[".$rs["fi_reposicion"]."] Fechas[".$fecha_falta.">".$fecha_new."] Periodo[".$_SESSION["periodo_id"]."] Materia[".$materia."] Profesor[".$prof."] Salon[".$salon."] Horario[".$hor."] Alumnos[".$alumnos."]";
-    $log->appendLog($_SESSION["usuario_id"], $_SESSION["usuario_nombre"]." ".$_SESSION["usuario_apellidos"], $desc_log);*/
+$log = new LogActividad();
+$desc_log = "Inserta reposición nueva ID[".$rs["fi_reposicion"]."] Fechas[".$fecha_falta.">".$fecha_new."] Periodo[".$_SESSION["periodo_id"]."] Materia[".$materia."] Profesor[".$prof."] Salon[".$salon."] Horario[".$hor."] Alumnos[".$alumnos."]";
+$log->appendLog($_SESSION["usuario_id"], $_SESSION["usuario_nombre"]." ".$_SESSION["usuario_apellidos"], $desc_log);*/
 
-    
-}else{//Cambio salón / hora
-    
-    try{
-        $db->query('SELECT * from fi_reposicion_solicitud(:f_nueva, :hora_nueva, :hor, :prof, 1, :desc, :alumnos, true, :aula, :duracion, :usr)',
-            [':f_nueva' => $fecha_cambio, ':hora_nueva' => $hora, ':hor' => $hor,
-            ':prof' => $prof, ':desc' => $comentario, ':alumnos' => $alumnos, ':aula' => $aula, ':duracion' => $duracion_tiempo, ':usr'=>$user->user["id"],
-            ]
-        );
-    }catch(Exception $e){
-        
-        header("Location: ".$pag."?error=1");
-        exit();
-    }
-    $texto = "<p>Se creó un cambio de salón nuevo.</p>";
-    $texto .= "<p><b>".mb_strtoupper($materia_rs["materia_nombre"])."</b> del día <b>".$fecha_falta." a las ".$hora." hrs. </b> se propone reponer el <b>".$fecha_nueva." a las ".$hora_nueva." hrs.</b>";
-    $texto .= "<p>Ingresa al <a href='https://paad.lci.ulsa.mx'>sistema PAAD</a> para autorizarlo.</p>";
-
-    /*
-    $log = new LogActividad();
-    $desc_log = "Inserta reposición nueva ID[".$rs["fi_reposicion"]."] Fechas[".$fecha_cambio.">".$fecha_cambio_nueva."] Periodo[".$_SESSION["periodo_id"]."] Materia[".$materia."] Profesor[".$prof."] Salon[".$salon."] Horario[".$hor."] Alumnos[".$alumnos."]";
-    $log->appendLog($_SESSION["usuario_id"], $_SESSION["usuario_nombre"]." ".$_SESSION["usuario_apellidos"], $desc_log);
-    */
-    
-}
 
 
 if($to!= "" && ENVIO_CORREOS){
-    $asunto = "Reposición nueva - solicitud";
         //crear plantilla
     $texto = '<body >
             <img src="https://paad.lci.ulsa.mx/imagenes/logo_lasalle.png" alt="La Salle" style="margin-bottom:60px">
@@ -155,12 +176,11 @@ if($to!= "" && ENVIO_CORREOS){
     require_once('../include/phpmailer/PHPMailerAutoload.php');
     if($_ENV['DB_NAME'] == "paad_pruebas"){
         $asunto = "PRUEBAS-".$asunto;
-        Mailer::enviarCorreo("alejandro.rosales@lasalle.mx", $asunto, $texto, true);
+        Mailer::enviarCorreo("alejandro.lara@lasalle.mx", $asunto, $texto, true);
     }else{
         Mailer::enviarCorreo($to, $asunto, $texto, true);
     }
 }
 
-exit();
 header("Location: ".$pag."?ok=0");
 ?>

+ 81 - 0
action/asignacion_select.php

@@ -0,0 +1,81 @@
+<?php
+
+/* 
+ * Obtiene datos de reposición
+ */
+$ruta = "../";
+require_once "../class/c_login.php";
+
+// check if the session is started
+if (!isset($_SESSION['user']))
+    die('No se ha iniciado sesión');
+
+$user = unserialize($_SESSION['user']);
+
+
+//--- Objeto para validar usuario. El id de usuario lo lee desde sesión
+/*if(!$objSesion->tieneAcceso()){
+    $return["error"] = "Error! No tienes permisos para realizar esta acción.";
+}else*/ if(!isset($_POST["id"])){
+    $return["error"] = "Error! No se recibió la información de la reposición.";
+}else{
+    $id = filter_input(INPUT_POST, "id", FILTER_SANITIZE_NUMBER_INT);//limpia texto
+
+    
+    try{
+        if($user->rol["rol_id"] == 7){//es supervisor
+            $rs = $db->querySingle('SELECT * from fs_asignacion_solicitud(:id, NULL, NULL, :sup, NULL)',
+                [':id' => $id, ':sup'=>$user->user["id"]]
+            );
+        }else{//coordinador 
+            $rs = $db->querySingle('SELECT * from fs_asignacion_solicitud(:id, NULL, NULL, NULL, null)',
+                [':id' => $id]
+            );
+        }
+
+    }catch(Exception $e){
+        $return["error"] = "Ocurrió un error al leer los datos de la reposición.";
+        echo json_encode($return);
+        exit();
+    }
+    
+    $return["fecha_nueva"] = date('d/m/Y', strtotime($rs["fecha_nueva"]));
+    $hora_nueva = explode(":",$rs["hora_nueva"]);
+    $return["hora_ini"] = $hora_nueva[0];
+    $return["min_ini"] = $hora_nueva[1];
+    $hora_nueva_fin = explode(":",$rs["hora_nueva_fin"]);
+    $return["hora_fin"] = $hora_nueva_fin[0];
+    $return["min_fin"] = $hora_nueva_fin[1];
+    $return["duracion"] = $rs["duracion_total"];
+
+//    $return["carrera"] = $rs["PlanEstudio_desc"];
+//    $return["materia"] = $rs["materia_id"];
+//    $return["materia_desc"] = $rs["materia_nombre"];
+    $return["salon"] = $rs["salon_id"];
+    if($rs["salon_id"]==""){  
+        $return["salon_desc"] = "Pendiente";
+    }else{
+        $salon_json = json_decode($rs["salon_array"], true);
+        if($salon_json[0]== "UNIVERSIDAD LA SALLE"){
+            unset($salon_json[0]);
+        }
+        $return["salon_desc"] = join(" / ",$salon_json);
+    }
+
+    //$return["salon_desc"] = $rs["salon"]=="" ? "-Pendiente-": $rs["salon"];
+    
+    $return["profesor"] = $rs["profesor_id"];
+    $return["profesor_nombre"] = $rs["profesor_nombre"];
+    $return["comentario"] = $rs["descripcion"];
+    $return["alumnos"] = $rs["alumnos"];
+    $return["aula"] = $rs["tipoaula_id"];
+    $return["aula_desc"] = $rs["tipoaula_nombre"];
+    $return["aula_supervisor"] = $rs["tipoaula_supervisor"];
+    $return["dia"] = date('w', strtotime($rs["fecha_nueva"]));
+    $return["motivo_cancelacion"] = $rs["motivo_cancelacion"];
+    $return["estado"] = $rs["estado_reposicion_id"];
+    $return["facultad"] = $rs["facultad_nombre"];
+    $return["supervisor_nombre"] = $rs["supervisor_nombre"];
+}
+echo json_encode($return);
+?>

+ 135 - 0
action/asignacion_update.php

@@ -0,0 +1,135 @@
+<?php
+
+/* 
+ * Actualiza reposición
+ */
+$pag = "../asignacion_crear.php";
+$ruta = "../";
+require_once "../class/c_login.php";
+
+define("COORDINADOR", 9);
+define("ENVIO_CORREOS", true);
+
+// check if the session is started
+if (!isset($_SESSION['user']))
+    die('No se ha iniciado sesión');
+
+
+$user = unserialize($_SESSION['user']);
+
+
+/*if(!isset($_POST["id"]) || !isset($_POST["fecha_falta"]) || !isset($_POST["fecha_inicial"]) || !isset($_POST["hora_ini"]) || !isset($_POST["min_ini"]) || !isset($_POST["materia"]) || !isset($_POST["grupo"])){
+    header("Location: ".$pag."?error=0");
+    exit();
+}*/
+
+$id = filter_input(INPUT_POST, "id", FILTER_SANITIZE_NUMBER_INT);//limpia texto
+$duracion_id = filter_input(INPUT_POST, "duracion", FILTER_SANITIZE_NUMBER_INT);//Id reposicion
+$fecha = trim(htmlspecialchars($_POST["fecha_inicial"], ENT_QUOTES, "UTF-8"));//limpia texto
+$hora_ini = filter_input(INPUT_POST, "hora_ini", FILTER_SANITIZE_NUMBER_INT);//limpia texto
+$min_ini = filter_input(INPUT_POST, "min_ini", FILTER_SANITIZE_NUMBER_INT);//limpia texto
+$alumnos = filter_input(INPUT_POST, "alumnos", FILTER_SANITIZE_NUMBER_INT);//limpia texto
+$aula = filter_input(INPUT_POST, "aula", FILTER_SANITIZE_NUMBER_INT);//1 regular , 2 sala computo, 3 otro facultad
+
+if(empty($_POST["prof"]))
+    $prof = $user["id"];
+else
+    $prof = filter_input(INPUT_POST, "prof", FILTER_SANITIZE_NUMBER_INT);//limpia texto
+
+//if(isset($_POST["salon"]) && $_POST["salon"] != "")
+//$salon = trim(filter_input(INPUT_POST, "salon", FILTER_SANITIZE_STRING,array('flags' => FILTER_FLAG_STRIP_LOW)));//limpia texto
+$comentario = trim(htmlspecialchars($_POST["comentario"], ENT_QUOTES, "UTF-8"));//limpia texto
+
+$duracion_rs = $db->querySingle("select * from duracion where duracion_id = :id", [":id"=>$duracion_id]);
+$duracion_tiempo = $duracion_rs["duracion_interval"];
+
+
+
+$hora = $hora_ini.":".$min_ini.":00";
+$fecha_new =  DateTime::createFromFormat('d/m/Y', $fecha)->format('Y-m-d')." ".$hora;
+$fecha_fin_new = date("Y-m-d", strtotime($fecha_new))." ".$duracion_tiempo;
+$dia_new = date('w', strtotime($fecha_new));
+
+//echo $fecha_new."<br>";
+//echo $fecha_fin_new."<br>";
+$fac_rs = $db->querySingle("SELECT facultad_nombre, clave_dependencia from facultad where facultad_id = :id_fac",[':id_fac' => $user->facultad["facultad_id"]] );
+
+$salon_desc = "Pendiente";
+if(!empty($salon)){
+    $salon_rs = $db->querySingle('SELECT s.salon_id, s.salon_array FROM salon_view s where s.salon_id  = :id_salon',
+            [':id_salon' => $salon]
+        );
+    if($salon_rs["salon_id"] == "" || $salon_rs["salon_id"] == NULL){
+        $salon_desc = "Pendiente";
+    }else{
+        $salon_json = json_decode($salon_rs["salon_array"], true);
+        if($salon_json[0]== "UNIVERSIDAD LA SALLE"){
+            unset($salon_json[0]);
+        }
+        $salon_desc = join(" / ",$salon_json);
+    }
+}
+
+//Obtiene correos
+$correos_rs = $db->query('SELECT coor.usuario_correo as coordinador_correo 
+        from reposicion_solicitud rs 
+        inner join profesor p on rs.profesor_id =p.profesor_id 
+        inner join usuario u on u.usuario_id = rs.usuario_id
+        inner join horario_view hv on hv.horario_id  = rs.horario_id 
+        inner join usuario coor on hv.facultad_id = coor.facultad_id and coor.rol_id = :rol_coord
+        where hv.facultad_id = :id_fac',
+            [':rol_coord' => COORDINADOR, ':id_fac' => $user->facultad["facultad_id"]]
+        );
+$coord_correos=[];
+foreach($correos_rs as $correo){
+    if( count($coord_correos)==0 && $correo["coordinador_correo"]!=""){
+        if(!isset($coord_correos["correo"]) || !in_array($correo["coordinador_correo"], $coord_correos["correo"])){
+            array_push($coord_correos, $correo["coordinador_correo"]);
+        }
+    }
+}
+
+$correosSup_rs = $db->querySingle("SELECT DISTINCT sup.usuario_correo as coordinador_correo
+    FROM horario_supervisor hs
+    inner join usuario sup on sup.usuario_id =hs.usuario_id 
+    where :id_fac = ANY(hs.facultad_id_array)
+        and sup.usuario_correo is not null and sup.usuario_correo != ''",
+    [':id_fac' => $user->facultad["facultad_id"]] );
+
+
+//Valida que profesor no este en 2 reposiciones al mismo tiempo
+$traslape = $db->querySingle('SELECT * from traslape_profesor_reposicion(:prof, :fecha, :hora, :dur, :id)',
+[':prof' => $prof, ':fecha'=>DateTime::createFromFormat('d/m/Y', $fecha)->format('Y-m-d'), ':hora'=>$hora, ':dur'=>$duracion_tiempo, ':id'=>$id]
+)["traslape_profesor_reposicion"];
+echo "SELECT * from traslape_profesor_reposicion($prof, '".DateTime::createFromFormat('d/m/Y', $fecha)->format('Y-m-d')."', $hora, $duracion_tiempo, $id)";
+if($traslape){
+    //header("Location:".$pag."?error=9");
+    echo "traslape";
+    exit();
+}
+
+
+/*
+$log = new LogActividad();
+$desc_log = "Actualiza reposición ID[".$id."] Fechas[".$fecha_ini."][".$fecha_fin."] Periodo[".$_SESSION["periodo_id"]."] Materia[".$materia."] Profesor[".$prof."] Salon[".$salon."] Horario[".$hor."]";
+$log->appendLog($_SESSION["usuario_id"], $_SESSION["usuario_nombre"]." ".$_SESSION["usuario_apellidos"], $desc_log);*/
+
+try{
+    $db->query('SELECT * from fu_asignacion_solicitud(:id, :f_nueva, :hora_nueva, NULL, NULL, :desc, :alumnos, :aula, :duracion, NULL)',
+        [':id'=> $id, ':f_nueva' => $fecha_new, ':hora_nueva' => $hora,
+        ':desc' => $comentario, ':alumnos' => $alumnos, ':aula' => $aula, ':duracion' => $duracion_tiempo
+        ]
+    );
+}catch(Exception $e){
+    //header("Location: ".$pag."?error=2");
+    print_r($e->getMessage());
+    echo "SELECT * from fu_asignacion_solicitud(:id, :f_nueva, :hora_nueva, NULL, NULL, :desc, :alumnos, :aula, :duracion, NULL)'";
+    print_r(
+        [':id'=> $id, ':f_nueva' => $fecha_new, ':hora_nueva' => $hora,
+        ':desc' => $comentario, ':alumnos' => $alumnos, ':aula' => $aula, ':duracion' => $duracion_tiempo
+    ]);
+    exit();
+}
+header("Location: ".$pag);
+exit();
+?>

+ 1 - 1
action/mail_javier.php

@@ -3,5 +3,5 @@ require_once "../class/c_login.php";
 require_once "../class/mailer.php";
 require_once('../include/phpmailer/PHPMailerAutoload.php');
 
-Mailer::enviarCorreo("javier.garrido@lasalle.mx", $asunto, $texto, true);
+Mailer::enviarCorreo("javier.garrido@lasalle.mx", "Prueba de correo", "Este es un correo de prueba", "", true);
 echo "Correo enviado";

+ 173 - 80
action/reposicion_autoriza.php

@@ -27,21 +27,11 @@ if(!isset($_POST["id"]) || !isset($_POST["edo"]) ){
 
 $id_repo = filter_input(INPUT_POST, "id", FILTER_SANITIZE_NUMBER_INT);//limpia texto
 $edo = filter_input(INPUT_POST, "edo", FILTER_SANITIZE_NUMBER_INT);//limpia texto
+$tipo = filter_input(INPUT_POST, "tipo", FILTER_SANITIZE_NUMBER_INT);//limpia texto
 if(isset($_POST["salon"]) && $_POST["salon"] != "")
     $salon = filter_input(INPUT_POST, "salon", FILTER_SANITIZE_NUMBER_INT);//limpia texto
 //--------------
 
-//--------------
-//Obtiene datos reposición
-$reposicion_rs = $db->querySingle('SELECT h.materia, r.fecha_nueva, r.hora_nueva, r.fecha_clase, h.horario_hora, h.facultad_id,  h.facultad, f.clave_dependencia, r.motivo_cancelacion, ta.tipoaula_supervisor , ta.tipoaula_nombre 
-    from reposicion_solicitud r
-    inner join horario_view h on h.horario_id = r.horario_id 
-    inner join facultad f on f.facultad_id = h.facultad_id
-    inner join tipoaula ta on ta.tipoaula_id = r.tipoaula_id
-    where r.reposicion_solicitud_id = :id_repo',
-            [':id_repo' => $id_repo]
-        );
-
 //Obtiene datos de salón asignado
 $salon_desc = "Pendiente";
 if(!empty($salon)){
@@ -59,18 +49,55 @@ if(!empty($salon)){
     }
 }
 
-//Obtiene correos
-$correos_rs = $db->query('SELECT p.profesor_nombre, p.profesor_correo, u.usuario_nombre as jefe_nombre, u.usuario_correo as jefe_correo,
-        coor.usuario_nombre as coordinador_nombre, coor.usuario_correo as coordinador_correo 
-        from reposicion_solicitud rs 
-        inner join profesor p on rs.profesor_id =p.profesor_id 
-        inner join usuario u on u.usuario_id = rs.usuario_id
-        inner join horario_view hv on hv.horario_id  = rs.horario_id 
-        inner join usuario coor on hv.facultad_id = coor.facultad_id and coor.rol_id = :rol_coord
-        where rs.reposicion_solicitud_id = :id_repo',
-            [':rol_coord' => COORDINADOR, ':id_repo' => $id_repo]
-        );
-//print_r($correos_rs);  exit();
+
+if($tipo ==1 || $tipo == 2){
+    //--------------
+    //Obtiene datos reposición
+    $reposicion_rs = $db->querySingle('SELECT h.materia, r.fecha_nueva, r.hora_nueva, r.fecha_clase, r.descripcion, h.horario_hora, h.facultad_id,  h.facultad, f.clave_dependencia, r.motivo_cancelacion, ta.tipoaula_supervisor , ta.tipoaula_nombre 
+        from reposicion_solicitud r
+        inner join horario_view h on h.horario_id = r.horario_id 
+        inner join facultad f on f.facultad_id = h.facultad_id
+        inner join tipoaula ta on ta.tipoaula_id = r.tipoaula_id
+        where r.reposicion_solicitud_id = :id_repo',
+                [':id_repo' => $id_repo]
+            );
+
+    //Obtiene correos
+    $correos_rs = $db->query('SELECT p.profesor_nombre, p.profesor_correo, u.usuario_nombre as jefe_nombre, u.usuario_correo as jefe_correo,
+            coor.usuario_nombre as coordinador_nombre, coor.usuario_correo as coordinador_correo 
+            from reposicion_solicitud rs 
+            inner join profesor p on rs.profesor_id =p.profesor_id 
+            inner join usuario u on u.usuario_id = rs.usuario_id
+            inner join horario_view hv on hv.horario_id  = rs.horario_id 
+            inner join usuario coor on hv.facultad_id = coor.facultad_id and coor.rol_id = :rol_coord
+            where rs.reposicion_solicitud_id = :id_repo',
+                [':rol_coord' => COORDINADOR, ':id_repo' => $id_repo]
+            );
+    //print_r($correos_rs);  exit();
+}else{
+    //Obtiene datos asignación
+    $reposicion_rs = $db->querySingle('SELECT r.fecha_nueva, r.hora_nueva, r.descripcion, f.facultad_id, f.facultad_nombre as facultad, f.clave_dependencia, r.motivo_cancelacion, ta.tipoaula_supervisor , ta.tipoaula_nombre, p.profesor_nombre
+        from asignacion_solicitud r
+        inner join usuario u on u.usuario_id = r.usuario_id
+        inner join facultad f on f.facultad_id = u.facultad_id
+        inner join tipoaula ta on ta.tipoaula_id = r.tipoaula_id
+        inner join profesor p on p.profesor_id = r.profesor_id
+        where r.asignacion_solicitud_id = :id_repo',
+                [':id_repo' => $id_repo]
+            );
+
+    //Obtiene correos
+    $correos_rs = $db->query('SELECT p.profesor_nombre, p.profesor_correo, NULL as jefe_nombre, NULL as jefe_correo,
+            coor.usuario_nombre as coordinador_nombre, coor.usuario_correo as coordinador_correo 
+            from asignacion_solicitud rs 
+            inner join profesor p on rs.profesor_id =p.profesor_id 
+            inner join usuario u on u.usuario_id = rs.usuario_id
+            inner join usuario coor on u.facultad_id = coor.facultad_id and coor.rol_id = :rol_coord
+            where rs.asignacion_solicitud_id = :id_repo',
+                [':rol_coord' => COORDINADOR, ':id_repo' => $id_repo]
+            );
+
+}
         
 $prof_correos=array();
 $jefe_correos=[];
@@ -106,72 +133,138 @@ foreach($correosSup_rs as $correo){
 }
 
 
-if($edo == 4){//cancelación
-    $motivo = "";
-    if(isset($_POST["motivo"]) && $_POST["motivo"] != "")
-        $motivo = trim($_POST["motivo"]);
-    $db->querySingle('SELECT fu_reposicion_cancela(:id, :motivo)',
-        [':id' => $id_repo, ':motivo' => $motivo]
-    );
-}else{
-    if(!empty($salon)){
-        $db->querySingle('SELECT fu_reposicion_solicitud(:id, NULL, NULL, NULL, :sal, :edo, NULL, NULL, NULL, NULL)',
-            [':id' => $id_repo, ':sal' => $salon, ':edo' => $edo]
+if($tipo ==1 || $tipo == 2){
+    if($edo == 4){//cancelación
+        $motivo = "";
+        if(isset($_POST["motivo"]) && $_POST["motivo"] != "")
+            $motivo = trim($_POST["motivo"]);
+        $db->querySingle('SELECT fu_reposicion_cancela(:id, :motivo)',
+            [':id' => $id_repo, ':motivo' => $motivo]
         );
     }else{
-        $db->querySingle('SELECT fu_reposicion_solicitud(:id, NULL, NULL, NULL, NULL, :edo, NULL, NULL, NULL, NULL)',
-            [':id' => $id_repo, ':edo' => $edo]
-        );
+        if(!empty($salon)){
+            $db->querySingle('SELECT fu_reposicion_solicitud(:id, NULL, NULL, NULL, :sal, :edo, NULL, NULL, NULL, NULL)',
+                [':id' => $id_repo, ':sal' => $salon, ':edo' => $edo]
+            );
+        }else{
+            $db->querySingle('SELECT fu_reposicion_solicitud(:id, NULL, NULL, NULL, NULL, :edo, NULL, NULL, NULL, NULL)',
+                [':id' => $id_repo, ':edo' => $edo]
+            );
+        }
     }
-}
 
+    $fecha_clase = date('d/m/Y', strtotime($reposicion_rs["fecha_clase"]));
+    $fecha_nueva = date('d/m/Y', strtotime($reposicion_rs["fecha_nueva"]));
+    $hora_tmp = explode(":",$reposicion_rs["horario_hora"]);
+    $hora_clase = $hora_tmp[0].":".$hora_tmp[1];
+    $hora_tmp = explode(":",$reposicion_rs["hora_nueva"]);
+    $hora_nueva = $hora_tmp[0].":".$hora_tmp[1];
 
-$fecha_clase = date('d/m/Y', strtotime($reposicion_rs["fecha_clase"]));
-$fecha_nueva = date('d/m/Y', strtotime($reposicion_rs["fecha_nueva"]));
-$hora_tmp = explode(":",$reposicion_rs["horario_hora"]);
-$hora_clase = $hora_tmp[0].":".$hora_tmp[1];
-$hora_tmp = explode(":",$reposicion_rs["hora_nueva"]);
-$hora_nueva = $hora_tmp[0].":".$hora_tmp[1];
-
-$asunto = "";
-$texto = "";
-$to = "";
-switch($edo){
-    case 2://Correo a supervisor
-        $asunto = "Reposición nueva - ".$reposicion_rs["clave_dependencia"]." ".$reposicion_rs["facultad"];
-        //crear plantilla
-        $texto = "<p>Se creó una reposición nueva para: <b>".$reposicion_rs["clave_dependencia"]." ".$reposicion_rs["facultad"]."</b>.</p>";
-        $texto .= "<p><b>".mb_strtoupper($reposicion_rs["materia"])."</b> del día <b>".$fecha_clase." a las ".$hora_clase." hrs. </b> se propone reponer el <b>".$fecha_nueva." a las ".$hora_nueva." hrs.</b>";
-        if(!$reposicion_rs["tipoaula_supervisor"]){
-            $texto .= " en el salón: <b>".$salon_desc."</b></p>";
+    $asunto = "";
+    $texto = "";
+    $to = "";
+    switch($edo){
+        case 2://Correo a supervisor
+            $asunto = "Reposición nueva - ".$reposicion_rs["clave_dependencia"]." ".$reposicion_rs["facultad"];
+            //crear plantilla
+            $texto = "<p>Se creó una reposición nueva para: <b>".$reposicion_rs["clave_dependencia"]." ".$reposicion_rs["facultad"]."</b>.</p>";
+            $texto .= "<p><b>".mb_strtoupper($reposicion_rs["materia"])."</b> del día <b>".$fecha_clase." a las ".$hora_clase." hrs. </b> se propone reponer el <b>".$fecha_nueva." a las ".$hora_nueva." hrs.</b>";
+            if(!$reposicion_rs["tipoaula_supervisor"]){
+                $texto .= " en el salón: <b>".$salon_desc."</b></p>";
+            }else{
+                $texto .= " en un salón de tipo: <b>".$reposicion_rs["tipoaula_nombre"]."</b></p>";
+            }
+            $texto .= "<p style='font-style:italic; padding-left:25px'>".$reposicion_rs["descripcion"]."</p>";
+            $texto .= "<p>Ingresa al <a href='https://paad.lci.ulsa.mx'>sistema PAAD</a> para autorizarla.</p>";
+            $to = join(",", $sup_correos);
+            $ok = 0;
+        break;
+        case 3://Correo a coordinador, profesor y jefe
+            $asunto = "Reposición autorizada - ".$reposicion_rs["materia"];
+            $texto = "<p>La resposición de la clase de <b>".$reposicion_rs["materia"]."</b> del día <b>".$fecha_clase." a las ".$hora_clase." hrs. </b> está autorizada para realizarse el día <b>".$fecha_nueva." a las ".$hora_nueva." hrs. en: $salon_desc</b></p>";
+            $to = join(",", $coord_correos).",".join(",", $prof_correos).",".join(",", $jefe_correos);
+            $ok = 0;
+            $db->querySingle('SELECT fu_reposicion_solicitud_supervisor(:id, :sup)',
+                [':id' => $id_repo, ':sup'=>$user->user["id"]]
+            );
+        break;
+        case 4://Correo a coordinador, profesor y jefe
+            $asunto = "Reposición declinada - ".$reposicion_rs["materia"];
+            $texto = "<p>La resposición de la clase de <b>".$reposicion_rs["materia"]." planeada para el día ".$fecha_nueva." a las ".$hora_nueva." hrs.</b> ha sido declinada por el siguiente motivo:</p>";
+            $texto .= "<p style='font-style:italic; padding-left:25px'>".$motivo."</p>";
+            $to = join(",", $coord_correos).",".join(",", $prof_correos).",".join(",", $jefe_correos);
+            $ok = 1;
+            $db->querySingle('SELECT fu_reposicion_solicitud_supervisor(:id, :sup)',
+                [':id' => $id_repo, ':sup'=>$user->user["id"]]
+            );
+        break;
+    }
+}else{
+    if($edo == 4){//cancelación
+        $motivo = "";
+        if(isset($_POST["motivo"]) && $_POST["motivo"] != "")
+            $motivo = trim($_POST["motivo"]);
+        $db->querySingle('SELECT fu_asignacion_cancela(:id, :motivo)',
+            [':id' => $id_repo, ':motivo' => $motivo]
+        );
+    }else{
+        if(!empty($salon)){
+            $db->querySingle('SELECT fu_asignacion_solicitud(:id, NULL, NULL, :sal, :edo, NULL, NULL, NULL, NULL, NULL)',
+                [':id' => $id_repo, ':sal' => $salon, ':edo' => $edo]
+            );
         }else{
-            $texto .= " en un salón de tipo: <b>".$reposicion_rs["tipoaula_nombre"]."</b></p>";
+            $db->querySingle('SELECT fu_asignacion_solicitud(:id, NULL, NULL, NULL, :edo, NULL, NULL, NULL, NULL, NULL)',
+                [':id' => $id_repo, ':edo' => $edo]
+            );
         }
-        $texto .= "<p>Ingresa al <a href='https://paad.lci.ulsa.mx'>sistema PAAD</a> para autorizarla.</p>";
-        $to = join(",", $sup_correos);
-        $ok = 0;
-    break;
-    case 3://Correo a coordinador, profesor y jefe
-        $asunto = "Reposición autorizada - ".$reposicion_rs["materia"];
-        $texto = "<p>La resposición de la clase de <b>".$reposicion_rs["materia"]."</b> del día <b>".$fecha_clase." a las ".$hora_clase." hrs. </b> está autorizada para realizarse el día <b>".$fecha_nueva." a las ".$hora_nueva." hrs. en: $salon_desc</b></p>";
-        $to = join(",", $coord_correos).",".join(",", $prof_correos).",".join(",", $jefe_correos);
-        $ok = 0;
-        $db->querySingle('SELECT fu_reposicion_solicitud_supervisor(:id, :sup)',
-            [':id' => $id_repo, ':sup'=>$user->user["id"]]
-        );
-    break;
-    case 4://Correo a coordinador, profesor y jefe
-        $asunto = "Reposición declinada - ".$reposicion_rs["materia"];
-        $texto = "<p>La resposición de la clase de <b>".$reposicion_rs["materia"]." planeada para el día ".$fecha_nueva." a las ".$hora_nueva." hrs.</b> ha sido declinada por el siguiente motivo:</p>";
-        $texto .= "<p style='font-style:italic; padding-left:25px'>".$motivo."</p>";
-        $to = join(",", $coord_correos).",".join(",", $prof_correos).",".join(",", $jefe_correos);
-        $ok = 1;
-        $db->querySingle('SELECT fu_reposicion_solicitud_supervisor(:id, :sup)',
-            [':id' => $id_repo, ':sup'=>$user->user["id"]]
-        );
-    break;
+    }
+    
+    $fecha_nueva = date('d/m/Y', strtotime($reposicion_rs["fecha_nueva"]));
+    $hora_tmp = explode(":",$reposicion_rs["hora_nueva"]);
+    $hora_nueva = $hora_tmp[0].":".$hora_tmp[1];
+
+    $asunto = "";
+    $texto = "";
+    $to = "";
+    switch($edo){
+        case 2://Correo a supervisor
+            $asunto = "Asignación nueva - ".$reposicion_rs["clave_dependencia"]." ".$reposicion_rs["facultad"];
+            //crear plantilla
+            $texto = "<p>Se creó una solicitud de asignación nueva para: <b>".$reposicion_rs["clave_dependencia"]." ".$reposicion_rs["facultad"]."</b>.</p>";
+            $texto .= "<p>Se solicita el día <b>".$fecha_nueva." a las ".$hora_nueva." hrs.</b> para el profesor: <b>".$reposicion_rs["profesor_nombre"]."</b>.";
+            if(!$reposicion_rs["tipoaula_supervisor"]){
+                $texto .= " en el salón: <b>".$salon_desc."</b></p>";
+            }else{
+                $texto .= " en un salón de tipo: <b>".$reposicion_rs["tipoaula_nombre"]."</b></p>";
+            }
+            $texto .= "<p style='font-style:italic; padding-left:25px'>".$reposicion_rs["descripcion"]."</p>";
+            $texto .= "<p>Ingresa al <a href='https://paad.lci.ulsa.mx'>sistema PAAD</a> para autorizarla.</p>";
+            $to = join(",", $sup_correos);
+            $ok = 0;
+        break;
+        case 3://Correo a coordinador, profesor y jefe
+            $asunto = "Asignación autorizada - ".$reposicion_rs["profesor_nombre"];
+            $texto = "<p>La asignación de espacio para el profesor <b>".$reposicion_rs["profesor_nombre"]."</b> está autorizada para realizarse el día <b>".$fecha_nueva." a las ".$hora_nueva." hrs. en: $salon_desc</b></p>";
+            $to = join(",", $coord_correos).",".join(",", $prof_correos).",".join(",", $jefe_correos);
+            $ok = 0;
+            $db->querySingle('SELECT fu_asignacion_solicitud_supervisor(:id, :sup)',
+                [':id' => $id_repo, ':sup'=>$user->user["id"]]
+            );
+        break;
+        case 4://Correo a coordinador, profesor y jefe
+            $asunto = "Asignación declinada - ".$reposicion_rs["profesor_nombre"];
+            $texto = "<p>La asignación de espacio para el profesor <b>".$reposicion_rs["profesor_nombre"]."</b> planeada para el día ".$fecha_nueva." a las ".$hora_nueva." hrs.</b> ha sido declinada por el siguiente motivo:</p>";
+            $texto .= "<p style='font-style:italic; padding-left:25px'>".$motivo."</p>";
+            $to = join(",", $coord_correos).",".join(",", $prof_correos).",".join(",", $jefe_correos);
+            $ok = 1;
+            $db->querySingle('SELECT fu_asignacion_solicitud_supervisor(:id, :sup)',
+                [':id' => $id_repo, ':sup'=>$user->user["id"]]
+            );
+        break;
+    }
 }
 
+
 if($to!= "" && ENVIO_CORREOS){
     $texto = '<body >
             <img src="https://paad.lci.ulsa.mx/imagenes/logo_lasalle.png" alt="La Salle" style="margin-bottom:60px">

+ 5 - 1
action/reposicion_profesor_materias.php

@@ -22,7 +22,11 @@ $user = unserialize($_SESSION['user']);
     $id = filter_input(INPUT_POST, "id", FILTER_SANITIZE_NUMBER_INT);//limpia texto
 
     try{
-        $rs = $db->query('SELECT * FROM fs_materiasprofesor(:id, :jefe)', [':id' => $id, ':jefe'=>$user->user["id"]] );
+        if($user->jefe_carrera){
+            $rs = $db->query('SELECT * FROM fs_materiasprofesor(:id, :jefe)', [':id' => $id, ':jefe'=>$user->user["id"]] );
+        }else{
+            $rs = $db->query('SELECT * FROM fs_materiasprofesor(:id, NULL)', [':id' => $id] );
+        }
 
     }catch(Exception $e){
         $return["error"] = "Ocurrió un error al leer los datos de las materias.";

+ 1 - 0
action/reposicion_select.php

@@ -82,6 +82,7 @@ $user = unserialize($_SESSION['user']);
     $return["facultad"] = $rs["facultad_nombre"];
     $return["carrera"] = $rs["carrera_nombre"];
     $return["grupo"] = $rs["horario_grupo"];
+    $return["supervisor_nombre"] = $rs["supervisor_nombre"];
 }
 echo json_encode($return);
 ?>

+ 5 - 4
action/reposicion_update.php

@@ -87,9 +87,10 @@ if($tipo == 1){//Reposición
 
     //Valida que profesor no este en 2 reposiciones al mismo tiempo
     */
-    $traslape = $db->querySingle('SELECT * from traslape_profesor_reposicion(:prof, :fecha, :hora, :dur)',
-    [':prof' => $prof, ':fecha'=>DateTime::createFromFormat('d/m/Y', $fecha)->format('Y-m-d'), ':hora'=>$hora, ':dur'=>$duracion_tiempo]
+    $traslape = $db->querySingle('SELECT * from traslape_profesor_reposicion(:prof, :fecha, :hora, :dur, :id)',
+    [':prof' => $prof, ':fecha'=>DateTime::createFromFormat('d/m/Y', $fecha)->format('Y-m-d'), ':hora'=>$hora, ':dur'=>$duracion_tiempo, ':id'=>$id]
     )["traslape_profesor_reposicion"];
+    echo "SELECT * from traslape_profesor_reposicion($prof, '".DateTime::createFromFormat('d/m/Y', $fecha)->format('Y-m-d')."', $hora, $duracion_tiempo, $id)";
     if($traslape){
         //header("Location:".$pag."?error=9");
         echo "traslape";
@@ -104,7 +105,7 @@ if($tipo == 1){//Reposición
 }
 
 try{
-    $db->query('SELECT * from fu_reposicion_solicitud(:id, :f_falta, :f_nueva, :hora_nueva, NULL, 1, :desc, :alumnos, :aula, :duracion, NULL)',
+    $db->query('SELECT * from fu_reposicion_solicitud(:id, :f_falta, :f_nueva, :hora_nueva, NULL, NULL, :desc, :alumnos, :aula, :duracion, NULL)',
         [':id'=> $id, ':f_falta' => $fecha_falta, ':f_nueva' => $fecha_new, ':hora_nueva' => $hora,
         ':desc' => $comentario, ':alumnos' => $alumnos, ':aula' => $aula, ':duracion' => $duracion_tiempo
         ]
@@ -112,7 +113,7 @@ try{
 }catch(Exception $e){
     //header("Location: ".$pag."?error=2");
     print_r($e->getMessage());
-    echo "SELECT * from fu_reposicion_solicitud(:id, :f_falta, :f_nueva, :hora_nueva, NULL, 1, :desc, :alumnos, :aula, :duracion, NULL)'";
+    echo "SELECT * from fu_reposicion_solicitud(:id, :f_falta, :f_nueva, :hora_nueva, NULL, NULL, :desc, :alumnos, :aula, :duracion, NULL)'";
     print_r(
         [':id'=> $id, ':f_falta' => $fecha_falta, ':f_nueva' => $fecha_new, ':hora_nueva' => $hora,
         ':desc' => $comentario, ':alumnos' => $alumnos, ':aula' => $aula, ':duracion' => $duracion_tiempo

+ 5 - 60
action/rutas_salón_horario.php

@@ -27,9 +27,6 @@ try {
                 exit;
             }
         });
-
-        
-
         // step 1: get subrutas
         $data = $db
             ->where('tiene_salones')
@@ -65,62 +62,10 @@ try {
             'salon_reposicion.salon as reposicion_salon',
         ];
         $fecha = ($_GET['fecha'] != 'null') ? ("'{$_GET['fecha']}'" ?: 'CURRENT_DATE') : 'CURRENT_DATE';
-
-        /*echo json_encode(array_values(
-            $db->query(
-                'SELECT ' . implode(', ', $columns) . <<<SQL
-                    , reposicion_hora + horario_view.duracion as reposicion_fin, registro_fecha_ideal
-                    FROM horario_view
-                        NATURAL JOIN periodo
-                        NATURAL JOIN registro
-                        NATURAL JOIN reposicion
-                        JOIN bloque_horario ON (bloque_horario.hora_inicio, bloque_horario.hora_fin) OVERLAPS (reposicion_hora, reposicion_hora + horario_view.duracion)
-                        NATURAL JOIN profesor
-                        JOIN salon_view_mat as salon_reposicion ON (salon_reposicion.salon_id = reposicion.salon_id)
-                    WHERE
-                        $fecha::DATE BETWEEN periodo.periodo_fecha_inicio
-                        AND periodo.periodo_fecha_fin
-                        AND reposicion_fecha = $fecha::DATE
-                        AND bloque_horario.id = :bloque_horario_id
-                        AND salon_reposicion.id_espacio_padre = :id_espacio_sgu
-                        ORDER BY reposicion_hora
-            SQL,
-                [
-                    'bloque_horario_id' => 6,
-                    'id_espacio_sgu' => 144,
-                ]
-            )
-        ), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
-        exit();*/
- 
-        $reposicion_rs = $db->query(
-            'SELECT ' . implode(', ', $columns) . <<<SQL
-                , reposicion_hora + horario_view.duracion as reposicion_fin, registro_fecha_ideal
-                FROM horario_view
-                    NATURAL JOIN periodo
-                    NATURAL JOIN registro
-                    NATURAL JOIN reposicion
-                    JOIN bloque_horario ON (bloque_horario.hora_inicio, bloque_horario.hora_fin) OVERLAPS (reposicion_hora, reposicion_hora + horario_view.duracion)
-                    NATURAL JOIN profesor
-                    JOIN salon_view_mat as salon_reposicion ON (salon_reposicion.salon_id = reposicion.salon_id)
-                WHERE
-                    $fecha::DATE BETWEEN periodo.periodo_fecha_inicio
-                    AND periodo.periodo_fecha_fin
-                    AND reposicion_fecha = $fecha::DATE
-                    AND bloque_horario.id = :bloque_horario_id
-                    AND salon_reposicion.id_espacio_padre = :id_espacio_sgu
-                    ORDER BY reposicion_hora
-        SQL,
-            [
-                'bloque_horario_id' => $_GET['bloque_horario_id'],
-                'id_espacio_sgu' => $_GET['id_espacio_sgu'],
-            ]
-        );
-
         $data = array_map(
             fn($ruta) => array_merge(
                 [
-                    'horarios' =>  $db->query(
+                    'horarios' => $db->query(
                         "SELECT " . implode(', ', $columns) . <<<SQL
                             FROM horario_view
                             NATURAL JOIN periodo
@@ -141,9 +86,9 @@ try {
                             'bloque_horario_id' => $_GET['bloque_horario_id'],
                             'id_espacio_sgu' => $ruta['id_espacio_sgu'],
                         ]
-                    ) ,
+                    ),
                     // 'query' => $db->getLastQuery(),
-                    'reposiciones' => $reposicion_rs/* $db->query(
+                    'reposiciones' => /*$db->query(
                         'SELECT ' . implode(', ', $columns) . <<<SQL
                             , reposicion_hora + horario_view.duracion as reposicion_fin, registro_fecha_ideal
                             FROM horario_view
@@ -165,7 +110,7 @@ try {
                             'bloque_horario_id' => $_GET['bloque_horario_id'],
                             'id_espacio_sgu' => $ruta['id_espacio_sgu'],
                         ]
-                    )*/ ,
+		    )*/ [],
                 ],
                 $ruta,
             ),
@@ -189,7 +134,7 @@ try {
     http_response_code(500);
     echo json_encode([
         'error' => $th->getMessage(),
-        // 'query' => $db->getLastQuery(),
+        'query' => $db->getLastQuery(),
     ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
     exit;
 } catch (Exception $th) {

+ 3 - 15
action/usuario_find.php

@@ -3,21 +3,9 @@ $ruta = '../';
 require_once '../include/bd_pdo.php';
 global $pdo;
 
-if ($_POST['nombre'] == "") {
-    $nombre = null;
-} else {
-    $nombre = $_POST['nombre'];
-}
-if ($_POST['clave'] == "") {
-    $clave = null;
-} else {
-    $clave = $_POST['clave'];
-}
-if ($_POST['facultad'] == "") {
-    $facultad = null;
-} else {
-    $facultad = $_POST['facultad'];
-}
+$nombre = $_POST['nombre'] ?: null;
+$clave = $_POST['clave'] ?: null;
+$facultad = $_POST['facultad'] ?: null;
 
 echo json_encode($db->query("SELECT * FROM fs_profesores(:nombre, :clave, :facultad) ORDER BY profesor_nombre", [':nombre' => $nombre, ':clave' => $clave, ':facultad' => $facultad]));
 ?>

+ 796 - 0
asignacion_crear.php

@@ -0,0 +1,796 @@
+<?php
+
+require_once 'class/c_login.php';
+if (!isset($_SESSION['user'])){
+    die(header('Location: index.php'));
+}
+
+//$user = unserialize($_SESSION['user']);
+$user = Login::get_user();
+
+$user->access();
+/*print_r($user);
+print_r($user->user["id"]);
+echo "****|";
+print_r($user->acceso);//null sin permisos, w o r
+echo "|****|";
+print_r($user->profesor);
+echo "|****|";
+print_r($user->facultad["facultad_id"]);
+exit();*/
+//profesor, admin, rol, facultad
+if ($user->acceso === null && !$user->admin){
+    die(header('Location: index.php'));
+    exit();
+}
+
+$jefatura = false;
+$coordinador = false;
+if($user->rol["rol_id"]==11){
+    $jefatura = true;
+}
+if($user->rol["rol_id"]==9){
+    $coordinador = true;
+}
+
+$write = true; //
+
+$en_fecha = $db->querySingle("SELECT ESTA_EN_PERIODO(NOW()::DATE, :periodo_id)", [':periodo_id' => $user->periodo_id])['esta_en_periodo'];
+
+//if($user->jefe_carrera){
+
+    //$prof_rs = $db->query('SELECT DISTINCT * FROM fs_profesores(null, null, :fac) ORDER BY PROFESOR_NOMBRE', [':fac' => $user->facultad["facultad_id"]]);
+    $prof_rs = $db->query('SELECT DISTINCT PROFESOR.* FROM PROFESOR
+	JOIN horario_profesor USING (profesor_id)
+    JOIN HORARIO_VIEW USING (horario_id)
+    WHERE FACULTAD_ID = :fac ORDER BY profesor.profesor_nombre', [':fac' => $user->facultad["facultad_id"]]);
+//}
+
+//Duraciones
+$duracion_rs = $db->query("select * from duracion order by duracion_interval");
+
+if(!is_null($user->periodo_id)){
+    //Periodo
+    $periodo_rs = $db->querySingle('SELECT periodo_fecha_inicio, periodo_fecha_fin FROM periodo WHERE periodo_id = :periodo_id', [':periodo_id' => $user->periodo_id]);
+    $periodo_fin = $periodo_rs["periodo_fecha_fin"];
+    if(strtotime($periodo_rs["periodo_fecha_inicio"])>strtotime(date("Y-m-d")) )
+        $fecha_man = date("d/m/Y", strtotime($periodo_rs["periodo_fecha_inicio"]));
+    else{
+        $dia_actual = intval(date("w"));
+        $dias = 1;//días mínimos Lun a Jue
+        if($dia_actual ==5 )//Vie
+            $dias=4;
+        else if( $dia_actual ==6 )//Sab
+            $dias=3;
+        else if( $dia_actual ==0 )//Do
+            $dias=2;
+        
+        $fecha_man = date("d/m/Y", strtotime("+".$dias." day"));
+    }
+    /*
+    // Materias
+    $id_prof = $user->profesor;
+    //$facultad_id = 28;
+    $materias_rs = $db->query('SELECT * FROM fs_materiasprofesor(:id)', [':id' => $id_prof]);
+    */
+    if(isset($_POST["fecha_inicial"]))
+        $fecha_ini = $_POST["fecha_inicial"];
+    else
+        $fecha_ini = date("d/m/Y", strtotime($periodo_rs["periodo_fecha_inicio"]));
+
+    if(isset($_POST["fecha_final"]))
+        $fecha_fin = $_POST["fecha_final"];
+    else
+        $fecha_fin = date("d/m/Y", strtotime($periodo_rs["periodo_fecha_fin"]));
+
+    $date = DateTime::createFromFormat('d/m/Y', $fecha_ini);
+    $fecha_ini_db = $date->format('Y-m-d');
+
+    $date = DateTime::createFromFormat('d/m/Y', $fecha_fin);
+    $fecha_fin_db = $date->format('Y-m-d');
+}
+
+?>
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Reposiciones crear |
+        <?= $user->facultad['facultad'] ?? "Administrador"; ?>
+    </title>
+    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
+        integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
+        crossorigin="anonymous" referrerpolicy="no-referrer" />
+    <?php
+    include 'import/html_css_files.php';
+    ?>
+    <link rel="stylesheet" href="css/jquery-ui.css">
+    <link rel="stylesheet" href="css/calendar.css">
+    <style>
+        .wizard { height: 20px; width: 80%; background: #D0D0D0; }
+        .wizard.full { background: #D0D0D0; }
+        .wizard.active > div:first-child { background: #00A6CE;  }
+        .wizard.active > div:last-child { width: 0px; height: 0px; border-style: solid; border-width: 10px 0 10px 6px; border-color: transparent transparent transparent #00a6ce; transform: rotate(0deg); }
+    </style>
+    <script src="js/jquery.min.js"></script>
+    <script src="js/bootstrap/popper.min.js"></script>
+    <script src="js/bootstrap/bootstrap.min.js"></script>
+    <script src="js/jquery-ui.js"></script>
+    <script src="js/datepicker-es.js"></script>
+</head>
+
+
+<!--  -->
+
+<body style="display: block;">
+    <?php
+    include('include/constantes.php');
+    include("import/html_header.php");
+    html_header("Solicitud de salones", "Sistema de gestión de checador");
+    ?>
+
+    <main class="container content marco content-margin" id="local-app">
+        <?php
+        if($write==true)  {?>
+        <!-- Botón para abrir el modal -->
+        <div class="row mb-4">
+            <div class="col-12 text-right">
+                <button type="button" class="btn btn-outline-secondary" data-tipo="1" data-toggle="modal" data-target="#modal" <?php if (!$en_fecha ) { echo "disabled"; } ?>><span class="ing-mas ing-fw"></span>Crear solicitud</button>
+            </div>
+        </div>
+        <?php }?>
+        <section id="message"></section>
+        <?php require('import/periodo.php') ?>
+        <?php if(!is_null($user->periodo_id)) { ?>
+        <form id="asistencia" method="post" onsubmit="return validaFechas()">
+            <div class="form-box">
+                <input type="hidden" name="facultad" value="">
+                
+                <div class="form-group row">
+                    <label for="filtro_inicial" class="col-4 col-form-label">Fecha inicial</label>
+                    <div class="col-8 col-sm-4">
+                        <input id="filtro_inicial" name="fecha_inicial" type="text" class="form-control date-picker-filtro" placeholder="dd/mm/aaaa" maxlength="10" required="required" readonly="" value="<?php echo $fecha_ini;?>">
+                        <div class="invalid-feedback">No es una fecha válida.</div>
+                    </div>
+                </div>
+                <div class="form-group row">
+                    <label for="filtro_final" class="col-4 col-form-label">Fecha final</label>
+                    <div class="col-8 col-sm-4">
+                        <input id="filtro_final" name="fecha_final" type="text" class="form-control date-picker-filtro" placeholder="dd/mm/aaaa" maxlength="10" required="required" readonly="" value="<?php echo $fecha_fin;?>">
+                        <div class="invalid-feedback">El rango de fechas no es válido.</div>
+                    </div>
+                </div>
+            </div>
+            <div class="form-group row justify-content-center">
+                <button type="submit" class="btn btn-outline-primary mr-2" id="btn-buscar"><span class="ing-buscar ing-fw"></span> Buscar</button>
+                <button type="button" class="btn btn-outline-danger" onclick="window.location.href = window.location.href"><span class="ing-borrar ing-fw"></span> Limpiar</button>
+            </div>
+        </form>
+
+        <?php
+            $asignaciones_rs = $db->query('SELECT * FROM fs_asignaciones_solicitud(:f_ini, :f_fin, :usr ,NULL)', [':f_ini' => $fecha_ini_db, ':f_fin' => $fecha_fin_db, ':usr' => $user->user["id"]]);
+        }
+        ?>
+
+        <div class="row">
+            <?php
+            if(isset($asignaciones_rs) && count($asignaciones_rs)>0){ ?>
+            <h3 class="mb-3">Asignaciones creadas</h3>
+            <div class="col-12 table-responsive px-0">
+                <table class="table table-sm table-striped table-white">
+                    <thead class="thead-dark">
+                        <tr >
+                            <th>Estado</th>
+                            <th>Responsable</th>
+                            <th style="width:160px">Fecha solicitada</th>
+                            <th style="width:160px">Duración</th>
+                            <th>Salón</th>
+                            <?php if($write){ ?><th>Acciones</th><?php } ?>
+                        </tr>
+                    </thead>
+                    <tbody>
+                        <?php
+                        foreach($asignaciones_rs as $asignacion){
+                        ?>
+                        <tr data-id="<?php echo $asignacion["asignacion_solicitud_id"]; ?>" id="id<?php echo $asignacion["asignacion_solicitud_id"]; ?>">
+                            <td class="align-middle text-center" style="color:<?php echo $asignacion["estado_color"];?>" title="<?php echo $asignacion["estado_nombre"];?>">
+                                <?php if($asignacion["estado_reposicion_id"]<3){ ?>
+                                <div class="wizard <?php if(intval($asignacion["estado_reposicion_id"])==2) echo "active";?> d-flex mx-auto">
+                                    <div class="w-50 h-100"></div>
+                                    <div class=""></div>
+                                </div>
+                                <?php } else if($asignacion["estado_reposicion_id"]==3){?>
+                                <div class="text-success text-center pt-1">
+                                    <span class="ing-autorizar ing-lg"></span>
+                                </div>
+                                <?php } else {?>
+                                <div class="text-danger text-center pt-1">
+                                    <span class="ing-negar ing-lg"></span>
+                                </div>
+                                <?php } ?>
+                            </td>
+                            <td class="align-middle"><?php echo $asignacion["profesor_nombre"]; ?></td>
+                            <td class="align-middle text-center"><?php
+                                
+                                echo date("d/m/Y", strtotime($asignacion["fecha_nueva"])) ."<br>".substr($asignacion["hora_nueva"],0,-3)." a ".substr($asignacion["hora_nueva_fin"],0,-3)." hrs.";
+                                ?>
+                            </td>
+                            <td class="align-middle text-center"><?php
+                                echo $asignacion["duracion_total"];
+                                ?>
+                            </td>
+                            <td class="align-middle text-center"><?php
+                                if($asignacion["salon_id"] != ""){
+                                    echo $asignacion["salon_id"];
+                                }else
+                                    echo "Pendiente";
+                                ?>
+                            </td>
+                            
+                            <?php if($write){ ?>
+                            <td class="align-middle text-center icono-acciones">
+                                <?php
+                                //no se ha aprobado
+                                
+                                if(($asignacion["estado_reposicion_id"] == 1 && $jefatura) || ($asignacion["estado_reposicion_id"] == 2 && $coordinador)){?>
+                                <a href="#" data-tipo="2" title="Editar" data-toggle="modal" data-target="#modal"><?php echo $ICO["editar"];?></a>
+                                <a href="#" data-toggle="modal" data-target="#modal_confirm" title="Borrar"><?php echo $ICO["cancelar"];?></a>
+                                <?php } ?>
+                            </td>
+                            <?php } ?>
+                        </tr>
+                        <?php }
+                    ?>
+                    </tbody>
+                </table>
+            </div>
+            <?php } else { 
+                if(is_null($user->periodo_id)){ ?>
+            <div class="col-12 text-center">
+                <h4 class="mt-4 text-danger">Selecciona un periodo</h4>
+            </div>
+            <?php } else {?>    
+            <div class="col-12 text-center">
+                <h4 class="mt-4 text-danger">No tienes solicitudes disponibles que cumplan con los filtros</h4>
+            </div>
+            <?php }
+            } ?>
+        </div>
+
+        <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modal" aria-hidden="true">
+            <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
+                <div class="modal-content">
+                    <div class="modal-header">
+                        <h4 class="col-12 modal-title text-center"><span id="modalLabel">Crear asignación</span>
+                        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
+                            <span aria-hidden="true">&times;</span>
+                        </button></h4>
+                    </div>
+                    <div class="modal-body">
+                        <form action="./action/asignacion_insert.php" method="post" id="formaModal" onsubmit="return submitForm()">
+                            <input type="hidden" name="id" id="id">
+                            <input type="hidden" name="estado" value="1">
+                            
+                            
+                            <div class="form-box">
+
+                                <div class="form-group row" id="profBlock">
+                                    <label for="prof" class="col-4 col-form-label">Profesor responsable*</label> 
+                                    <div class="col-8">
+                                        <div class="datalist datalist-select mb-1 w-100" id="dlProfesor">
+                                            <div class="datalist-input">Selecciona un profesor</div>
+                                            <span class="ing-buscar icono"></span>
+                                            <ul style="display:none">
+                                                <?php foreach($prof_rs as $prof){?>
+                                                    <li data-id="<?php echo $prof["profesor_id"];?>" <?php if($prof["profesor_id"]==$user->profesor){ echo "class='selected'";} ?> ><?php echo $prof["profesor_nombre"];?></li>
+                                                <?php } ?>
+                                            </ul>
+                                            <input type="hidden" id="prof" name="prof" value="">
+                                        </div>
+                                    </div>
+                                </div>
+                            </div>
+                            <div class="form-box prof-selected">
+                                
+
+                                <div class="form-group row materia-block">
+                                    <label for="duracion" class="col-4 col-form-label">Duración</label> 
+                                    <div class="col-4">
+                                        <select name="duracion" id="duracion" class="form-control" required="required">
+                                            <?php foreach($duracion_rs as $dura){?>
+                                            <option value="<?php echo $dura["duracion_id"];?>" data-duracion="<?php echo $dura["duracion_interval"];?>" ><?php echo $dura["duracion_nombre"];?></option>
+                                            <?php } ?>
+                                        </select>
+                                    </div>
+                                </div>
+                                
+                                <div class="form-group row repo_block materia-block">
+                                    <label for="fecha_inicial" class="col-4 col-form-label">Fecha de asignación *</label> 
+                                    <div class="col-8">
+                                        <input id="fecha_inicial" name="fecha_inicial" type="text" class="form-control date-picker-future" placeholder="dd/mm/aaaa" maxlength="10" required="required" readonly="readonly" value="">
+                                        <small class="form-text text-muted">Las solicitudes de asignación se deben solicitar con al menos 24hrs de anticipación.<br>
+                                                    Recuerda que en sábado el límite para terminar la clase es a las 15:00hrs.
+                                        </small>
+                                    </div>
+                                </div>
+                                <div class="form-group row materia-block">
+                                    <label for="hora_ini" class="col-4 col-form-label" id="hora_nombre">Hora *</label>
+                                    <?php
+                                    //define("HORA_FINAL", 22);
+                                    //define("FRACCION_HORA", 15);
+                                    $default_h = 7; $default_m = 15;
+                                    ?>
+                                    <div class="col-4">
+                                        <select name="hora_ini" id="hora_ini" class="form-control" required="required">
+                                            <?php for($h = $default_h; $h < HORA_FINAL; $h++){?>
+                                            <option value="<?php echo sprintf( '%02d', $h );?>" <?php if($default_h == $h){ echo 'selected="selected"';}?>><?php echo sprintf( '%02d', $h );?></option>
+                                            <?php } ?>
+                                        </select>
+                                    </div>
+                                    <div class="col-4">
+                                        <select name="min_ini" id="min_ini" class="form-control" required="required">
+                                            <?php for($m = 0; $m < 60; $m+=(60/FRACCION_HORA)){?>
+                                            <option value="<?php echo sprintf( '%02d', $m );?>" <?php if($default_m == $m){ echo 'selected="selected"';}?>><?php echo sprintf( '%02d', $m );?></option>
+                                            <?php } ?>
+                                        </select>
+                                    </div>
+                                </div>
+
+                                
+                                <div class="form-group row materia-block">
+                                    <label for="salon" class="col-4 col-form-label">Alumnos aproximados *</label> 
+                                    <div class="col-8 col-md-4">
+                                        <input type="number" name="alumnos" id="alumnos" class="form-control" value="1" min="1" max="50">
+                                    </div>
+                                </div>
+                                
+                                <div class="form-group row materia-block">
+                                    <label for="aula" class="col-4 col-form-label">Tipo aula *</label> 
+                                    <div class="col-8">
+                                        <div class="datalist datalist-select mb-1 w-100" id="dlAula">
+                                            <div class="datalist-input">Salón</div>
+                                            <span class="ing-buscar icono"></span>
+                                            <ul style="display:none">
+                                                <?php
+                                                $tipoaula_rs = $db->query('select * from tipoaula t order by t.tipoaula_id ');
+                                                foreach($tipoaula_rs as $ta){ ?>
+                                                    <li data-id="<?php echo $ta["tipoaula_id"];?>"><?php echo $ta["tipoaula_nombre"];?></li>
+                                                <?php } ?>
+                                            </ul>
+                                            <input type="hidden" id="aula" name="aula" value="1">
+                                        </div>
+                                    </div>
+                                </div>
+                            
+                                <div class="form-group row materia-block">
+                                    <label for="comentario" class="col-4 col-form-label">Comentarios</label> 
+                                    <div class="col-8">
+                                        <p><i>Requerimientos específicos del salón, software especializado, etc.</i></p>
+                                        <textarea rows="3" class="form-control" id="comentario" name="comentario"></textarea>
+                                    </div>
+                                </div>
+                            </div>
+                            
+                            <div class="form-group row mt-3" id="submitGroup">
+                                <div class="offset-4 col-8">
+                                    <button type="submit" class="btn btn-outline-primary  materia-block" id="submitBtn" data-tipo="1"><?php echo $ICO["aceptar"];?> Guardar</button>
+                                    <button type="reset" class="btn btn-outline-danger" data-dismiss="modal"><?php echo $ICO["cancelar"];?> Cancelar</button>
+                                </div>
+                            </div>
+                            <div class="form-group row mt-3" id="loadingGroup" style="display:none">
+                                <div class="col-12 text-center">
+                                    <div class="spinner-border text-primary" role="status">
+                                        <span class="sr-only">Loading...</span>
+                                    </div>
+                                </div>
+                            </div>
+                        </form>
+                    </div>
+                </div>
+            </div>
+        </div>
+        
+    
+        <div class="modal fade" id="modal_confirm" tabindex="-1" role="dialog" aria-labelledby="modal" aria-hidden="true">
+            <div class="modal-dialog modal-dialog-centered" role="document">
+                <div class="modal-content">
+                    <div class="modal-body">
+                        <div class="row">
+                            <div class="col">
+                                <p class="font-weight-bold">¿Estás seguro de que quieres borrar la solicitud de asignación de salón?</p>
+                                <p>Esta acción no se puede deshacer.</p>
+                            </div>
+                        </div>
+                    </div>
+                    <div class="modal-footer">
+                        <input type="hidden" id="id_borrar" value="">
+                        <button type="button" class="btn btn-outline-primary btn-borrar"><?php echo $ICO["aceptar"];?> Borrar</button>
+                        <button type="button" class="btn btn-outline-danger" data-dismiss="modal" aria-label="Close"><?php echo $ICO["cancelar"];?> Cancelar</button>
+                    </div>
+                </div>
+            </div>
+        </div>
+    </main>
+    <? include "import/html_footer.php"; ?>
+    
+    <?php
+    //--Manejo de errores y mensajes de exito
+    if(isset($_GET["error"]) && is_numeric($_GET["error"])){
+        switch ($_GET["error"]){
+            case 0: $errorDesc = "No se reciberon los datos de la solicitud de asignación."; break;
+            case 1: $errorDesc = "Ocurrió un error al insertar los datos de la solicitud de asignacióno."; break;
+            case 2: $errorDesc = "Ocurrió un error al actualizar los datos de la solicitud de asignación."; break;
+            case 3: $errorDesc = "No tienes permisos para realizar esa acción."; break;
+            case 4: $errorDesc = "Ocurrió un error al cargar los datos de la solicitud de asignación."; break;
+            case 6: $errorDesc = "La solicitud de asignación que buscas no existe. Consulta la lista de reopsiciones disponibles en esta sección."; break;
+            case 7: $errorDesc = "La solicitud de asignación se empalma con el horario del grupo y no se puede guardar."; break;
+            case 8: $errorDesc = "El salón de la solicitud de asignación está siendo utilizado ese día a esa hora y no se puede guardar."; break;
+            case 9: $errorDesc = "El profesor está asigndo a otra clase o solicitud de asignación el mismo día a la misma hora y no se puede guardar."; break;
+            case 10: $errorDesc = "El profesor está asigndo a una materia el mismo día a la misma hora y no se puede guardar."; break;
+            case 11: $errorDesc = "No hay clases asignadas para esa materia y grupo en la fecha de falta."; break;
+        }
+    }
+    if(isset($_GET["ok"]) && is_numeric($_GET["ok"])){
+        switch ($_GET["ok"]){
+            case 0: $successDesc = "La solicitud de asignación se guardó correctamente."; break;
+            case 1: $successDesc = "La solicitud de asignación se actualizó correctamente."; break;
+        }
+    }
+    require_once 'js/messages.php';
+    ?>
+    <script>
+    <?php if(isset($errorDesc)){ ?>
+    triggerMessage("<?php echo $errorDesc;?>", "Error");
+    <?php } else if(isset($successDesc)){ ?>
+    triggerMessage("<?php echo $successDesc;?>", "Éxito", "success");
+    <?php } ?>
+
+    var vacaciones=[
+        <?php
+        $vacaciones_rs = $db->query('SELECT diasfestivos_dia from diasfestivos d where :periodo = any(d.periodos_id)', [':periodo' => $user->periodo_id ]); 
+        
+            foreach($vacaciones_rs as $v){ echo '"'.$v["diasfestivos_dia"].'",';}
+        ?>
+    ];
+    var _dias_asistencia = [];//ya registró asistencia, cambia con ajax
+    var _dia_valido = 0;
+    var _fecha_manhana = "<?php echo $fecha_man; ?>";
+    var _periodo_fecha_inicial = "<?php echo date("d/m/Y", strtotime($periodo_rs["periodo_fecha_inicio"])); ?>";
+    var _periodo_fecha_final = "<?php echo date("d/m/Y", strtotime($periodo_rs["periodo_fecha_fin"])); ?>";
+    var datepickerOptions_filtro = { dateFormat: "dd/mm/yy", minDate:_periodo_fecha_inicial, maxDate:_periodo_fecha_final};
+
+    var datepickerOptions = { dateFormat: "dd/mm/yy", minDate:_periodo_fecha_inicial, maxDate:_periodo_fecha_final,
+        beforeShowDay: function(date) {
+            var day = date.getDay();
+            var dateString = $.datepicker.formatDate("yy-mm-dd", date);
+            if (day === _dia_valido) {// 0 representa el domingo
+                if (vacaciones.indexOf(dateString) !== -1 || _dias_asistencia.indexOf(dateString) !== -1) 
+                    return [false];
+                else
+                    return [true];
+            }else{
+                return [false];
+            }
+            
+        }
+    };
+    var datepickerOptions_future = { dateFormat: "dd/mm/yy", minDate:_fecha_manhana, maxDate:_periodo_fecha_final,
+        beforeShowDay: function(date) {
+            var day = date.getDay();
+            var dateString = $.datepicker.formatDate("yy-mm-dd", date);
+            if (day === 0) {// 0 representa el domingo
+                return [false];
+            } else {
+                if (vacaciones.indexOf(dateString) !== -1) {
+                    return [false];
+                } else {
+                    return [true];
+                }
+            }
+            
+        }
+    };
+
+    function diaAAno(fecha_str){//de dd/mm/yyyy a yyyy-mm-dd 
+        if(fecha_str.charAt(2) == "/" && fecha_str.charAt(5) == "/"){//dd/mm/yyyy
+            var fecha_arr = fecha_str.split("/");
+            return fecha_arr[2]+"-"+fecha_arr[1]+"-"+fecha_arr[0];
+        }
+        return fecha_str;
+    }
+    function fechaMayor(fechaI, fechaF) {//cual es mayor >0 I mayor   <0 F mayor
+        return (Date.parse(diaAAno(fechaI)) - Date.parse(diaAAno(fechaF)));
+    }
+
+    function validaFechas(){
+        if(fechaMayor($('#filtro_inicial').val().trim(), $('#filtro_final').val().trim()) > 0){
+            $('#filtro_final').addClass("is-invalid");
+            return false;
+        }
+        return true;
+    }
+
+    function submitForm(){
+        var myBtn = $('#submitBtn');
+        var error = false;
+        
+        $("#gpo").removeClass("is-invalid");
+        $("#fecha_inicial").removeClass("is-invalid");
+        $("#fecha_falta").removeClass("is-invalid");
+        $("#fecha_cambio").removeClass("is-invalid");
+        
+        if($("#fecha_falta").val() == ""){
+            $("#fecha_falta").addClass("is-invalid");
+            error = true;
+        }
+        if($("#fecha_inicial").val() == ""){//fecha reposición
+            $("#fecha_inicial").addClass("is-invalid");
+            error = true;
+        }
+        
+        console.log(myBtn.data("tipo"));
+        
+        if(myBtn.data("tipo") == 2 ){
+            $('#formaModal').prop("action", "./action/asignacion_update.php");
+        }else{
+            $('#formaModal').prop("action", "./action/asignacion_insert.php");
+        }
+        if(!error){
+            $("#loadingGroup").show();
+            $("#submitGroup").hide();
+        }
+        return !error;
+    }
+
+    
+    
+    $(document).ready(function(){
+        $(".prof-selected").hide();
+        //fecha de clase
+        $(".date-picker" ).datepicker(datepickerOptions);
+        $(".date-picker" ).datepicker( $.datepicker.regional[ "es" ] );
+
+        //fecha de clase
+        $(".date-picker-filtro" ).datepicker(datepickerOptions_filtro);
+        $(".date-picker-filtro" ).datepicker( $.datepicker.regional[ "es" ] );
+
+        //fecha nueva
+        $(".date-picker-future" ).datepicker(datepickerOptions_future);
+        $(".date-picker-future" ).datepicker( $.datepicker.regional[ "es" ] );
+        
+        
+        function creaOpcion(id_horario, dia, hora, min, nombre, gpo, duracion){
+            return '<li data-id="'+id_horario+'" data-dia="'+dia+'" data-hr="'+hora+'" data-min="'+min+'" data-gpo="'+gpo+'" data-duracion="'+duracion+'">'+nombre+'</li>';
+        }
+
+        $('#filtro_final').focus(function(){
+            $("#filtro_final").removeClass("is-invalid");
+        });
+
+        function obtieneProf(pid){
+            return $.ajax({
+                url:  './action/reposicion_profesor_materias.php',
+                type: 'POST', 
+                dataType: 'json',
+                data: { id: pid, },
+                //async: false,
+                success: function(result) {
+                    if(result["error"]!= "" &&  result["error"] !== undefined){
+                        triggerMessage(result["error"], "Error");
+                        $("#modal").modal('hide');
+                        $(".prof-selected").hide();
+                    }else{
+                        $(".prof-selected").show();
+                        $("#dlMateria ul").html("");
+                        for(i=0; i<result["materias"].length; i++){
+                            var html = creaOpcion(result["materias"][i]["horario_id"],
+                                result["materias"][i]["horario_dia"],
+                                result["materias"][i]["horario_hora"],
+                                result["materias"][i]["horario_min"],
+                                result["materias"][i]["materia_nombre"],
+                                result["materias"][i]["grupo"],
+                                result["materias"][i]["duracion"]
+                                );
+                            $("#dlMateria ul").append(html);
+                        }
+                    }
+                },
+                error: function(jqXHR, textStatus, errorThrown ){
+                    triggerMessage(errorThrown, "Error");
+                }
+            });//ajax
+        }
+
+        $(document).on( "click", "#dlProfesor ul li", function(event){//cambia datalist
+            var pid = $(this).data('id');
+            //busca materias del profesor
+            var profCarga = obtieneProf(pid);
+            profCarga.done(function(){
+                $("#dlMateria ul li:first").click();
+            });
+        });
+        
+        
+        //Actualiza días elegibles de calendario
+        $(document).on( "click", "#dlMateria ul li", function(event){//manda al frente de todos
+            _dia_valido = $(this).data('dia');//variable global
+            var grupo = $(this).data("gpo");
+            var duracionMateria = $(this).data("duracion");
+
+            $(".date-picker" ).datepicker(datepickerOptions);
+            var hora = $(this).data("hr");
+            var min = $(this).data("min");
+            $("#hora_ini").val(hora)
+            $("#min_ini").val(min)
+
+            return $.ajax({
+                url:  './action/asistenciasprofesor_select.php',
+                type: 'POST', 
+                dataType: 'json',
+                data: { "id": $("#prof").val(), "hor": $(this).data("id") },
+                //async: false,
+                success: function(result) {
+                    if(result["error"]!= "" &&  result["error"] !== undefined){
+                        triggerMessage(result["error"], "Error");
+                        $('#modal').modal("hide");
+                    }else{
+                        _dias_asistencia = result["asistenciaArr"];
+                        
+                        $('#duracion option').each(function() {
+                            if ($(this).data("duracion") === duracionMateria) {
+                                // Selecciona la opción correspondiente en el select de "duracion"
+                                $(this).prop('selected', true);
+                            }
+                        });
+                    }
+
+                },
+                error: function(jqXHR, textStatus, errorThrown ){
+                    triggerMessage(errorThrown, "Error");
+                }
+            });//ajax
+            
+            
+        });
+        
+
+        $('#modal_confirm').on('show.bs.modal', function (event) {
+            var button = $(event.relatedTarget); // Button that triggered the modal
+            var id = button.parents("tr").data("id");
+            $("#id_borrar").val(id);
+            
+        });
+        
+        $(".btn-borrar").click(function(){
+            var r_id =  $("#id_borrar").val();
+            $.ajax({
+                url:  './action/asignacion_delete.php',
+                type: 'POST', 
+                dataType: 'json',
+                data: { id: r_id},
+                success: function(result) {
+                    if(result["error"]!= "" &&  result["error"] !== undefined){
+                        triggerMessage(result["error"], "Error");
+                    }else{
+                        triggerMessage(result["ok"], "Éxito", "success");
+                        $("#id"+r_id).remove();
+                    }
+                },
+                error: function(jqXHR, textStatus, errorThrown ){
+                    triggerMessage(errorThrown, "Error");
+                }
+            });//ajax
+            $('#modal_confirm').modal("hide");
+        });
+
+        
+        $('#modal').on('show.bs.modal', function (event) {
+            var button = $(event.relatedTarget); // Button that triggered the modal
+            var tipo = button.data('tipo'); // 1 alta, 2 edicion
+            var modal = $(this);
+            $("#loadingGroup").hide();
+            $("#submitGroup").show();
+            
+            $("#modal .is-invalid").removeClass("is-invalid");
+            //$(this).find(".form-control:first-child").focus();
+            $('#submitBtn').attr("disabled", false);
+            
+
+            $("#errorBox").collapse('hide');
+            $("#errorBox_text").html("");
+            if(tipo == 1){//alta
+                $("#submitBtn").data('tipo', 1);
+                $("#modalLabel").html("Solicitar Asignación");
+                modal.find("input[type=text]").val("");
+                modal.find("#alumnos").val("15");
+                $("#plan").attr("readonly", false);
+                $("#sem").attr("readonly", false);
+                $("#gpo").attr("readonly", false);
+                
+                //$("#prof").attr("readonly", false);
+                disableDatalist("#horario", false);
+                disableDatalist("#tipo", false);
+                if($("#prof").length>0)
+                    disableDatalist("#prof", false);
+                setDatalistFirst("#tipo");
+                setDatalistFirst("#aula");
+                setDatalistFirst("#horario");
+                $("#dlMateria ul li:first").click();
+                
+            }else{//editar
+                $("#submitBtn").data('tipo', 2);
+                $("#modalLabel").html("Editar solicitud");
+                $("#plan").attr("readonly", true);
+                $("#sem").attr("readonly", true);
+                $("#gpo").attr("readonly", true);
+                //$("#materia").attr("readonly", true);
+                disableDatalist("#horario");
+                disableDatalist("#tipo");
+                disableDatalist("#prof");
+                /*if($("#prof").length>0)
+                    disableDatalist("#prof");
+                $("#prof").attr("readonly", true);*/
+                var r_id = $(button).parents("tr").data("id");
+                $("#id").val(r_id);
+                $.ajax({
+                    url:  './action/asignacion_select.php',
+                    type: 'POST', 
+                    dataType: 'json',
+                    data: { id: r_id },
+                    async: true,
+                    success: function(result) {
+                        if(result["error"]!= "" &&  result["error"] !== undefined){
+                            triggerMessage(result["error"], "Error");
+                            $("#modal").modal('hide');
+                        }else{
+                            //setDatalist("#prof", result["profesor"]);
+                            setDatalist("#prof", result["profesor"]);
+                            
+                            var profCarga = obtieneProf(result["profesor"]);
+
+                            //$('#salon').val(result["salon"]);
+                            $("#fecha_falta").val(result["fecha_clase"]);
+                            $('#hora_ini').val(result["hora_ini"]);
+                            $('#min_ini').val(result["min_ini"]);
+                            $('#comentario').val(result["comentario"]);
+                            $('#alumnos').val(result["alumnos"]);
+                            
+
+                                $("#fecha_inicial").val(result["fecha_nueva"]);
+
+                                $("#fecha_cambio").val(result["fecha_nueva"]);
+                            
+                            _dia_valido = parseInt(result["dia"]);
+                            $(".date-picker" ).datepicker(datepickerOptions);
+                            $("#dlTipo ul li:selected").click();
+                            
+                            
+                            profCarga.done(function(){
+                                setDatalist("#horario", result["horario"]);// No se actualiza TODO
+                            });
+                            setDatalist("#aula", result["aula"]);
+                            modal.modal('show');
+                        }
+                    },
+                    error: function(jqXHR, textStatus, errorThrown ){
+                        triggerMessage(errorThrown, "Error");
+                        $("#modal").modal('hide');
+                        //$('#messageBox')[0].scrollIntoView({ block: "end" });
+                    }
+                });//ajax
+            }
+        });//show
+        
+    });
+
+    $(function() {
+        $('[data-toggle="tooltip"]').tooltip()
+    })
+</script>
+<script src="js/messages.js"></script>
+
+</body>
+
+</html>

+ 26 - 0
auditoria.php

@@ -62,8 +62,13 @@
         <!-- {{ store.filters }} -->
         <?php include "import/periodo.php" ?>
         <div class="form-box marco">
+<<<<<<< HEAD
             <? if (!$user->facultad['facultad_id']) { ?>
                 <div class="form-group row">
+=======
+            <div class="form-group row">
+                <? if (!$user->facultad['facultad_id']) { ?>
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                     <label for="dlFacultad" class="col-4 col-form-label">Facultad</label>
                     <div class="col-6">
                         <div id="dlFacultad" class="datalist datalist-select mb-1 w-100">
@@ -86,6 +91,7 @@
                             <input type="hidden" id="facultad_id" name="id">
                         </div>
                     </div>
+<<<<<<< HEAD
                 </div>
                 <div class="form-group row">
                     <!-- Checkbox para descargar todo -->
@@ -98,6 +104,10 @@
                     </div>
                 </div>
             <? } ?>
+=======
+                <? } ?>
+            </div>
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
 
             <div class="form-group row" v-if="store.bloques_horario.data.length > 0">
                 <label for="dlBloqueHorarios" class="col-4 col-form-label">Bloque horarios</label>
@@ -526,8 +536,12 @@
                                                     <strong>{{clase_vista.justificador_facultad}}</strong>
                                                 </span>
 
+<<<<<<< HEAD
                                                 el día {{clase_vista.registro_fecha_justificacion?.slice(0, 10)}} a
                                                 las
+=======
+                                                el día {{clase_vista.registro_fecha_justificacion?.slice(0, 10)}} a las
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                                                 {{clase_vista.registro_fecha_justificacion?.slice(11, 16)}}
                                             </span>
                                             <div v-if="clase_vista.justificacion">
@@ -623,8 +637,12 @@
                                         Justificar <strong :class="`text-${store.current.justificada.estado_color}`"
                                             class="text-uppercase">
                                             {{store.current.justificada.nombre}}</strong> del día <span
+<<<<<<< HEAD
                                             class="text-muted">{{store.current.justificada.registro_fecha_ideal}}</span>
                                         a
+=======
+                                            class="text-muted">{{store.current.justificada.registro_fecha_ideal}}</span> a
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                                         las <span
                                             class="text-muted">{{store.current.justificada.horario_hora?.slice(0,5)}}</span>
                                         para el profesor <span
@@ -682,14 +700,22 @@
                             <p class="lead">
                                 Selecciona los bloques que deseas justificar, puedes seleccionar varios bloques
                                 <small>
+<<<<<<< HEAD
                                     Todos los profesores que tengan clases en los bloques seleccionados serán
                                     justificados
+=======
+                                    Todos los profesores que tengan clases en los bloques seleccionados serán justificados
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                                 </small>
                             </p>
                             <form>
                                 <div class="form-group row" v-if="store.periodo">
+<<<<<<< HEAD
                                     <label for="fecha-justificación" class="col-sm-4 col-form-label barra-right">Fecha
                                         de la
+=======
+                                    <label for="fecha-justificación" class="col-sm-4 col-form-label barra-right">Fecha de la
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                                         justificación</label>
                                     <div class="col-sm-8">
                                         <input type="date" class="form-control" id="fecha-justificación"

+ 927 - 0
cambio_crear.php

@@ -0,0 +1,927 @@
+<?php
+
+require_once 'class/c_login.php';
+if (!isset($_SESSION['user'])){
+    die(header('Location: index.php'));
+}
+
+//$user = unserialize($_SESSION['user']);
+$user = Login::get_user();
+
+$user->access();
+//profesor, admin, rol, facultad
+if ($user->acceso === null && !$user->admin){
+    die(header('Location: index.php'));
+    exit();
+}
+
+
+$write = true; //
+
+$en_fecha = $db->querySingle("SELECT ESTA_EN_PERIODO(NOW()::DATE, :periodo_id)", [':periodo_id' => $user->periodo_id])['esta_en_periodo'];
+
+
+if($user->jefe_carrera){
+    //$prof_rs = $db->query('SELECT DISTINCT * FROM fs_profesores(null, null, :fac) ORDER BY PROFESOR_NOMBRE', [':fac' => $user->facultad["facultad_id"]]);
+    $prof_rs = $db->query('SELECT DISTINCT PROFESOR.* FROM PUESTO_USUARIO
+        JOIN PUESTO_MATERIA USING (PUESTO_ID)
+        JOIN HORARIO_VIEW USING (MATERIA_ID)
+        JOIN HORARIO_PROFESOR USING (HORARIO_ID)
+        JOIN PROFESOR USING (PROFESOR_ID)
+        WHERE USUARIO_ID = :usr', [':usr' => $user->user["id"]]);
+}else{
+    $prof_rs = $db->query('SELECT DISTINCT PROFESOR.* FROM PROFESOR
+        JOIN horario_profesor USING (profesor_id)
+        JOIN HORARIO_VIEW USING (horario_id)
+        WHERE FACULTAD_ID = :fac ORDER BY profesor.profesor_nombre', [':fac' => $user->facultad["facultad_id"]]);
+}
+
+//Duraciones
+$duracion_rs = $db->query("select * from duracion order by duracion_interval");
+
+if(!is_null($user->periodo_id)){
+    //Periodo
+    $periodo_rs = $db->querySingle('SELECT periodo_fecha_inicio, periodo_fecha_fin FROM periodo WHERE periodo_id = :periodo_id', [':periodo_id' => $user->periodo_id]);
+    $periodo_fin = $periodo_rs["periodo_fecha_fin"];
+    if(strtotime($periodo_rs["periodo_fecha_inicio"])>strtotime(date("Y-m-d")) )
+        $fecha_man = date("d/m/Y", strtotime($periodo_rs["periodo_fecha_inicio"]));
+    else{
+        $dia_actual = intval(date("w"));
+        $dias = 2;//días mínimos Lun a Jue
+        if($dia_actual ==5 || $dia_actual ==4 )//Vie
+            $dias=4;
+        else if( $dia_actual ==6 )//Sab
+            $dias=3;
+        else if( $dia_actual ==0 )//Do
+            $dias=2;
+        
+        $fecha_man = date("d/m/Y", strtotime("+".$dias." day"));
+    }
+    /*
+    // Materias
+    $id_prof = $user->profesor;
+    //$facultad_id = 28;
+    $materias_rs = $db->query('SELECT * FROM fs_materiasprofesor(:id)', [':id' => $id_prof]);
+    */
+    if(isset($_POST["fecha_inicial"]))
+        $fecha_ini = $_POST["fecha_inicial"];
+    else
+        $fecha_ini = date("d/m/Y", strtotime($periodo_rs["periodo_fecha_inicio"]));
+
+    if(isset($_POST["fecha_final"]))
+        $fecha_fin = $_POST["fecha_final"];
+    else
+        $fecha_fin = date("d/m/Y", strtotime($periodo_rs["periodo_fecha_fin"]));
+
+    $date = DateTime::createFromFormat('d/m/Y', $fecha_ini);
+    $fecha_ini_db = $date->format('Y-m-d');
+
+    $date = DateTime::createFromFormat('d/m/Y', $fecha_fin);
+    $fecha_fin_db = $date->format('Y-m-d');
+}
+
+?>
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Reposiciones crear |
+        <?= $user->facultad['facultad'] ?? "Administrador"; ?>
+    </title>
+    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
+        integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
+        crossorigin="anonymous" referrerpolicy="no-referrer" />
+    <?php
+    include 'import/html_css_files.php';
+    ?>
+    <link rel="stylesheet" href="css/jquery-ui.css">
+    <link rel="stylesheet" href="css/calendar.css">
+    <style>
+        .wizard { height: 20px; width: 80%; background: #D0D0D0; }
+        .wizard.full { background: #D0D0D0; }
+        .wizard.active > div:first-child { background: #00A6CE;  }
+        .wizard.active > div:last-child { width: 0px; height: 0px; border-style: solid; border-width: 10px 0 10px 6px; border-color: transparent transparent transparent #00a6ce; transform: rotate(0deg); }
+    </style>
+    <script src="js/jquery.min.js"></script>
+    <script src="js/bootstrap/popper.min.js"></script>
+    <script src="js/bootstrap/bootstrap.min.js"></script>
+    <script src="js/jquery-ui.js"></script>
+    <script src="js/datepicker-es.js"></script>
+</head>
+
+
+<!--  -->
+
+<body style="display: block;">
+    <?php
+    include('include/constantes.php');
+    include("import/html_header.php");
+    html_header("Cambios permanentes de horario", "Sistema de gestión de checador");
+    ?>
+
+    <main class="container content marco content-margin" id="local-app">
+        <?php
+        if($write==true && isset($prof_rs) && count($prof_rs)>0)  {?>
+        <!-- Botón para abrir el modal -->
+        <div class="row mb-4">
+            <div class="col-12 text-right">
+                <button type="button" class="btn btn-outline-secondary" data-tipo="1" data-toggle="modal" data-target="#modal" <?php if (!$en_fecha ) { echo "disabled"; } ?>><span class="ing-mas ing-fw"></span>Solicitar cambio</button>
+            </div>
+        </div>
+        <?php }?>
+        <section id="message"></section>
+        <?php require('import/periodo.php') ?>
+        <?php if(!is_null($user->periodo_id)) { ?>
+        <form id="asistencia" method="post" onsubmit="return validaFechas()">
+            <div class="form-box">
+                <input type="hidden" name="facultad" value="">
+                
+                <div class="form-group row">
+                    <label for="filtro_inicial" class="col-4 col-form-label">Fecha inicial</label>
+                    <div class="col-8 col-sm-4">
+                        <input id="filtro_inicial" name="fecha_inicial" type="text" class="form-control date-picker-filtro" placeholder="dd/mm/aaaa" maxlength="10" required="required" readonly="" value="<?php echo $fecha_ini;?>">
+                        <div class="invalid-feedback">No es una fecha válida.</div>
+                    </div>
+                </div>
+                <div class="form-group row">
+                    <label for="filtro_final" class="col-4 col-form-label">Fecha final</label>
+                    <div class="col-8 col-sm-4">
+                        <input id="filtro_final" name="fecha_final" type="text" class="form-control date-picker-filtro" placeholder="dd/mm/aaaa" maxlength="10" required="required" readonly="" value="<?php echo $fecha_fin;?>">
+                        <div class="invalid-feedback">El rango de fechas no es válido.</div>
+                    </div>
+                </div>
+            </div>
+            <div class="form-group row justify-content-center">
+                <button type="submit" class="btn btn-outline-primary mr-2" id="btn-buscar"><span class="ing-buscar ing-fw"></span> Buscar</button>
+                <button type="button" class="btn btn-outline-danger" onclick="window.location.href = window.location.href"><span class="ing-borrar ing-fw"></span> Limpiar</button>
+            </div>
+        </form>
+
+        <?php
+        
+            $reposiciones_rs = $db->query('SELECT * FROM fs_cambios_solicitud(:f_ini, :f_fin, :usr ,NULL)', [':f_ini' => $fecha_ini_db, ':f_fin' => $fecha_fin_db, ':usr' => $user->user["id"]]);
+        }
+        ?>
+
+        <div class="row">
+            <?php
+            if(isset($reposiciones_rs) && count($reposiciones_rs)>0){ ?>
+            <h3 class="mb-3">Reposiciones creadas</h3>
+            <div class="col-12 table-responsive px-0">
+                <table class="table table-sm table-striped table-white">
+                    <thead class="thead-dark">
+                        <tr >
+                            <th>Estado</th>
+                            <th>Materia</th>
+                            <th>Profesor</th>
+                            <th style="width:160px">Fecha</th>
+                            <th style="width:160px">Duración</th>
+                            <th>Salón</th>
+                            <?php if($write){ ?><th>Acciones</th><?php } ?>
+                        </tr>
+                    </thead>
+                    <tbody>
+                        <?php
+                        foreach($reposiciones_rs as $reposicion){
+                        ?>
+                        <tr data-id="<?php echo $reposicion["reposicion_id"]; ?>" id="id<?php echo $reposicion["reposicion_id"]; ?>">
+                            <td class="align-middle text-center" style="color:<?php echo $reposicion["estado_color"];?>" title="<?php echo $reposicion["estado_nombre"];?>">
+                                <?php if($reposicion["estado_reposicion_id"]<3){ ?>
+                                <div class="wizard <?php if(intval($reposicion["estado_reposicion_id"])==2) echo "active";?> d-flex mx-auto">
+                                    <div class="w-50 h-100"></div>
+                                    <div class=""></div>
+                                </div>
+                                <?php } else if($reposicion["estado_reposicion_id"]==3){?>
+                                <div class="text-success text-center pt-1">
+                                    <span class="ing-autorizar ing-lg"></span>
+                                </div>
+                                <?php } else {?>
+                                <div class="text-danger text-center pt-1">
+                                    <span class="ing-negar ing-lg"></span>
+                                </div>
+                                <?php } ?>
+                            </td>
+                            <td class="align-middle"><?php echo $reposicion["materia_nombre"]; ?></td>
+                            <td class="align-middle">
+                                <?php if($reposicion["es_reposicion"]) echo "Reposición"; else echo "Cambio"; ?>
+                            </td>
+                            <td class="align-middle text-center"><?php
+                                echo date("d/m/Y", strtotime($reposicion["fecha_clase"]))."<br>".substr($reposicion["horario_hora"],0,-3)." a ".substr($reposicion["horario_hora_fin"],0,-3)." hrs.";;
+                                ?>
+                            </td>
+                            <td class="align-middle text-center"><?php
+                                
+                                echo date("d/m/Y", strtotime($reposicion["fecha_nueva"])) ."<br>".substr($reposicion["hora_nueva"],0,-3)." a ".substr($reposicion["hora_nueva_fin"],0,-3)." hrs.";
+                                ?>
+                            </td>
+                            <td class="align-middle text-center"><?php
+                                echo $reposicion["duracion_total"];
+                                ?>
+                            </td>
+                            <td class="align-middle text-center"><?php
+                                if($reposicion["salon_id"] != ""){
+                                    echo $reposicion["salon_id"];
+                                }else
+                                    echo "Pendiente";
+                                ?>
+                            </td>
+                            
+                            <?php if($write){ ?>
+                            <td class="align-middle text-center icono-acciones">
+                                <?php
+                                
+                                //no se ha aprobado
+                                if(($reposicion["estado_reposicion_id"] == 1 && $user->jefe_carrera) || ($reposicion["estado_reposicion_id"] == 2 && !$user->jefe_carrera)){?>
+                                <a href="#" data-tipo="2" title="Editar" data-toggle="modal" data-target="#modal"><?php echo $ICO["editar"];?></a>
+                                <a href="#" data-toggle="modal" data-target="#modal_confirm" title="Borrar"><?php echo $ICO["cancelar"];?></a>
+                                <?php } ?>
+                            </td>
+                            <?php } ?>
+                        </tr>
+                        <?php }
+                    ?>
+                    </tbody>
+                </table>
+            </div>
+            <?php } else { 
+                if(is_null($user->periodo_id)){ ?>
+            <div class="col-12 text-center">
+                <h4 class="mt-4 text-danger">Selecciona un periodo</h4>
+            </div>
+            <?php } else {?>    
+            <div class="col-12 text-center">
+                <h4 class="mt-4 text-danger">No hay solicitudes de cambio disponibles que cumplan con los filtros</h4>
+            </div>
+            <?php }
+            } ?>
+        </div>
+
+        <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modal" aria-hidden="true">
+            <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
+                <div class="modal-content">
+                    <div class="modal-header">
+                        <h4 class="col-12 modal-title text-center"><span id="modalLabel">Solicitar Cambio</span>
+                        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
+                            <span aria-hidden="true">&times;</span>
+                        </button></h4>
+                    </div>
+                    <div class="modal-body">
+                        <form action="./action/cambio_insert.php" method="post" id="formaModal" onsubmit="return submitForm()">
+                            <input type="hidden" name="id" id="id">
+                            <input type="hidden" name="estado" value="1">
+                            <input type="hidden" name="ciclo" id="ciclo" value="0">
+                            <input type="hidden" name="bloque" id="bloque" value="0">
+                            
+                            <div class="form-box">
+
+                                <div class="form-group row" id="profBlock">
+                                    <label for="prof" class="col-4 col-form-label">Profesor *</label> 
+                                    <div class="col-8">
+                                        <div class="datalist datalist-select mb-1 w-100" id="dlProfesor">
+                                            <div class="datalist-input">Selecciona un profesor</div>
+                                            <span class="ing-buscar icono"></span>
+                                            <ul style="display:none">
+                                                <?php foreach($prof_rs as $prof){?>
+                                                    <li data-id="<?php echo $prof["profesor_id"];?>" <?php if($prof["profesor_id"]==$user->profesor){ echo "class='selected'";} ?> ><?php echo $prof["profesor_nombre"];?></li>
+                                                <?php } ?>
+                                            </ul>
+                                            <input type="hidden" id="prof" name="prof" value="">
+                                        </div>
+                                    </div>
+                                </div>
+                            </div>
+                            <div class="form-box prof-selected">
+                                <div class="form-group row" id="materiaBlock">
+                                    <label for="horario" class="col-4 col-form-label">Materia *</label> 
+                                    <div class="col-8">
+                                        <div class="datalist datalist-select mb-1 w-100" id="dlMateria">
+                                            <div class="datalist-input">Selecciona una materia</div>
+                                            <span class="ing-buscar icono"></span>
+                                            <ul style="display:none">
+                                            
+                                            </ul>
+                                            <input type="hidden" id="horario" name="horario" value="">
+                                        </div>
+                                    </div>
+                                </div>
+
+                                <div class="form-group row" id="profBlock">
+                                    <label for="prof" class="col-4 col-form-label">Profesor nuevo*</label> 
+                                    <div class="col-8">
+                                        <div class="datalist datalist-select mb-1 w-100" id="dlProfesor">
+                                            <div class="datalist-input">Selecciona un profesor</div>
+                                            <span class="ing-buscar icono"></span>
+                                            <ul style="display:none">
+                                                <?php foreach($prof_rs as $prof){?>
+                                                    <li data-id="<?php echo $prof["profesor_id"];?>" <?php if($prof["profesor_id"]==$user->profesor){ echo "class='selected'";} ?> ><?php echo $prof["profesor_nombre"];?></li>
+                                                <?php } ?>
+                                            </ul>
+                                            <input type="hidden" id="prof" name="prof" value="">
+                                        </div>
+                                    </div>
+                                </div>
+                                
+
+                                <div class="form-group row materia-block">
+                                    <label for="duracion" class="col-4 col-form-label">Duración</label> 
+                                    <div class="col-4">
+                                        <select name="duracion" id="duracion" class="form-control" required="required">
+                                            <?php foreach($duracion_rs as $dura){?>
+                                            <option value="<?php echo $dura["duracion_id"];?>" data-duracion="<?php echo $dura["duracion_interval"];?>" ><?php echo $dura["duracion_nombre"];?></option>
+                                            <?php } ?>
+                                        </select>
+                                        <small class="form-text text-muted">Original: <span id="duracion_original">0</span></small>
+                                    </div>
+                                </div>
+                                
+                                <div class="form-group row cambio_block materia-block">
+                                    <label for="fecha_cambio" class="col-4 col-form-label">Fecha de cambio *</label> 
+                                    <div class="col-8">
+                                        <small class="form-text text-muted">Selecciona el día a partir del cuál se aplicará</small>
+                                        <input id="fecha_cambio" name="fecha_cambio" type="text" class="form-control date-picker" placeholder="dd/mm/aaaa" maxlength="10" required="required" readonly="readonly" value="">
+                                    </div>
+                                </div>
+
+                                
+                                <div class="form-group row materia-block">
+                                    <label for="hora_ini" class="col-4 col-form-label" id="hora_nombre">Hora cambio *</label>
+                                    <?php
+                                    //define("HORA_FINAL", 22);
+                                    //define("FRACCION_HORA", 15);
+                                    $default_h = 7; $default_m = 15;
+                                    ?>
+                                    <div class="col-4">
+                                        <select name="hora_ini" id="hora_ini" class="form-control" required="required">
+                                            <?php for($h = $default_h; $h < HORA_FINAL; $h++){?>
+                                            <option value="<?php echo sprintf( '%02d', $h );?>" <?php if($default_h == $h){ echo 'selected="selected"';}?>><?php echo sprintf( '%02d', $h );?></option>
+                                            <?php } ?>
+                                        </select>
+                                        <small class="form-text text-muted">Original: <span id="hora_original">0</span></small>
+                                    </div>
+                                    <div class="col-4">
+                                        <select name="min_ini" id="min_ini" class="form-control" required="required">
+                                            <?php for($m = 0; $m < 60; $m+=(60/FRACCION_HORA)){?>
+                                            <option value="<?php echo sprintf( '%02d', $m );?>" <?php if($default_m == $m){ echo 'selected="selected"';}?>><?php echo sprintf( '%02d', $m );?></option>
+                                            <?php } ?>
+                                        </select>
+                                    </div>
+                                </div>
+
+                                
+                                <div class="form-group row materia-block">
+                                    <label for="salon" class="col-4 col-form-label">Alumnos aproximados *</label> 
+                                    <div class="col-8 col-md-4">
+                                        <input type="number" name="alumnos" id="alumnos" class="form-control" value="1" min="1" max="50">
+                                    </div>
+                                </div>
+                                
+                                <div class="form-group row materia-block">
+                                    <label for="aula" class="col-4 col-form-label">Tipo aula *</label> 
+                                    <div class="col-8">
+                                        <div class="datalist datalist-select mb-1 w-100" id="dlAula">
+                                            <div class="datalist-input">Salón</div>
+                                            <span class="ing-buscar icono"></span>
+                                            <ul style="display:none">
+                                                <?php
+                                                $tipoaula_rs = $db->query('select * from tipoaula t order by t.tipoaula_id ');
+                                                foreach($tipoaula_rs as $ta){ ?>
+                                                    <li data-id="<?php echo $ta["tipoaula_id"];?>"><?php echo $ta["tipoaula_nombre"];?></li>
+                                                <?php } ?>
+                                            </ul>
+                                            <input type="hidden" id="aula" name="aula" value="1">
+                                        </div>
+                                    </div>
+                                </div>
+                                <?php if(!$user->jefe_carrera){//es coordinador
+                                    $salones_rs = $db->query('SELECT * from salon_view where es_salon is true');
+                                ?>
+                                <div class="row" id="salon-editar" style="display: none;">
+                                    <div class="col-6 col-sm-4 barra-right text-right">
+                                        <p class="font-weight-bold">Salón *</p>
+                                    </div>
+                                    <div class="col-6">
+                                        <input list="lista_salones" name="dlSalon" id="dlSalon" class="form-control" placeholder="Salón">
+                                        <div class="valid-feedback">
+                                            Salón encontrado
+                                        </div>
+                                        <div class="invalid-feedback">
+                                            Salón no encontrado
+                                        </div>
+                                        <datalist id="lista_salones">
+                                            <?php
+                                            foreach ($salones_rs as $salon) {
+                                                extract($salon);
+                                                $salon_json = json_decode($salon_array, true);
+                                                if($salon_json[0]== "UNIVERSIDAD LA SALLE"){
+                                                    unset($salon_json[0]);
+                                                }
+                                                $salon_nombre = join(" / ",$salon_json);
+                                            ?>
+                                                <option data-id="<?= $salon_id ?>" data-nombre="<?= $salon_nombre ?>" value="<?= $salon_nombre ?>"></option>
+                                            <?php
+                                            }
+                                            ?>
+                                        </datalist>
+                                        <!-- <ul class="list-group" id="salones"></ul> -->
+                                        <input type="hidden" id="salon" name="salon" value="">
+                                    </div>
+                                </div>
+                                <?php } ?>
+                            
+                                <div class="form-group row materia-block">
+                                    <label for="comentario" class="col-4 col-form-label">Comentarios</label> 
+                                    <div class="col-8">
+                                        <p><i>Requerimientos específicos del salón, software especializado, etc.</i></p>
+                                        <textarea rows="3" class="form-control" id="comentario" name="comentario"></textarea>
+                                    </div>
+                                </div>
+                            </div>
+                            
+                            <div class="form-group row mt-3" id="submitGroup">
+                                <div class="offset-4 col-8">
+                                    <button type="submit" class="btn btn-outline-primary  materia-block" id="submitBtn" data-tipo="1"><?php echo $ICO["aceptar"];?> Guardar</button>
+                                    <button type="reset" class="btn btn-outline-danger" data-dismiss="modal"><?php echo $ICO["cancelar"];?> Cancelar</button>
+                                </div>
+                            </div>
+                            <div class="form-group row mt-3" id="loadingGroup" style="display:none">
+                                <div class="col-12 text-center">
+                                    <div class="spinner-border text-primary" role="status">
+                                        <span class="sr-only">Loading...</span>
+                                    </div>
+                                </div>
+                            </div>
+                        </form>
+                    </div>
+                </div>
+            </div>
+        </div>
+
+
+        
+    
+        <div class="modal fade" id="modal_confirm" tabindex="-1" role="dialog" aria-labelledby="modal" aria-hidden="true">
+            <div class="modal-dialog modal-dialog-centered" role="document">
+                <div class="modal-content">
+                    <div class="modal-body">
+                        <div class="row">
+                            <div class="col">
+                                <p class="font-weight-bold">¿Estás seguro de que quieres borrar la reposición?</p>
+                                <p>Esta acción no se puede deshacer.</p>
+                            </div>
+                        </div>
+                    </div>
+                    <div class="modal-footer">
+                        <input type="hidden" id="id_borrar" value="">
+                        <button type="button" class="btn btn-outline-primary btn-borrar"><?php echo $ICO["aceptar"];?> Borrar</button>
+                        <button type="button" class="btn btn-outline-danger" data-dismiss="modal" aria-label="Close"><?php echo $ICO["cancelar"];?> Cancelar</button>
+                    </div>
+                </div>
+            </div>
+        </div>
+    </main>
+    <? include "import/html_footer.php"; ?>
+    
+    <?php
+    //--Manejo de errores y mensajes de exito
+    if(isset($_GET["error"]) && is_numeric($_GET["error"])){
+        switch ($_GET["error"]){
+            case 0: $errorDesc = "No se reciberon los datos de la reposición."; break;
+            case 1: $errorDesc = "Ocurrió un error al insertar los datos de la reposición/cambio."; break;
+            case 2: $errorDesc = "Ocurrió un error al actualizar los datos de la reposición/cambio."; break;
+            case 3: $errorDesc = "No tienes permisos para realizar esa acción."; break;
+            case 4: $errorDesc = "Ocurrió un error al cargar los datos de la reposición/cambio."; break;
+            case 6: $errorDesc = "La reposición/cambio que buscas no existe. Consulta la lista de reopsiciones disponibles en esta sección."; break;
+            case 7: $errorDesc = "La reposición/cambio se empalma con el horario del grupo y no se puede guardar."; break;
+            case 8: $errorDesc = "El salón de la reposición está siendo utilizado ese día a esa hora y no se puede guardar."; break;
+            case 9: $errorDesc = "El profesor está asigndo a otra clase o reposición el mismo día a la misma hora y no se puede guardar."; break;
+            case 10: $errorDesc = "El profesor está asigndo a una materia el mismo día a la misma hora y no se puede guardar."; break;
+            case 11: $errorDesc = "No hay clases asignadas para esa materia y grupo en la fecha de falta."; break;
+        }
+    }
+    if(isset($_GET["ok"]) && is_numeric($_GET["ok"])){
+        switch ($_GET["ok"]){
+            case 0: $successDesc = "La reposición se guardó correctamente."; break;
+            case 1: $successDesc = "La reposición se actualizó correctamente."; break;
+        }
+    }
+    require_once 'js/messages.php';
+    ?>
+    <script>
+    <?php if(isset($errorDesc)){ ?>
+    triggerMessage("<?php echo $errorDesc;?>", "Error");
+    <?php } else if(isset($successDesc)){ ?>
+    triggerMessage("<?php echo $successDesc;?>", "Éxito", "success");
+    <?php } ?>
+
+    var vacaciones=[
+        <?php
+        $vacaciones_rs = $db->query('SELECT diasfestivos_dia from diasfestivos d where :periodo = any(d.periodos_id)', [':periodo' => $user->periodo_id ]); 
+        
+            foreach($vacaciones_rs as $v){ echo '"'.$v["diasfestivos_dia"].'",';}
+        ?>
+    ];
+    var _dias_asistencia = [];//ya registró asistencia, cambia con ajax
+    var _dia_valido = 0;
+    var _fecha_manhana = "<?php echo $fecha_man; ?>";
+    var _periodo_fecha_inicial = "<?php echo date("d/m/Y", strtotime($periodo_rs["periodo_fecha_inicio"])); ?>";
+    var _periodo_fecha_final = "<?php echo date("d/m/Y", strtotime($periodo_rs["periodo_fecha_fin"])); ?>";
+    var datepickerOptions_filtro = { dateFormat: "dd/mm/yy", minDate:_periodo_fecha_inicial, maxDate:_periodo_fecha_final};
+
+    var datepickerOptions = { dateFormat: "dd/mm/yy", minDate:_periodo_fecha_inicial, maxDate:_periodo_fecha_final,
+        beforeShowDay: function(date) {
+            var day = date.getDay();
+            var dateString = $.datepicker.formatDate("yy-mm-dd", date);
+            
+                if (vacaciones.indexOf(dateString) !== -1 || _dias_asistencia.indexOf(dateString) !== -1) 
+                    return [false];
+                else
+                    return [true];
+            
+            
+        }
+    };
+    var datepickerOptions_future = { dateFormat: "dd/mm/yy", minDate:_fecha_manhana, maxDate:_periodo_fecha_final,
+        beforeShowDay: function(date) {
+            var day = date.getDay();
+            var dateString = $.datepicker.formatDate("yy-mm-dd", date);
+            if (day === 0) {// 0 representa el domingo
+                return [false];
+            } else {
+                if (vacaciones.indexOf(dateString) !== -1) {
+                    return [false];
+                } else {
+                    return [true];
+                }
+            }
+            
+        }
+    };
+
+    function diaAAno(fecha_str){//de dd/mm/yyyy a yyyy-mm-dd 
+        if(fecha_str.charAt(2) == "/" && fecha_str.charAt(5) == "/"){//dd/mm/yyyy
+            var fecha_arr = fecha_str.split("/");
+            return fecha_arr[2]+"-"+fecha_arr[1]+"-"+fecha_arr[0];
+        }
+        return fecha_str;
+    }
+    function fechaMayor(fechaI, fechaF) {//cual es mayor >0 I mayor   <0 F mayor
+        return (Date.parse(diaAAno(fechaI)) - Date.parse(diaAAno(fechaF)));
+    }
+
+    function validaFechas(){
+        if(fechaMayor($('#filtro_inicial').val().trim(), $('#filtro_final').val().trim()) > 0){
+            $('#filtro_final').addClass("is-invalid");
+            return false;
+        }
+        return true;
+    }
+
+    function submitForm(){
+        var myBtn = $('#submitBtn');
+        var error = false;
+        
+        $("#gpo").removeClass("is-invalid");
+        invalidDatalist("#materia", false);
+        $("#fecha_inicial").removeClass("is-invalid");
+        $("#fecha_falta").removeClass("is-invalid");
+        $("#fecha_cambio").removeClass("is-invalid");
+
+        
+        if($("#tipo").val() == 1){//reposición
+            if($("#fecha_falta").val() == ""){
+                $("#fecha_falta").addClass("is-invalid");
+                error = true;
+            }
+            if($("#fecha_inicial").val() == ""){//fecha reposición
+                $("#fecha_inicial").addClass("is-invalid");
+                error = true;
+            }    
+        }else{
+            if($("#fecha_cambio").val() == ""){
+                $("#fecha_cambio").addClass("is-invalid");
+                error = true;
+            }
+        }
+        if($("#horario").val().trim() == "" || $("#horario").val() === null){
+            invalidDatalist("#horario", true);
+            error = true;
+        }
+        
+        if(myBtn.data("tipo") == 2 ){
+            $('#formaModal').prop("action", "./action/cambio_update.php");
+        }else{
+            $('#formaModal').prop("action", "./action/cambio_insert.php");
+        }
+        if(!error){
+            $("#loadingGroup").show();
+            $("#submitGroup").hide();
+        }
+        return !error;
+    }
+
+    function cambiaTipo(tipo){
+        if (tipo == 1){//reposición
+            $(".repo_block").show();
+            $(".cambio_block").hide();
+            $(".repo_block").find("input[type=text]").attr("required", true);
+            $(".cambio_block").find("input[type=text]").removeAttr("required");
+            $("#hora_nombre").text("Hora reposición *");
+        }else{//Cambio de salón
+            $(".repo_block").hide();
+            $(".cambio_block").show();
+            $(".repo_block").find("input[type=text]").removeAttr("required");
+            $(".cambio_block").find("input[type=text]").attr("required", true);
+            $("#hora_nombre").text("Hora cambio *");
+            var hora = $("#dlMateria ul li.selected").data("hr");
+            var min = $("#dlMateria ul li.selected").data("min");
+            $("#hora_ini").val(hora)
+            $("#min_ini").val(min)
+
+        }
+    }
+    
+    $(document).ready(function(){
+        $(".prof-selected").hide();
+        //fecha de clase
+        $(".date-picker" ).datepicker(datepickerOptions);
+        $(".date-picker" ).datepicker( $.datepicker.regional[ "es" ] );
+
+        //fecha de clase
+        $(".date-picker-filtro" ).datepicker(datepickerOptions_filtro);
+        $(".date-picker-filtro" ).datepicker( $.datepicker.regional[ "es" ] );
+        
+        
+        function creaOpcion(id_horario, dia, hora, min, nombre, gpo, duracion){
+            return '<li data-id="'+id_horario+'" data-dia="'+dia+'" data-hr="'+hora+'" data-min="'+min+'" data-gpo="'+gpo+'" data-duracion="'+duracion+'">'+nombre+'</li>';
+        }
+
+        $('#filtro_final').focus(function(){
+            $("#filtro_final").removeClass("is-invalid");
+        });
+
+        function obtieneProf(pid){
+            return $.ajax({
+                url:  './action/reposicion_profesor_materias.php',
+                type: 'POST', 
+                dataType: 'json',
+                data: { id: pid, },
+                //async: false,
+                success: function(result) {
+                    if(result["error"]!= "" &&  result["error"] !== undefined){
+                        triggerMessage(result["error"], "Error");
+                        $("#modal").modal('hide');
+                        $(".prof-selected").hide();
+                    }else{
+                        $(".prof-selected").show();
+                        $("#dlMateria ul").html("");
+                        for(i=0; i<result["materias"].length; i++){
+                            var html = creaOpcion(result["materias"][i]["horario_id"],
+                                result["materias"][i]["horario_dia"],
+                                result["materias"][i]["horario_hora"],
+                                result["materias"][i]["horario_min"],
+                                result["materias"][i]["materia_nombre"],
+                                result["materias"][i]["grupo"],
+                                result["materias"][i]["duracion"]
+                                );
+                            $("#dlMateria ul").append(html);
+                        }
+                    }
+                },
+                error: function(jqXHR, textStatus, errorThrown ){
+                    triggerMessage(errorThrown, "Error");
+                }
+            });//ajax
+        }
+
+        $(document).on( "click", "#dlProfesor ul li", function(event){//cambia datalist
+            var pid = $(this).data('id');
+            //busca materias del profesor
+            var profCarga = obtieneProf(pid);
+            profCarga.done(function(){
+                $("#dlMateria ul li:first").click();
+            });
+        });
+        
+        
+        //Actualiza días elegibles de calendario
+        $(document).on( "click", "#dlMateria ul li", function(event){//manda al frente de todos
+            _dia_valido = $(this).data('dia');//variable global
+            var grupo = $(this).data("gpo");
+            var duracionMateria = $(this).data("duracion");
+
+            $(".date-picker" ).datepicker(datepickerOptions);
+            var hora = $(this).data("hr");
+            var min = $(this).data("min");
+            $("#hora_ini").val(hora)
+            $("#min_ini").val(min)
+            
+            $("#ciclo").val(parseInt(grupo[6]));
+            $("#bloque").val(parseInt(grupo[8])-1);
+            
+            $('#duracion option').each(function() {
+                if ($(this).data("duracion") === duracionMateria) {
+                    // Selecciona la opción correspondiente en el select de "duracion"
+                    $(this).prop('selected', true);
+                }
+            });
+            $("#duracion_original").text(duracionMateria);
+            $("#hora_original").text(hora+":"+min);
+/*
+            return $.ajax({
+                url:  './action/asistenciasprofesor_select.php',
+                type: 'POST', 
+                dataType: 'json',
+                data: { "id": $("#prof").val(), "hor": $(this).data("id") },
+                //async: false,
+                success: function(result) {
+                    if(result["error"]!= "" &&  result["error"] !== undefined){
+                        triggerMessage(result["error"], "Error");
+                        $('#modal').modal("hide");
+                    }else{
+                        _dias_asistencia = result["asistenciaArr"];
+                        //Cambiar ciclo [6] y bloque [8]
+                        $("#ciclo").val(parseInt(grupo[6]));
+                        $("#bloque").val(parseInt(grupo[8])-1);
+                        
+                        $('#duracion option').each(function() {
+                            if ($(this).data("duracion") === duracionMateria) {
+                                // Selecciona la opción correspondiente en el select de "duracion"
+                                $(this).prop('selected', true);
+                            }
+                        });
+                        $("#duracion_original").text(duracionMateria);
+                        $("#hora_original").text(hora+":"+min);
+                    }
+
+                },
+                error: function(jqXHR, textStatus, errorThrown ){
+                    triggerMessage(errorThrown, "Error");
+                }
+            });//ajax
+  */          
+            
+        });
+        
+        $("#dlTipo ul li").click(function(){//cambia datalist
+            cambiaTipo($(this).data('id'));
+            $(".date-picker" ).datepicker(datepickerOptions);
+        });
+        $("#dlAula ul li").click(function(){//cambia datalist
+            if($(this).data("id") == 1){
+                $("#salon-editar").hide();
+                $("#dlSalon").val("");
+                $("#salon").val("");
+
+            }else{
+                $("#salon-editar").show();
+            }
+            
+        });
+
+        $('#modal_confirm').on('show.bs.modal', function (event) {
+            var button = $(event.relatedTarget); // Button that triggered the modal
+            var id = button.parents("tr").data("id");
+            $("#id_borrar").val(id);
+        });
+        
+        $(".btn-borrar").click(function(){
+            var r_id =  $("#id_borrar").val();
+            $.ajax({
+                url:  './action/cambio_delete.php',
+                type: 'POST', 
+                dataType: 'json',
+                data: { id: r_id},
+                success: function(result) {
+                    if(result["error"]!= "" &&  result["error"] !== undefined){
+                        triggerMessage(result["error"], "Error");
+                    }else{
+                        triggerMessage(result["ok"], "Éxito", "success");
+                        $("#id"+r_id).remove();
+                    }
+                },
+                error: function(jqXHR, textStatus, errorThrown ){
+                    triggerMessage(errorThrown, "Error");
+                }
+            });//ajax
+            $('#modal_confirm').modal("hide");
+        });
+
+        
+        $('#modal').on('show.bs.modal', function (event) {
+            var button = $(event.relatedTarget); // Button that triggered the modal
+            var tipo = button.data('tipo'); // 1 alta, 2 edicion
+            var modal = $(this);
+
+            $("#loadingGroup").hide();
+            $("#submitGroup").show();
+            
+            $("#modal .is-invalid").removeClass("is-invalid");
+            //$(this).find(".form-control:first-child").focus();
+            
+
+            $("#errorBox").collapse('hide');
+            $("#errorBox_text").html("");
+            if(tipo == 1){//alta
+                $("#submitBtn").data('tipo', 1);
+                $("#modalLabel").html("Solicitar cambio");
+                modal.find("input[type=text]").val("");
+                modal.find("#alumnos").val("15");
+                $("#plan").attr("readonly", false);
+                $("#sem").attr("readonly", false);
+                $("#gpo").attr("readonly", false);
+                
+                //$("#prof").attr("readonly", false);
+                disableDatalist("#horario", false);
+                disableDatalist("#tipo", false);
+                if($("#prof").length>0)
+                    disableDatalist("#prof", false);
+                setDatalistFirst("#tipo");
+                setDatalistFirst("#aula");
+                setDatalistFirst("#horario");
+                $("#dlMateria ul li:first").click();
+                
+            }else{//editar
+                $("#submitBtn").data('tipo', 2);
+                $("#modalLabel").html("Editar Reposición");
+                $("#plan").attr("readonly", true);
+                $("#sem").attr("readonly", true);
+                $("#gpo").attr("readonly", true);
+                //$("#materia").attr("readonly", true);
+                disableDatalist("#horario");
+                disableDatalist("#tipo");
+                disableDatalist("#prof");
+                /*if($("#prof").length>0)
+                    disableDatalist("#prof");
+                $("#prof").attr("readonly", true);*/
+                var r_id = $(button).parents("tr").data("id");
+                $("#id").val(r_id);
+                $.ajax({
+                    url:  './action/cambio_select.php',
+                    type: 'POST', 
+                    dataType: 'json',
+                    data: { id: r_id },
+                    async: true,
+                    success: function(result) {
+                        if(result["error"]!= "" &&  result["error"] !== undefined){
+                            triggerMessage(result["error"], "Error");
+                            $("#modal").modal('hide');
+                        }else{
+                            //setDatalist("#prof", result["profesor"]);
+                            setDatalist("#prof", result["profesor"]);
+                            
+                            var profCarga = obtieneProf(result["profesor"]);
+
+                            //$('#salon').val(result["salon"]);
+                            $("#fecha_falta").val(result["fecha_clase"]);
+                            
+                            
+                            $('#comentario').val(result["comentario"]);
+                            $('#alumnos').val(result["alumnos"]);
+                            $('#ciclo').val(result["ciclo"]);
+                            $('#bloque').val(result["bloque"]);
+                            
+                            if(result["tipo"]){
+                                setDatalist("#tipo", 1);
+                                cambiaTipo(1);
+                                $("#fecha_inicial").val(result["fecha_nueva"]);
+                            }else{
+                                setDatalist("#tipo", 2);
+                                cambiaTipo(2);
+                                $("#fecha_cambio").val(result["fecha_nueva"]);
+                            }
+                            _dia_valido = parseInt(result["dia"]);
+                            $(".date-picker" ).datepicker(datepickerOptions);
+                            $("#dlTipo ul li:selected").click();
+                            
+                            
+                            profCarga.done(function(){
+                                setDatalist("#horario", result["horario"]);// No se actualiza TODO
+                                $('#hora_ini').val(result["hora_ini"]);
+                                $('#min_ini').val(result["min_ini"]);
+                            });
+                            setDatalist("#aula", result["aula"]);
+                            modal.modal('show');
+                        }
+                    },
+                    error: function(jqXHR, textStatus, errorThrown ){
+                        triggerMessage(errorThrown, "Error");
+                        $("#modal").modal('hide');
+                        //$('#messageBox')[0].scrollIntoView({ block: "end" });
+                    }
+                });//ajax
+            }
+        });//show
+        
+    });
+
+    $(function() {
+        $('[data-toggle="tooltip"]').tooltip()
+    })
+</script>
+<script src="js/messages.js"></script>
+
+</body>
+
+</html>

+ 8 - 0
class/mailer.php

@@ -5,7 +5,11 @@
 class Mailer{
     private const FROM = "academia@lasalle.mx";
     private const FROM_NAME = "Vicerrectoría Académica";
+<<<<<<< HEAD
     private const FROM_PASS = "D1s3c4nt3S1l1c4#$";//4c4d3m14S3gur4##  Foy25193 D1s3c4nt3S1l1c4#$
+=======
+    private const FROM_PASS = "4c4d3m14S3gur4##";//Foy25193
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
     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;
 
@@ -95,4 +99,8 @@ class Mailer{
         return false;
     }
 
+<<<<<<< HEAD
 }
+=======
+}
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f

+ 257 - 0
días_festivos.php

@@ -1,5 +1,6 @@
 <?php
 require_once 'class/c_login.php';
+<<<<<<< HEAD
 require_once 'include/bd_pdo.php';
 
 $user = Login::get_user();
@@ -17,11 +18,68 @@ if(isset($_GET['facultad'])){
 }else{
     $fac = $user->facultad['facultad_id'];
 }
+=======
+if (!isset($_SESSION['user'])){
+    die(header('Location: index.php'));
+}
+
+//$user = unserialize($_SESSION['user']);
+$user = Login::get_user();
+
+$user->access();
+if ($user->acceso === null && !$user->admin){
+    die(header('Location: index.php'));
+    exit();
+}
+
+
+$periodo_rs = $db->querySingle('SELECT periodo_fecha_inicio, periodo_fecha_fin FROM periodo WHERE periodo_id = :periodo_id', [':periodo_id' => $user->periodo_id]);
+
+
+if(isset($_POST["fecha_ini"]) && $_POST["fecha_ini"]!=""){
+    $fecha_ini_obj = DateTime::createFromFormat('d/m/Y', $_POST["fecha_ini"]);
+}else{
+    $fecha_ini_obj = DateTime::createFromFormat('Y-m-d', $periodo_rs["periodo_fecha_inicio"]);
+}
+if(isset($_POST["fecha_fin"]) && $_POST["fecha_fin"]!=""){
+    $fecha_fin_obj = DateTime::createFromFormat('d/m/Y', $_POST["fecha_fin"]);
+}else{
+    $fecha_fin_obj = DateTime::createFromFormat('Y-m-d', $periodo_rs["periodo_fecha_fin"]);
+}
+
+$fecha_ini = $fecha_ini_obj->format('d/m/Y');
+$fecha_fin = $fecha_fin_obj->format('d/m/Y');
+unset($periodo_rs);
+
+$fs_dias_festivos = $db->query("SELECT  d.diasfestivos_id, d.diasfestivos_dia , p.periodo_id , p.periodo_nombre, extract(dow from diasfestivos_dia) AS dia_id  from diasfestivos d 
+join periodo p on p.periodo_id = any (d.periodos_id) where diasfestivos_dia between :ini and :fin
+order by d.diasfestivos_dia DESC", [":ini"=> $fecha_ini_obj->format('Y-m-d'), ":fin"=>$fecha_fin_obj->format('Y-m-d')]);
+
+
+$dias_arr = array();
+foreach ($fs_dias_festivos as $dia){
+    if(isset($dias_arr[$dia["diasfestivos_id"]])){
+        $dias_arr[$dia["diasfestivos_id"]]["periodos"][] = array("periodo_id"=>$dia["periodo_id"], "periodo_nombre"=>$dia["periodo_nombre"]);
+    }else{
+        $dias_arr[$dia["diasfestivos_id"]] = array("diasfestivos_id"=>$dia["diasfestivos_id"], "diasfestivos_dia"=>$dia["diasfestivos_dia"], "dia_id"=>$dia["dia_id"],
+            "periodos"=>array(array("periodo_id"=>$dia["periodo_id"], "periodo_nombre"=>$dia["periodo_nombre"]))
+        );
+    }
+}
+
+$dias_nombres=array("Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado");
+$write = true;
+
+$fs_periodos = $db->query("SELECT periodo_id, periodo_nombre, periodo_fecha_inicio, periodo_fecha_fin FROM periodo WHERE CURRENT_DATE < periodo_fecha_fin order by id_periodo_sgu");
+
+
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
 ?>
 <!DOCTYPE html>
 <html lang="en">
 
 <head>
+<<<<<<< HEAD
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Días Festivos</title>
@@ -46,14 +104,85 @@ if(isset($_GET['facultad'])){
     $fs_dias_festivos_generales = query("SELECT * FROM fs_diasfestivos(null, null) ORDER BY diasfestivos_dia", null, false);
     ?>
     <main class="content marco">
+=======
+    <title>Días festivos</title>
+
+    <meta charset="utf-8">
+    <meta http-equiv="content-type" content="text/plain; charset=UTF-8" />
+    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
+    <?php
+    include 'import/html_css_files.php';
+    ?>
+    <link rel="stylesheet" href="css/jquery-ui.css">
+    <link rel="stylesheet" href="css/calendar.css">
+    <link rel="stylesheet" href="css/toggle.css" type="text/css">
+    <script src="js/scrollables.js" defer></script>
+    <script>
+        const write = <?= $write ? 'true' : 'false' ?>;
+    </script>
+    <script src="js/jquery.min.js"></script>
+    <script src="js/bootstrap/popper.min.js"></script>
+    <script src="js/bootstrap/bootstrap.min.js"></script>
+    <script src="js/jquery-ui.js"></script>
+    <script src="js/datepicker-es.js"></script>
+    <script src="js/messages.js"></script>
+
+</head>
+
+<body style="display: block;">
+    <?php
+    include('include/constantes.php');
+    include("import/html_header.php");
+    html_header("Días festivos", "Sistema de gestión de checador");
+    ?>
+    <?= "<!-- $user -->" ?>
+    <main class="container content marco content-margin" id="local-app">
+        
+        <section id="message"></section>
+        
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
         <?php if($user->admin){ ?>
         <div class="col-12 text-right">
             <button type="button" class="btn btn-outline-secondary" data-toggle="modal" data-target="#modal" data-tipo="1"><span class="ing-mas ing-fw"></span> Agregar Día Festivo</button>
         </div>
         <?php } ?>
         <div id="message"></div>
+<<<<<<< HEAD
         <!-- Tabla -->
         <?php if($fs_dias_festivos || $fs_dias_festivos_generales){ ?>
+=======
+        <form action="días_festivos.php" method="post" class="">
+            <div class="form-box">
+                <div class="form-group row">
+                    <label for="filter_fecha_ini" class="col-4 col-form-label">Fecha inicial</label>
+                    <div class="col-8 col-sm-4">
+                        <input id="filter_fecha_ini" name="fecha_ini" type="text" class="form-control date-picker" placeholder="dd/mm/aaaa" maxlength="10" required="required" readonly="" value="<?php echo $fecha_ini;?>">
+                        <div class="invalid-feedback">No es una fecha válida.</div>
+                    </div>
+                </div>
+                <div class="form-group row">
+                    <label for="filter_fecha_fin" class="col-4 col-form-label">Fecha final</label>
+                    <div class="col-8 col-sm-4">
+                        <input id="filter_fecha_fin" name="fecha_fin" type="text" class="form-control date-picker" placeholder="dd/mm/aaaa" maxlength="10" required="required" readonly="" value="<?php echo $fecha_fin;?>">
+                        <div class="invalid-feedback">No es una fecha válida.</div>
+                    </div>
+                </div>
+                <div class="col-12 text-center">
+                    <button type="submit" class="btn btn-outline-primary">
+                        <span class="ing-buscar ing-fw"></span>
+                        Filtrar
+                    </button>
+                    <button type="button" class="btn btn-outline-danger btn-reset">
+                        <span class="ing-borrar ing-fw"></span>
+                        Limpiar
+                    </button>
+                </div>
+            </div>
+        </form>
+        <!-- Tabla -->
+        <?php
+        if(count($dias_arr) > 0){ ?>
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
             <div class="row mt-3">
                 <div class="col-12 table-responsive">
                     <table class="table table-sm table-striped table-white">
@@ -61,14 +190,19 @@ if(isset($_GET['facultad'])){
                             <tr>
                                 <th>Día</th>
                                 <th>Periodo</th>
+<<<<<<< HEAD
                                 <th>Nivel</th>
                                 <?php if($user->admin){ ?>
                                 <th>Facultad</th>
+=======
+                                <?php if($user->admin){ ?>
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                                 <th>Acciones</th>
                                 <?php } ?>
                             </tr>
                         </thead>
                         <tbody>
+<<<<<<< HEAD
                             <?php foreach($fs_dias_festivos as $dia){ ?>
                             <tr data-id="<?= $dia['diasfestivos_id'] ?>" id="<?= $dia['diasfestivos_id'] ?>" data-periodo="1">
                                 <td class="text-center"><?php $day =  explode("-", $dia['diasfestivos_dia']);
@@ -79,12 +213,33 @@ if(isset($_GET['facultad'])){
                                 <?php if($user->admin){ ?>
                                 <td class="text-center"><?= $dia['facultad_nombre'] ?></td>
                                 <td class="text-center icono-acciones">
+=======
+                            <?php foreach($dias_arr as $dia){ ?>
+                            <tr data-id="<?= $dia['diasfestivos_id'] ?>" id="<?= $dia['diasfestivos_id'] ?>" data-periodo="1">
+                                <td class="text-center text-nowrap align-middle">
+                                    <?php $day =  explode("-", $dia['diasfestivos_dia']);
+                                        echo $dias_nombres[$dia["dia_id"]]."<br>";
+                                        echo $day[2]."/".$day[1]."/".$day[0];
+                                    ?></td>
+                                <td>
+                                    <ul class="mb-0">
+                                    <?
+                                    foreach($dia["periodos"] as $per){
+                                        echo "<li>".$per['periodo_nombre']."</li>";
+                                    }
+                                    ?>
+                                    </ul>
+                                </td>
+                                <?php if($user->admin){ ?>
+                                <td class="text-center icono-acciones align-middle">
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                                     <a href="#" data-toggle="modal" data-target="#modal" data-tipo="2" title="Editar"><span class="ing-editar ing-fw"></span></a>
                                     <a href="#" data-toggle="modal" data-target="#modal_confirm" title="Borrar"><span class="ing-basura ing-fw"></span></a>
                                 </td>
                                 <?php } ?>
                             </tr>
                             <?php } ?>
+<<<<<<< HEAD
                             <?php foreach($fs_dias_festivos_generales as $dia){ ?>
                             <tr data-id="<?= $dia['diasfestivos_id'] ?>" id="<?= $dia['diasfestivos_id'] ?>" data-periodo="0">
                                 <td class="text-center"><?php $day =  explode("-", $dia['diasfestivos_dia']);
@@ -101,6 +256,9 @@ if(isset($_GET['facultad'])){
                                 <?php } ?>
                             </tr>    
                             <?php } ?>
+=======
+                            
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                         </tbody>
                     </table>
                 </div>
@@ -129,6 +287,7 @@ if(isset($_GET['facultad'])){
                     <form action="" method="post" id="formaModal" onsubmit="return valida_campos()">
                         <input type="hidden" name="id" id="id">
                         <div class="form-box">
+<<<<<<< HEAD
                             <div class="form-group row">
                                 <label for="periodo" class="col-3 col-form-label">Periodo *</label>
                                 <div class="col-8">
@@ -145,6 +304,8 @@ if(isset($_GET['facultad'])){
                                     </div>
                                 </div>
                             </div>
+=======
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                             <div class="form-group row" id="rangoDiv">
                                 <label for="rango" class="col-3 col-form-label">Rango</label>
                                 <div class="col-8">
@@ -157,13 +318,38 @@ if(isset($_GET['facultad'])){
                                     <input id="diaFestivo" name="diaFestivo" type="text" class="form-control date-picker" placeholder="dd/mm/aaaa" maxlength="10" required="required" readonly="">
                                 </div>
                                 <div class="col-1 diaFestivoRango">
+<<<<<<< HEAD
                                     -
+=======
+                                    <span class="ing-menos pt-2"></span>
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                                 </div>
                                 <div class="col-4 diaFestivoRango" id="diaFestivoRango">
                                     <input id="diaFestivoFin" name="diaFestivoFin" type="text" class="form-control date-picker" placeholder="dd/mm/aaaa" maxlength="10" required="required" readonly="">
                                 </div>
                                 <div class="invalid-feedback">Debe seleccionar una fecha</div>
                             </div>
+<<<<<<< HEAD
+=======
+
+                            <div class="form-group row" id="periodos">
+                                <label for="periodos" class="col-3 col-form-label">Periodos</label>
+                                <div class="col-9" style="overflow-y:auto; overflow-x:none; max-height:220px; font-size:80%">
+                                    <?php
+                                    foreach($fs_periodos as $per){
+                                    ?>
+                                        <div class="form-check form-check-inline" data-fechaini = "<?php echo $per["periodo_fecha_inicio"];?>" data-fechafin = "<?php echo $per["periodo_fecha_fin"];?>">
+                                            <input class="form-check-input radio-lg " type="checkbox" id="check<?php echo $per["periodo_id"]?>" name="periodo[]" value="<?php echo $per["periodo_id"]?>">
+                                            <label for="check<?php echo $per["periodo_id"]?>" class="col-form-label"><?php echo $per["periodo_nombre"]?></label> 
+                                        </div>
+                                    <?php 
+                                    }
+                                    ?>
+                                </div>
+                                
+                            </div>
+
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                             <div class="form-group row">
                                 <div class="offset-4 col-8">
                                     <button type="submit" class="btn btn-outline-primary" id="submitBtn" data-tipo="1">
@@ -181,7 +367,11 @@ if(isset($_GET['facultad'])){
         </div>
     </div>
 
+<<<<<<< HEAD
     <div class="modal fade" id="modal_confirm" tabindex="-1" role="dialog" aria-labelledby="modal" aria-hidden="true">
+=======
+    <div class="modal fade" id="modal_confirm" tabindex="-1" role="dialog" aria-labelledby="modal_confirm" aria-hidden="true">
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
         <div class="modal-dialog modal-dialog-centered" role="document">
             <div class="modal-content">
                 <div class="modal-body">
@@ -203,13 +393,27 @@ if(isset($_GET['facultad'])){
     <script src="js/jquery.min.js"></script>
     <script src="js/jquery-ui.js"></script>
     <script src="js/bootstrap/bootstrap.min.js"></script>
+<<<<<<< HEAD
     <script src="js/datalist.js"></script>
+=======
+    
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
     <script src="js/datepicker-es.js"></script>
     <script src="js/toggle.js"></script>
     <?php
         require_once 'js/messages.php';
     ?>
     <script>
+<<<<<<< HEAD
+=======
+        $(document).on( "click", ".btn-reset", function(event){
+            var forma = $(this).parents("form");
+            forma.find("input[type=text]").val("");
+            forma.submit();
+        });
+
+
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
         $(document).ready(function(){
             $('.diaFestivoRango').hide();
         });
@@ -251,23 +455,60 @@ if(isset($_GET['facultad'])){
             changeMonth: true,
         });
 
+<<<<<<< HEAD
     <?php if(!$fs_dias_festivos && !$fs_dias_festivos_generales){ ?>
         triggerMessage("No se encontraron días festivos", "Error");
     <?php } ?>
 
+=======
+    <?php if(count($dias_arr) == 0){ ?>
+        triggerMessage("No se encontraron días festivos", "Error");
+    <?php } ?>
+
+        function actualizaPeriodos(fechaOriginal){
+            var partesFecha = fechaOriginal.split('/');
+            var fechaFestivo = partesFecha[2]+"-"+partesFecha[1]+"-"+partesFecha[0];
+
+            $.each($('#periodos .form-check'), function(){
+                if(fechaFestivo>= $(this).data("fechaini") && fechaFestivo<= $(this).data("fechafin")){
+                    $(this).show();
+                }else{
+                    $(this).find("input").prop("checked", false);
+                    $(this).hide();
+                }
+            });
+        }
+
+        //Cambio de fecha valida periodos activos para esa fecha
+        $('#modal .date-picker').change(function(){
+            actualizaPeriodos($(this).val());
+        });
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
         $('#modal').on('show.bs.modal', function (event){
             var button = $(event.relatedTarget);
             var tipo = button.data('tipo');
             var modal = $(this);
+<<<<<<< HEAD
+=======
+            $("#formaModal .text-danger").removeClass("text-danger");
+            $("#diaFestivoFin").removeClass("is-invalid");
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
             if(tipo==1){//agregar
                 $('#modalLabel').html("Agregar Día Festivo");
                 $('#submitBtn').data('tipo', 1);
                 $('#diaFestivo').datepicker("setDate", today);
                 $('#diaFestivoFin').datepicker("setDate", today);
+<<<<<<< HEAD
                 setDatalistFirst("#periodo");
                 $('#rangoDiv').show();
                 $('#dia').removeClass('col-9');
                 $('#dia').addClass('col-4');
+=======
+                $('#rangoDiv').show();
+                $('#dia').removeClass('col-9');
+                $('#dia').addClass('col-4');
+                actualizaPeriodos($("#diaFestivo").val());
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
             }
             else{
                 $('#modalLabel').html("Editar Día Festivo");
@@ -285,11 +526,15 @@ if(isset($_GET['facultad'])){
                     success:function(result){
                         console.log(result);
                         $('#id').val(result['diasfestivos_id']);
+<<<<<<< HEAD
                         if(!result['periodo_id']){
                             setDatalist('#periodo', 0);
                         }else{
                             setDatalist('#periodo', result['periodo_id']);
                         }
+=======
+                        
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                         var date = new Date(result['diasfestivos_dia']);
                         date.setDate(date.getDate() + 1);
                         $('#diaFestivo').datepicker("setDate", date);
@@ -301,6 +546,11 @@ if(isset($_GET['facultad'])){
 
         function valida_campos(){
             var error=false;
+<<<<<<< HEAD
+=======
+            $("#modal .text-danger").removeClass("text-danger");
+            $("#diaFestivoFin").removeClass("is-invalid");
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
             if($("#diaFestivo").val()==""){
                 $("#diaFestivo").addClass("is-invalid");
                 error=true;
@@ -316,6 +566,13 @@ if(isset($_GET['facultad'])){
                 $('#diaFestivoFin').addClass("is-invalid");
                 error=true;
             }
+<<<<<<< HEAD
+=======
+            if($("#modal .form-check-input:checked").length<=0){
+                $("#modal .form-check-input").siblings().addClass("text-danger");
+                error=true;
+            }
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
             if(error){
                 return false;
             }else{

+ 65 - 0
export/control.php

@@ -0,0 +1,65 @@
+<button onclick="getExcel()">
+    Get excel
+</button>
+<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
+<script>
+    async function getExcel() {
+        const res = await fetch('supervisor_excel.php', {
+            method: 'POST',
+            headers: {
+                'Content-Type': 'application/json'
+            },
+            body: JSON.stringify([
+                {
+                    "profesor_id": 1089,
+                    "estado_supervisor_id": 1,
+                    "horario_id": 3538,
+                    "registro_id": 1,
+                    "registro_fecha": null,
+                    "registro_retardo": null,
+                    "registro_justificada": null,
+                    "registro_fecha_ideal": "2023-08-03",
+                    "comentario": "Hola mundo",
+                    "registro_fecha_supervisor": "2023-08-03 12:21:38.336147",
+                    "supervisor_id": 6,
+                    "justificacion": null,
+                    "fecha_justificacion": null,
+                    "horario_hora": "12:00:00",
+                    "horario_fin": "13:30:00",
+                    "horario_grupo": "MG 45030102",
+                    "horario_dia": 4,
+                    "dia": "jueves",
+                    "duracion_id": 2,
+                    "duracion": "01:30:00",
+                    "carrera_id": 439,
+                    "carrera": "LICENCIATURA EN INGENIERÍA ELECTRÓNICA PARA SISTEMAS INTELIGENTES",
+                    "facultad_id": 28,
+                    "facultad": "FACULTAD DE INGENIERÍA",
+                    "periodo_id": null,
+                    "periodo": "LICENCIATURA: agosto - noviembre 2023",
+                    "materia_id": 191,
+                    "materia": "Dinámica",
+                    "nivel_id": 1,
+                    "nivel": "Licenciatura",
+                    "salon_id": 1245,
+                    "salon": "ING MM 208",
+                    "nombre": "Asistencia",
+                    "estado_color": "success",
+                    "estado_icon": "ing-autorizar",
+                    "profesor_nombre": "ISRAEL WOOD CANO",
+                    "profesor_clave": "008999",
+                    "profesor_correo": "israel.wood@lasallistas.org.mx",
+                    "profesor_grado": null,
+                    "usuario_id": 6,
+                    "usuario_nombre": "Francisco Javier  Garrido Alfaro",
+                    "usuario_correo": null,
+                    "usuario_admin": false,
+                    "usuario_clave": "ad011538",
+                    "rol_id": 7
+                }
+            ])
+        });
+        const blob = await res.blob();
+        saveAs(blob, 'excel.xlsx');
+    }
+</script>

+ 142 - 0
export/faltas_excel.php

@@ -0,0 +1,142 @@
+<?php
+
+$fecha = date('d_m_Y');
+header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
+header("Content-Disposition: attachment;filename=horario_$fecha.xlsx");
+header("Cache-Control: max-age=0");
+
+require_once "../vendor/autoload.php";
+
+use PhpOffice\PhpSpreadsheet\Spreadsheet;
+use PhpOffice\PhpSpreadsheet\Style\Border;
+use PhpOffice\PhpSpreadsheet\Style\Color;
+use PhpOffice\PhpSpreadsheet\Style\Fill;
+use PhpOffice\PhpSpreadsheet\Style\Alignment;
+use PhpOffice\PhpSpreadsheet\IOFactory;
+
+$spreadsheet = new Spreadsheet();
+$sheet = $spreadsheet->getActiveSheet();
+
+// Image settings
+$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
+$drawing->setName('La Salle')
+    ->setDescription('La Salle')
+    ->setPath('../imagenes/logo.png')
+    ->setCoordinates('B1')
+    ->setHeight(100)
+    ->setOffsetX(10)
+    ->setWorksheet($spreadsheet->getActiveSheet());
+
+$json = file_get_contents('php://input');
+$data = json_decode($json, true);
+
+empty($data) and die(json_encode(['error' => 'No se recibieron datos', 'data' => $data]));
+
+$data_excel = array(
+    "CLAVE" => 'profesor_clave',
+    "PROFESOR" => 'profesor_nombre',
+    "CORREO" => 'profesor_correo',
+    "FALTAS" => 'faltas',
+    "TOTAL" => 'total',
+    "PORCENTAJE" => 'porcentaje',
+); // Same as before
+
+
+
+const ROW = 6;
+// Merge cells from A1 to C+ ROW
+$sheet->mergeCells('A1:B' . (ROW - 1));
+// Merge cells from D1 to size of $data_excel + 1
+$sheet->mergeCells('C1:' . chr(65 + count($data_excel) - 1) . (ROW - 1));
+
+// Set the title in D1 Sistema de Auditoría de Asistencia
+$sheet->setCellValue('C1', 'Sistema de Auditoría de Asistencia');
+$sheet->getStyle('C1')->applyFromArray([
+    'font' => [
+        'bold' => true,
+        'size' => 30,
+        'name' => 'Indivisa Text Sans',
+        'color' => ['argb' => '001d68'],
+    ],
+    'alignment' => [
+        'vertical' => Alignment::VERTICAL_CENTER,
+    ],
+]);
+
+
+$lastColumnLetter = chr(65 + count($data_excel) - 1);
+$headers_range = 'A' . ROW . ':' . $lastColumnLetter . ROW;
+
+$keys = array_keys($data_excel);
+array_walk($keys, function ($key, $index) use ($sheet) {
+    $sheet->setCellValue(chr(65 + $index) . ROW, $key);
+});
+// Apply the header styles
+$sheet->getStyle($headers_range)->applyFromArray([
+    'font' => [
+        'bold' => true,
+        'size' => 15,
+        'name' => 'Indivisa Text Sans',
+        'color' => ['argb' => Color::COLOR_WHITE],
+    ],
+    'alignment' => [
+        'horizontal' => Alignment::HORIZONTAL_CENTER,
+        'vertical' => Alignment::VERTICAL_CENTER,
+    ],
+    'fill' => [
+        'fillType' => Fill::FILL_SOLID,
+        'startColor' => ['argb' => '001d68'],
+    ]
+]);
+
+// set filters
+$sheet->setAutoFilter($headers_range);
+
+
+
+// Styles that are common for all rows can be set outside the loop
+
+const DEFAULT_FONT = [
+    'size' => 12,
+    'name' => 'Indivisa Text Sans',
+    'color' => ['argb' => '001d68']
+];
+
+const DEFAULT_STYLE = [
+    'alignment' => [
+        'vertical' => Alignment::VERTICAL_CENTER,
+        'wrapText' => true,
+    ],
+    'font' => DEFAULT_FONT,
+    'borders' => [
+        'outline' => [
+            'borderStyle' => Border::BORDER_THIN,
+            'color' => ['argb' => Color::COLOR_WHITE],
+        ]
+    ]
+];
+
+foreach ($data as $index => $registro) {
+    $pair = $index % 2 == 0;
+    $cellRange = 'A' . (ROW + $index + 1) . ':' . $lastColumnLetter . (ROW + $index + 1);
+    $styleArray = DEFAULT_STYLE;
+    $styleArray['fill'] = [
+        'fillType' => Fill::FILL_SOLID,
+        'startColor' => ['argb' => $pair ? 'd4d9dd' : 'f6f7f8'],
+    ];
+
+    $sheet->getStyle($cellRange)->applyFromArray($styleArray);
+    $values = array_values($data_excel);
+    array_walk($values, function ($row, $column_index) use ($sheet, $index, $registro) {
+        $cellLocation = chr(65 + $column_index) . (ROW + $index + 1);
+        $sheet->setCellValue($cellLocation, $registro[$row]);
+    });
+}
+
+
+foreach ($sheet->getColumnIterator() as $column) {
+    $sheet->getColumnDimension($column->getColumnIndex())->setAutoSize(true);
+}
+
+$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
+$writer->save('php://output');

+ 139 - 0
export/horario_excel.php

@@ -0,0 +1,139 @@
+<?php
+$ruta = "../";
+require_once "../vendor/autoload.php";
+require_once "../class/c_login.php";
+
+
+use PhpOffice\PhpSpreadsheet\Spreadsheet;
+
+$spreadsheet = new Spreadsheet();
+$sheet = $spreadsheet->getActiveSheet();
+
+//crea imagen 
+$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
+$drawing->setName('La Salle');
+$drawing->setDescription('La Salle');
+$drawing->setPath('../imagenes/logo.png'); // put your path and image here
+$drawing->setCoordinates('A1');
+$drawing->setHeight(100);
+$drawing->setOffsetX(10);
+//agrega imagen
+$drawing->setWorksheet($spreadsheet->getActiveSheet());
+
+
+extract($_POST);
+$row = 6;
+$sábado = $sábado == 'true';
+$sheet->setCellValue("A$row", 'Hora');
+$sheet->setCellValue("B$row", 'Lunes');
+$sheet->setCellValue("C$row", 'Martes');
+$sheet->setCellValue("D$row", 'Miércoles');
+$sheet->setCellValue("E$row", 'Jueves');
+$sheet->setCellValue("F$row", 'Viernes');
+if ($sábado)
+    $sheet->setCellValue("G$row", 'Sábado');
+
+// to this row set bold, font size 12 and Indivisa Sans, and center the text, bg color to #101097, color to white,
+$until = $sábado ? 'G' : 'F';
+
+$sheet->getStyle("A$row:$until$row")->getFont()->setBold(true);
+$sheet->getStyle("A$row:$until$row")->getFont()->setSize(15);
+$sheet->getStyle("A$row:$until$row")->getFont()->setName('Indivisa Display Sans');
+$sheet->getStyle("A$row:$until$row")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
+$sheet->getStyle("A$row:$until$row")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
+$sheet->getStyle("A$row:$until$row")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID);
+$sheet->getStyle("A$row:$until$row")->getFill()->getStartColor()->setARGB('001d68');
+$sheet->getStyle("A$row:$until$row")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
+
+# the first column is the hour of the day merged with 4 rows each
+$row++;
+foreach (range($min, $max) as $hour) {
+    $sheet->setCellValue("A$row", "$hour:00");
+    $sheet->mergeCells("A$row:A" . ($row + 3));
+
+    for ($i = 0; $i < 4; $i++)
+        $sheet->getRowDimension($row + $i)->setRowHeight(25);
+
+
+    // align to center
+    $sheet->getStyle("A$row")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
+    $sheet->getStyle("A$row")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
+
+    $sheet->getStyle("A$row")->getFont()->setBold(true);
+    $sheet->getStyle("A$row")->getFont()->setName('Indivisa Text Sans');
+    $sheet->getStyle("A$row")->getFont()->setSize(12);
+
+
+    $row += 4;
+}
+
+
+# Size columns to 30
+foreach (range('A', 'G') as $column) {
+    if ($column == 'G' && !$sábado)
+        continue;
+    $sheet->getColumnDimension($column)->setWidth(($column == 'A' ? 10 : 30));
+}
+
+# foreach horarios
+$row = 7;
+$días = ['lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'];
+$lista_minutos = ['00', '15', '30', '45'];
+foreach (json_decode($horarios) as $horario) {
+    [$hora, $minutos] = array_map(fn($x) => intval($x), explode(':', $horario->hora));
+    $rowHora = $row + ($hora - $min) * 4;
+    $rowHora += array_search($minutos, $lista_minutos);
+
+    $colHora = array_search($horario->dia, $días) + 2;
+    $content = new \PhpOffice\PhpSpreadsheet\RichText\RichText();
+    $content->createText("$horario->hora");
+    // $content = "$horario->hora $horario->materia\n$horario->salon\n$horario->profesor";
+    $content->createTextRun(" $horario->materia\n")->getFont()->setBold(true)->setName('Indivisa Text Sans')->setSize(12);
+    $content->createTextRun("Salón: $horario->salon\n")->getFont()->setBold(true);
+    foreach ($horario->profesores as $profesor) $content->createTextRun("🎓 $profesor->profesor\n")->getFont()->setBold(true);
+    // APPLY THE FONT FAMILY
+    $sheet->setCellValueByColumnAndRow($colHora, $rowHora, $content);
+
+    $sheet->getStyleByColumnAndRow($colHora, $rowHora)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
+    $sheet->getStyleByColumnAndRow($colHora, $rowHora)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
+
+    // merge cells
+    $sheet->mergeCellsByColumnAndRow($colHora, $rowHora, $colHora, $rowHora + $horario->bloques - 1);
+    // set border white
+    $sheet->getStyleByColumnAndRow($colHora, $rowHora)->getBorders()->getOutline()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
+    $sheet->getStyleByColumnAndRow($colHora, $rowHora)->getBorders()->getOutline()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
+    // set bg color d4d9dd
+    $sheet->getStyleByColumnAndRow($colHora, $rowHora)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID);
+    $sheet->getStyleByColumnAndRow($colHora, $rowHora)->getFill()->getStartColor()->setARGB('d4d9dd');
+
+    // set font size 12
+    $sheet->getStyleByColumnAndRow($colHora, $rowHora)->getFont()->setSize(12);
+    // set font name Indivisa Text Sans
+    $sheet->getStyleByColumnAndRow($colHora, $rowHora)->getFont()->setName('Indivisa Text Sans');
+    // set font color 001d68z
+    $sheet->getStyleByColumnAndRow($colHora, $rowHora)->getFont()->getColor()->setARGB('001d68');
+
+    // wrap text
+    $sheet->getStyleByColumnAndRow($colHora, $rowHora)->getAlignment()->setWrapText(true);
+    // border white
+    $sheet->getStyleByColumnAndRow($colHora, $rowHora)->getBorders()->getOutline()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
+    $sheet->getStyleByColumnAndRow($colHora, $rowHora)->getBorders()->getOutline()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
+}
+
+
+#$writer = new Xlsx($spreadsheet);
+$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
+# $writer->save('asistencias.xlsx');
+
+// download
+header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
+header('Content-Disposition: attachment;filename="asistencias.xlsx"');
+header('Cache-Control: max-age=0');
+
+// cache expires in 60 seconds (1 minute)
+header('Expires: mon 26 jul 1997 05:00:00 gmt');
+header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
+header('Cache-Control: cache, must-revalidate');
+header('Pragma: public');
+
+$writer->save('php://output');

+ 179 - 0
export/supervisor_excel.php

@@ -0,0 +1,179 @@
+<?php
+
+$fecha = date('d_m_Y');
+header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
+header("Content-Disposition: attachment;filename=horario_$fecha.xlsx");
+header("Cache-Control: max-age=0");
+
+require_once "../vendor/autoload.php";
+
+use PhpOffice\PhpSpreadsheet\Spreadsheet;
+use PhpOffice\PhpSpreadsheet\Style\Border;
+use PhpOffice\PhpSpreadsheet\Style\Color;
+use PhpOffice\PhpSpreadsheet\Style\Fill;
+use PhpOffice\PhpSpreadsheet\Style\Alignment;
+use PhpOffice\PhpSpreadsheet\IOFactory;
+
+$spreadsheet = new Spreadsheet();
+$sheet = $spreadsheet->getActiveSheet();
+
+// Image settings
+$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
+$drawing->setName('La Salle')
+    ->setDescription('La Salle')
+    ->setPath('../imagenes/logo.png')
+    ->setCoordinates('B1')
+    ->setHeight(100)
+    ->setOffsetX(10)
+    ->setWorksheet($spreadsheet->getActiveSheet());
+
+$json = file_get_contents('php://input');
+$data = json_decode($json, true);
+
+empty($data) and die(json_encode(['error' => 'No se recibieron datos', 'data' => $data]));
+
+$data_excel = array(
+    "FECHA" => 'registro_fecha_ideal',
+    "CLAVE" => 'profesor_clave',
+    "PROFESOR" => 'profesor_nombre',
+    "CORREO" => 'profesor_correo',
+    "FACULTAD" => 'facultad',
+    "MATERIA" => 'materia',
+    "CARRERA / PROGRAMA" => 'carrera',
+    "GRUPO" => 'horario_grupo',
+    "HORARIO" => 'horario_hora_completa',
+    "SALÓN" => 'salon',
+    "REGISTRO PROFESOR" => 'asistencia',
+    "HORA DE REGISTRO" => 'registro_fecha',
+    "NOMBRE SUPERVISOR" => 'usuario_nombre',
+    "REGISTRO SUPERVISOR" => 'nombre',
+    "HORA DE SUPERVISIÓN" => 'registro_fecha_supervisor',
+    "OBSERVACIONES" => 'comentario',
+    "JUSTIFICACIÓN" => 'justificacion',
+); // Same as before
+
+
+
+const ROW = 6;
+// Merge cells from A1 to C+ ROW
+$sheet->mergeCells('A1:C' . (ROW - 1));
+// Merge cells from D1 to size of $data_excel + 1
+$sheet->mergeCells('D1:' . chr(65 + count($data_excel) - 1) . (ROW - 1));
+
+// Set the title in D1 Sistema de Auditoría de Asistencia
+$sheet->setCellValue('D1', 'Sistema de Auditoría de Asistencia');
+$sheet->getStyle('D1')->applyFromArray([
+    'font' => [
+        'bold' => true,
+        'size' => 30,
+        'name' => 'Indivisa Text Sans',
+        'color' => ['argb' => '001d68'],
+    ],
+    'alignment' => [
+        'vertical' => Alignment::VERTICAL_CENTER,
+    ],
+]);
+
+
+$lastColumnLetter = chr(65 + count($data_excel) - 1);
+$headers_range = 'A' . ROW . ':' . $lastColumnLetter . ROW;
+
+$keys = array_keys($data_excel);
+array_walk($keys, function ($key, $index) use ($sheet) {
+    $sheet->setCellValue(chr(65 + $index) . ROW, $key);
+});
+// Apply the header styles
+$sheet->getStyle($headers_range)->applyFromArray([
+    'font' => [
+        'bold' => true,
+        'size' => 15,
+        'name' => 'Indivisa Text Sans',
+        'color' => ['argb' => Color::COLOR_WHITE],
+    ],
+    'alignment' => [
+        'horizontal' => Alignment::HORIZONTAL_CENTER,
+        'vertical' => Alignment::VERTICAL_CENTER,
+    ],
+    'fill' => [
+        'fillType' => Fill::FILL_SOLID,
+        'startColor' => ['argb' => '001d68'],
+    ]
+]);
+
+// set filters
+$sheet->setAutoFilter($headers_range);
+
+
+
+// Styles that are common for all rows can be set outside the loop
+
+const DEFAULT_FONT = [
+    'size' => 12,
+    'name' => 'Indivisa Text Sans',
+    'color' => ['argb' => '001d68']
+];
+
+const DEFAULT_STYLE = [
+    'alignment' => [
+        'vertical' => Alignment::VERTICAL_CENTER,
+        'wrapText' => true,
+    ],
+    'font' => DEFAULT_FONT,
+    'borders' => [
+        'outline' => [
+            'borderStyle' => Border::BORDER_THIN,
+            'color' => ['argb' => Color::COLOR_WHITE],
+        ]
+    ]
+];
+
+function getFormattedValue($key, $registro)
+{
+    return match ($key) {
+        'asistencia' => is_null($registro['registro_fecha'])
+        ? "Sin registro"
+        : ($registro['registro_retardo'] ? "Retardo " : "Asistencia "),
+        'registro_fecha', 'registro_fecha_supervisor' =>
+        is_null($registro[$key])
+        ? 'Sin registro'
+        : date('H:i', strtotime($registro[$key])),
+        'nombre' => $registro[$key] ?? "Sin registro",
+        'horario_hora_completa' => "{$registro['horario_hora']} - {$registro['horario_fin']}",
+        'usuario_nombre', 'justificacion', 'comentario' =>
+        $registro[$key] ?? "Sin registro",
+        default => $registro[$key]
+    };
+}
+
+foreach ($data as $index => $registro) {
+    $pair = $index % 2 == 0;
+    $cellRange = 'A' . (ROW + $index + 1) . ':' . $lastColumnLetter . (ROW + $index + 1);
+    $styleArray = DEFAULT_STYLE;
+    $styleArray['fill'] = [
+        'fillType' => Fill::FILL_SOLID,
+        'startColor' => ['argb' => $pair ? 'd4d9dd' : 'f6f7f8'],
+    ];
+
+    $sheet->getStyle($cellRange)->applyFromArray($styleArray);
+
+    $values = array_values($data_excel);
+
+    array_walk($values, function ($row, $column_index) use ($sheet, $index, $registro) {
+        $value = getFormattedValue($row, $registro);
+        $cellLocation = chr(65 + $column_index) . (ROW + $index + 1);
+
+        $sheet->setCellValue($cellLocation, $value);
+
+        if ($value == "Sin registro") {
+            $sheet->getStyle($cellLocation)->applyFromArray(['font' => ['color' => ['argb' => 'ea0029']]]);
+        }
+    });
+}
+
+
+foreach ($sheet->getColumnIterator() as $column) {
+    $sheet->getColumnDimension($column->getColumnIndex())->setAutoSize(true);
+}
+
+$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
+$writer->save('php://output');

+ 4 - 0
include/bd_pdo_rest.php

@@ -1,5 +1,9 @@
 <?php
+<<<<<<< HEAD
 require_once "/saa_dsk/www/vendor/autoload.php";
+=======
+require_once "/usr/share/nginx/html/paad/vendor/autoload.php";
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
 $dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
 $dotenv->load();
 use \SeinopSys\PostgresDb;

+ 8 - 0
include/db/postgrest.conf

@@ -2,7 +2,11 @@
 
 # The standard connection URI format, documented at
 # https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING
+<<<<<<< HEAD
 db-uri       = "postgres://postgres:4ud1t0rf4lt4$$@localhost:5432/paad"
+=======
+db-uri       = "postgres://postgres:4ud1t0rf4lt4$$@localhost:5432/paad_pruebas"
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
 
 # The database role to use when no client authentication is provided.
 # Should differ from authenticator
@@ -17,4 +21,8 @@ jwt-secret-is-base64 = false
 server-port = 3000
 
 # the location root is /api 
+<<<<<<< HEAD
 server-host = "*"
+=======
+server-host = "*"
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f

+ 8 - 0
js/auditoría.js

@@ -99,8 +99,13 @@ const store = reactive({
         },
         printEstados() {
             if (store.filters.estados.length > 0)
+<<<<<<< HEAD
                 document.querySelector('#estados').innerHTML = store.filters.estados.map((estado) => `<span class="mx-2 badge badge-${store.estados.getEstado(estado).estado_color}">
                     <i class="${store.estados.getEstado(estado).estado_icon}"></i> ${store.estados.getEstado(estado).nombre}
+=======
+                document.querySelector('#estados').innerHTML = store.filters.estados.map((estado) => `<span class="mx-2 badge badge-${store.estados.getEstado(estado).estado_color}">
+                    <i class="${store.estados.getEstado(estado).estado_icon}"></i> ${store.estados.getEstado(estado).nombre}
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                 </span>`).join('');
             else
                 document.querySelector('#estados').innerHTML = `Todos los registros`;
@@ -208,7 +213,10 @@ const store = reactive({
                 params['fecha_inicio'] = fecha_inicio;
             if (fecha_fin)
                 params['fecha_fin'] = fecha_fin;
+<<<<<<< HEAD
             params['periodo_id'] = store.filters.todos_los_periodos ? 1 : 0;
+=======
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
             const paramsUrl = new URLSearchParams(params).toString();
             try {
                 const res = await fetch(`action/action_auditoria.php?${paramsUrl}`, {

+ 12 - 0
js/scrollables.js

@@ -29,3 +29,15 @@ const check = () => {
 }
 
 ['scroll', 'resize'].forEach(e => window.addEventListener(e, check))
+<<<<<<< HEAD
+=======
+
+document.addEventListener('DOMContentLoaded', function () {
+    const links = document.querySelectorAll('a');
+    links.forEach(function (link) {
+        link.addEventListener('click', function (event) {
+            // event.preventDefault();
+        });
+    });
+});
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f

+ 391 - 0
reposiciones_autorizar.php

@@ -87,7 +87,13 @@ if($user->periodo_id!= ""){
     $repEdo_rs = $db->query('SELECT * FROM fs_estado_reposicion' );
 
     $repoParams = array();
+<<<<<<< HEAD
     $query = "";
+=======
+    $asigParams = array();
+    $query = "";
+
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
     if($user->rol["rol_id"] == 9){//es coordinador
         $query .= ":facultad, ";
         $repoParams[":facultad"] = $user->facultad["facultad_id"];
@@ -101,7 +107,12 @@ if($user->periodo_id!= ""){
     }else{
         $query .= "NULL,";
     }
+<<<<<<< HEAD
     $query .= ":f_ini, :f_fin, :edo, ";
+=======
+    $query .= ":f_ini, :f_fin, ";
+    $queryAsig = ":f_ini, :f_fin,";
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
 
 
     $date = DateTime::createFromFormat('d/m/Y', $fecha_ini);
@@ -112,6 +123,12 @@ if($user->periodo_id!= ""){
     $repoParams[":f_ini"] = $fecha_ini_db;
     $repoParams[":f_fin"] = $fecha_fin_db;
     $repoParams[":edo"] = 1;//se sobreescribe
+<<<<<<< HEAD
+=======
+
+    $asigParams[":f_ini"] = $fecha_ini_db;
+    $asigParams[":f_fin"] = $fecha_fin_db;
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
 }
 ?>
 <!DOCTYPE html>
@@ -190,8 +207,19 @@ if($user->periodo_id!= ""){
                 <button type="submit" class="btn btn-outline-primary mr-2" id="btn-buscar"><span class="ing-buscar ing-fw"></span> Buscar</button>
                 <button type="button" class="btn btn-outline-danger" onclick="window.location.href = window.location.href"><span class="ing-borrar ing-fw"></span> Limpiar</button>
             </div>
+<<<<<<< HEAD
         </form>
 
+=======
+
+            <p class="text-right">
+                <button class="btn btn-secondary" id="exportar"><span class="ing-descargar"></span>Descargar xls</button>
+            </p>
+        </form>
+
+        
+
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
         <ul class="nav nav-tabs d-print-none mb-4" id="myTab" role="tablist">
             <li class="nav-item">
                 <a class="nav-link" id="tab1-tab" data-toggle="tab" href="#tab1" role="tab" aria-controls="calendario" aria-selected="true">Nuevas reposiciones</a>
@@ -212,6 +240,7 @@ if($user->periodo_id!= ""){
             foreach($repEdo_rs as $redo){ ?>
             <div class="tab-pane fade" id="tab<?php echo $i;?>" role="tabpanel" aria-labelledby="tab<?php echo $i;?>-tab">
                 <?php
+<<<<<<< HEAD
                 $repoParams[":edo"]=$redo["estado_reposicion_id"];
                 if($user->rol["rol_id"] == 7){//es supervisor
                     $repoParams[":sup"] = $user->user["id"];
@@ -222,6 +251,54 @@ if($user->periodo_id!= ""){
                 ?>
                 
                 <h4 class="mb-4" <?php echo "style='color:".$redo["estado_color"]."'>".$redo["estado_nombre"]; ?> </h4>
+=======
+
+                $tablaArr = [];
+
+                $repoParams[":edo"]=$redo["estado_reposicion_id"];
+                $asigParams[":edo"]=$redo["estado_reposicion_id"];
+                if($user->rol["rol_id"] == 7){//es supervisor
+                    $repoParams[":sup"] = $user->user["id"];
+                    $reposiciones_rs = $db->query('SELECT * FROM fs_reposicion_solicitud(NULL, '.$query.':edo, 0, NULL, :sup) ', $repoParams );
+                }else{
+                    $reposiciones_rs = $db->query('SELECT * FROM fs_reposicion_solicitud(NULL, '.$query.':edo, 0, NULL) ', $repoParams );
+                }
+                foreach($reposiciones_rs as $repo){
+                    $tablaArr[] = array("id"=>$repo["reposicion_solicitud_id"], "estado"=>$repo["estado_reposicion_id"], "tipo"=>($repo["es_reposicion"]==true?1:2),
+                        "profesor_clave"=>$repo["profesor_clave"], "profesor_nombre"=>$repo["profesor_nombre"], "materia_nombre"=>$repo["materia_nombre"], "horario_grupo"=>$repo["horario_grupo"],
+                        "fecha_falta"=>$repo["fecha_clase"], "fecha_nueva"=>$repo["fecha_nueva"], "hora_original"=> $repo["horario_hora"], "hora_nueva"=>$repo["hora_nueva"], "hora_nueva_fin"=>$repo["hora_nueva_fin"],
+                        "salon_id"=>$repo["salon_id"], "salon_array"=>$repo["salon_array"]);
+                }
+                
+                if($user->rol["rol_id"] == 7){//es supervisor
+                    $asigParams[":sup"] = $user->user["id"];
+                    $asignaciones_rs = $db->query('SELECT * FROM fs_asignacion_solicitud(NULL, '.$queryAsig.' :sup, :edo) ', $asigParams );
+                }else{
+                    $asignaciones_rs = $db->query('SELECT * FROM fs_asignacion_solicitud(NULL, '.$queryAsig.' NULL, :edo) ', $asigParams );
+                }
+                
+
+                foreach($asignaciones_rs as $asig){
+                    $tablaArr[] = array("id"=>$asig["asignacion_solicitud_id"], "estado"=>$asig["estado_reposicion_id"], "tipo"=>3,
+                        "profesor_clave"=>$asig["profesor_clave"], "profesor_nombre"=>$asig["profesor_nombre"], "materia_nombre"=>"", "horario_grupo"=>"",
+                        "fecha_falta"=>"", "fecha_nueva"=>$asig["fecha_nueva"], "hora_original"=>"", "hora_nueva"=>$asig["hora_nueva"], "hora_nueva_fin"=>$asig["hora_nueva_fin"],
+
+                        "salon_id"=>$asig["salon_id"], "salon_array"=>$asig["salon_array"]);
+                }
+
+                if(count($tablaArr)>0){
+                    //ordena $tablaArr por fecha_repo
+                    usort($tablaArr, function($a, $b) {
+                        return strtotime($a['fecha_nueva']) - strtotime($b['fecha_nueva']);
+                    });
+                    
+                }else{
+                    echo "No hay reposiciones en este estado";
+                }
+                ?>
+                
+                <h4 class="mb-4" <?php echo "style='color:".$redo["estado_color"]."'";?> > <?php echo $redo["estado_nombre"]; ?> </h4>
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
 
                 <table class="table table-sm table-striped table-white">
                     <thead class="thead-dark">
@@ -237,6 +314,7 @@ if($user->periodo_id!= ""){
                     </thead>
                     <tbody>
                         <?php
+<<<<<<< HEAD
                     if(isset($reposiciones_rs)){
                         foreach($reposiciones_rs as $reposicion){
                         ?>
@@ -248,6 +326,19 @@ if($user->periodo_id!= ""){
                                     <div class=""></div>
                                 </div>
                                 <?php } else if($reposicion["estado_reposicion_id"]==3){?>
+=======
+                    if(isset($tablaArr)){
+                        foreach($tablaArr as $reposicion){
+                        ?>
+                        <tr data-id="<?php echo $reposicion["id"]; ?>" data-edo="<?php echo $reposicion["estado"];?>" id="id<?php echo $reposicion["id"]; ?>">
+                            <td class="align-middle">
+                                <?php if($reposicion["estado"]<3){ ?>
+                                <div class="wizard <?php if(intval($reposicion["estado"])==2) echo "active";?> d-flex mx-auto">
+                                    <div class="w-50 h-100"></div>
+                                    <div class=""></div>
+                                </div>
+                                <?php } else if($reposicion["estado"]==3){?>
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                                 <div class="text-success text-center pt-1">
                                     <span class="ing-autorizar ing-lg"></span>
                                 </div>
@@ -258,7 +349,15 @@ if($user->periodo_id!= ""){
                                 <?php } ?>
                             </td>
                             <td class="align-middle">
+<<<<<<< HEAD
                                 <?php if($reposicion["es_reposicion"]) echo "Resposición"; else echo "Cambio"; ?>
+=======
+                                <?php switch($reposicion["tipo"]){
+                                    case 1: echo "Resposición"; break;
+                                    case 2: echo "Cambio"; break;
+                                    case 3: echo "Asignación"; break;
+                                }?>
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                             </td>
                             <td><?php
                                 echo $reposicion["profesor_clave"]." - ".$reposicion["profesor_nombre"];
@@ -266,6 +365,7 @@ if($user->periodo_id!= ""){
                                 <br>
                                 <small>
                                 <?php echo $reposicion["materia_nombre"]; ?>
+<<<<<<< HEAD
                                 (<?php
                                     echo $reposicion["horario_grupo"];
                                 ?>)
@@ -274,6 +374,21 @@ if($user->periodo_id!= ""){
                             <td class="text-center align-middle text-nowrap"><?php
                                 $fechaI = date("d/m/Y", strtotime($reposicion["fecha_clase"]));
                                 echo $fechaI."<br>".substr($reposicion["horario_hora"],0, 5);
+=======
+                                <?php
+                                if($reposicion["horario_grupo"]!="")
+                                    echo "(".$reposicion["horario_grupo"].")";
+                                ?>
+                                </small>
+                            </td>
+                            <td class="text-center align-middle text-nowrap"><?php
+                                if($reposicion["fecha_falta"]!=""){
+                                    $fechaI = date("d/m/Y", strtotime($reposicion["fecha_falta"]));
+                                    echo $fechaI."<br>".substr($reposicion["hora_original"],0, 5);
+                                }else{
+                                    echo " - ";
+                                }
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                                 ?>
                             </td>
                             <td class="text-center align-middle text-nowrap"><?php
@@ -294,6 +409,7 @@ if($user->periodo_id!= ""){
                             <td class="text-center align-middle icono-acciones text-nowrap">
                                 <?php if (duracionMinutos($reposicion["fecha_nueva"], date("Y-m-d H:i:00")) < 0){ ?>
                                     <?php //no se cumple la fecha de la reposicion, es jefe de carrera
+<<<<<<< HEAD
                                     if((!$user->jefe_carrera || $user->admin || !$coordinador) && $reposicion["estado_reposicion_id"] == 1){?>
                                     <a href="#" data-toggle="modal" data-target="#modal_aprobar" data-tipo="2" title="Aprobar"><?php echo $ICO["ver"];?></a>
                                     <?php } //no se cumple la fecha de la reposicion, no es jefe de carrera
@@ -312,6 +428,26 @@ if($user->periodo_id!= ""){
                                         if(
                                             (($user->jefe_carrera || $user->admin || $coordinador) && $reposicion["estado_reposicion_id"] == 1)/* nueva */
                                             || (($user->admin || $coordinador || $supervisor) && $reposicion["estado_reposicion_id"] == 2)/* aprobado facultad */
+=======
+                                    if((!$user->jefe_carrera || $user->admin || !$coordinador) && $reposicion["estado"] == 1){?>
+                                    <a href="#" data-toggle="modal" data-target="#modal_aprobar" data-estado="2" data-tipo="<?php echo $reposicion["tipo"];?>" title="Aprobar"><?php echo $ICO["ver"];?></a>
+                                    <?php } //no se cumple la fecha de la reposicion, no es jefe de carrera
+                                    else if(($supervisor || $user->admin) && $reposicion["estado"] == 2){?>
+                                    <a href="#" data-toggle="modal" data-target="#modal_aprobar" data-estado="3" data-tipo="<?php echo $reposicion["tipo"];?>" title="Autorizar" ><?php echo $ICO["ver"];?></a>
+                                    <?php } else { ?>
+                                        <a href="#" data-toggle="modal" data-target="#modal_aprobar" data-estado="1" data-tipo="<?php echo $reposicion["tipo"];?>" title="Ver detalle"><?php echo $ICO["ver"];?></a>
+                                    <?php } ?>
+                                    <?php
+                                }else{ //fecha ya pasó?>
+                                    <a href="#" data-toggle="modal" data-target="#modal_aprobar" data-estado="1" data-tipo="<?php echo $reposicion["tipo"];?>" title="Ver detalle"><span class="text-danger"><?php echo $ICO["ver"];?></span></a>
+                                <?php } ?>
+
+                                <?php
+                                    if($reposicion["estado"]<4){
+                                        if(
+                                            (($user->jefe_carrera || $user->admin || $coordinador) && $reposicion["estado"] == 1)/* nueva */
+                                            || (($user->admin || $coordinador || $supervisor) && $reposicion["estado"] == 2)/* aprobado facultad */
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                                         ){
                                 ?>
                                 <a href="#" data-toggle="modal" data-target="#modal_confirm" title="Cancelar"><span class="text-danger"><?php echo $ICO["cancelar"];?></span></a>
@@ -347,6 +483,10 @@ if($user->periodo_id!= ""){
                         <form action="./action/reposicion_autoriza.php" method="post" id="formaModal">
                             <input type="hidden" name="id" id="id">
                             <input type="hidden" name="edo" id="edo" value="">
+<<<<<<< HEAD
+=======
+                            <input type="hidden" name="tipo" id="tipo" value="">
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                             
                             <div class="row">
                                 <div class="col-6 col-sm-4 barra-right text-right">
@@ -481,6 +621,18 @@ if($user->periodo_id!= ""){
                                     <input type="hidden" id="salon" name="salon" value="">
                                 </div>
                             </div>
+<<<<<<< HEAD
+=======
+
+                            <div class="row" id="supervisor" style="display: none;">
+                                <div class="col-6 col-sm-4 barra-right text-right">
+                                    <p class="font-weight-bold">Supervisor</p>
+                                </div>
+                                <div class="col-6">
+                                    <p class="rep-sup"></p>
+                                </div>
+                            </div>
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                             
                             
                             <div class="row mt-4">
@@ -501,7 +653,11 @@ if($user->periodo_id!= ""){
                                 </div>
                             </div>
 
+<<<<<<< HEAD
                             <div class="form-group row mt-3">
+=======
+                            <div class="form-group row mt-3" id="submitGroup">
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                                 <div class="col-12 text-center">
                                     
                                     <p class="aprobar-block">Una vez realizada la acción no se puede deshacer.</p>
@@ -512,6 +668,16 @@ if($user->periodo_id!= ""){
                                     
                                 </div>
                             </div>
+<<<<<<< HEAD
+=======
+                            <div class="form-group row mt-3" id="loadingGroup" style="display:none">
+                                <div class="col-12 text-center">
+                                    <div class="spinner-border text-primary" role="status">
+                                        <span class="sr-only">Loading...</span>
+                                    </div>
+                                </div>
+                            </div>
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                         </form>
                     </div>
                 </div>
@@ -644,11 +810,19 @@ if($user->periodo_id!= ""){
         $('#modal_aprobar').on('show.bs.modal', function (event) {
             var button = $(event.relatedTarget); // Button that triggered the modal
             var id = button.parents("tr").data("id");
+<<<<<<< HEAD
             var edo = button.data('tipo');
+=======
+            var edo = button.data('estado');
+            var tipo = button.data('tipo');
+            $("#loadingGroup").hide();
+            $("#submitGroup").show();
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
 
             //1 ver, 2 aprobar, 3 autorizar
             $("#edo").val(edo);
             $("#id").val(id);
+<<<<<<< HEAD
             
 
             $.ajax({
@@ -743,6 +917,218 @@ if($user->periodo_id!= ""){
                     triggerMessage(errorThrown, "Error");
                 }
             });//ajax
+=======
+            $("#tipo").val(tipo);
+            
+            var action_pag;
+            if(tipo == 1 || tipo == 2){
+                $.ajax({
+                    url:  './action/reposicion_select.php',
+                    type: 'POST', 
+                    dataType: 'json',
+                    data: { id: id},
+                    success: function(result) {
+                        if(result["error"]!= "" &&  result["error"] !== undefined){
+                            triggerMessage(result["error"], "Error");
+                            $('#modal_aprobar').modal("hide");
+                        }else{
+                            $("#dlSalon").val("");
+                            $("#modal_aprobar .rep-prof").text(result["profesor_nombre"]);
+                            $("#modal_aprobar .rep-fac").text(result["facultad"]);
+                            $("#modal_aprobar .rep-carr").parents(".row").show();
+                            $("#modal_aprobar .rep-carr").text(result["carrera"]);
+                            $("#modal_aprobar .rep-gpo").parents(".row").show();
+                            $("#modal_aprobar .rep-gpo").text(result["grupo"]);
+                            $("#modal_aprobar .rep-mat").parents(".row").show();
+                            $("#modal_aprobar .rep-mat").text(result["materia_desc"]);
+                            $("#modal_aprobar .rep-ciclo").parents(".row").show();
+                            $("#modal_aprobar .rep-ciclo").text(result["ciclo"]);
+                            $("#modal_aprobar .rep-bloque").text(result["bloque"]);
+                            if(result["tipo"])
+                                $("#modal_aprobar .rep-tipo").text("Reposición");
+                            else
+                                $("#modal_aprobar .rep-tipo").text("Cambio");
+                            $("#modal_aprobar .rep-aula").text(result["aula_desc"])
+                            $("#modal_aprobar .rep-aula").data("aula",result["aula"]);
+                            $("#modal_aprobar .rep-falta").parents(".row").show();
+                            $("#modal_aprobar .rep-falta").text(result["fecha_clase"]);
+                            $("#modal_aprobar .rep-fecha").text(result["fecha_nueva"]+" de "+result["hora_ini"]+":"+result["min_ini"]+" a "+result["hora_fin"]+":"+result["min_fin"]);
+                            if(result["salon"] =="" || result["salon"] === undefined){
+                                $('#salon').prop("selectedIndex", 0);
+                            }else{
+                                $('#salon').val(result["salon"]);
+                            }
+                            $("#modal_aprobar .rep-salon").text(result["salon_desc"]);
+                            $("#modal_aprobar .rep-comentarios").text(result["comentario"]);
+                            $('#modal_aprobar .rep-alumnos').text(result["alumnos"]);
+
+                            if(result["supervisor_nombre"]!=""){
+                                $("#supervisor").show();
+                                $("#modal_aprobar .rep-sup").text(result["supervisor_nombre"]);
+                            }else{
+                                $("#supervisor").hide();
+                            }
+
+                            if(result["estado"] == 4){//cancelada
+                                $('#modal_aprobar .rep-motivo').text(result["motivo_cancelacion"]);
+                                $("#cancelada-block").show();
+                            }else{
+                                $("#cancelada-block").hide();
+                            }
+
+                            if(edo == 1){// 1  ver
+                                $("#modalLabel").text("Detalle de reposición");
+                                $(".aprobar-block").hide();
+
+                                /*if(parseInt($("#modal_aprobar .rep-aula").data("aula")) != 1){//tipo aula 1 (salon normal)  - ver
+                                    $("#salon-ver").hide();
+                                    $("#salon-editar").show();
+                                }else{
+                                    $("#salon-ver").show();
+                                    $("#salon-editar").hide();
+                                }*/
+                                $("#salon-ver").show();
+                                $("#salon-editar").hide();
+                                
+                            }else{
+                                $("#modalLabel").text("Aprobar reposición");
+                                $(".aprobar-block").show();
+
+                                if(edo == 2 && parseInt($("#modal_aprobar .rep-aula").data("aula")) == 1){//tipo aula 1 (salon normal)  - ver
+                                    $("#salon-ver").show();
+                                    $("#salon-editar").hide();
+                                }else if(edo == 3 && parseInt($("#modal_aprobar .rep-aula").data("aula")) != 1){//aprobar (con salón especial)
+                                    $("#salon-ver").show();
+                                    $("#salon-editar").hide();
+                                }else{
+                                    $("#salon-ver").hide();
+                                    $("#salon-editar").show();
+                                }
+                            }
+
+                            if(result["aula_supervisor"]){//Solo supervisor
+                                <?php if($supervisor){ ?>
+                                    $("#salon-editar").attr("disabled", false);
+                                <?php }else{?>
+                                    $("#salon-editar").attr("disabled", true);
+                                <?php } ?>
+                            }else{// Facultad
+                                <?php if(!$supervisor){ ?>
+                                    $("#salon-editar").attr("disabled", false);
+                                <?php }else{?>
+                                    $("#salon-editar").attr("disabled", true);
+                                <?php } ?>
+                            }                        
+
+                        }
+                    },
+                    error: function(jqXHR, textStatus, errorThrown ){
+                        triggerMessage(errorThrown, "Error");
+                    }
+                });//ajax
+            }else{
+                
+                $.ajax({
+                    url:  './action/asignacion_select.php',
+                    type: 'POST', 
+                    dataType: 'json',
+                    data: { id: id},
+                    success: function(result) {
+                        if(result["error"]!= "" &&  result["error"] !== undefined){
+                            triggerMessage(result["error"], "Error");
+                            $('#modal_aprobar').modal("hide");
+                        }else{
+                            $("#dlSalon").val("");
+                            $("#modal_aprobar .rep-prof").text(result["profesor_nombre"]);
+                            $("#modal_aprobar .rep-fac").text(result["facultad"]);
+                            $("#modal_aprobar .rep-carr").parents(".row").hide();
+                            $("#modal_aprobar .rep-gpo").parents(".row").hide();
+                            $("#modal_aprobar .rep-mat").parents(".row").hide();
+                            $("#modal_aprobar .rep-ciclo").parents(".row").hide();
+                            
+                            $("#modal_aprobar .rep-tipo").text("Asignación");
+                            
+                            $("#modal_aprobar .rep-aula").text(result["aula_desc"])
+                            $("#modal_aprobar .rep-aula").data("aula",result["aula"]);
+                            $("#modal_aprobar .rep-falta").parents(".row").hide();
+                            $("#modal_aprobar .rep-fecha").text(result["fecha_nueva"]+" de "+result["hora_ini"]+":"+result["min_ini"]+" a "+result["hora_fin"]+":"+result["min_fin"]);
+                            if(result["salon"] =="" || result["salon"] === undefined){
+                                $('#salon').prop("selectedIndex", 0);
+                            }else{
+                                $('#salon').val(result["salon"]);
+                            }
+                            $("#modal_aprobar .rep-salon").text(result["salon_desc"]);
+                            $("#modal_aprobar .rep-comentarios").text(result["comentario"]);
+                            $('#modal_aprobar .rep-alumnos').text(result["alumnos"]);
+
+                            if(result["supervisor_nombre"]!=""){
+                                $("#supervisor").show();
+                                $("#modal_aprobar .rep-sup").text(result["supervisor_nombre"]);
+                            }else{
+                                $("#supervisor").hide();
+                            }
+
+                            if(result["estado"] == 4){//cancelada
+                                $('#modal_aprobar .rep-motivo').text(result["motivo_cancelacion"]);
+                                $("#cancelada-block").show();
+                            }else{
+                                $("#cancelada-block").hide();
+                            }
+
+                            if(edo == 1){// 1  ver
+                                $("#modalLabel").text("Detalle de reposición");
+                                $(".aprobar-block").hide();
+
+                                /*if(parseInt($("#modal_aprobar .rep-aula").data("aula")) != 1){//tipo aula 1 (salon normal)  - ver
+                                    $("#salon-ver").hide();
+                                    $("#salon-editar").show();
+                                }else{
+                                    $("#salon-ver").show();
+                                    $("#salon-editar").hide();
+                                }*/
+                                $("#salon-ver").show();
+                                $("#salon-editar").hide();
+                                
+                            }else{
+                                $("#modalLabel").text("Aprobar reposición");
+                                $(".aprobar-block").show();
+
+                                if(edo == 2 && parseInt($("#modal_aprobar .rep-aula").data("aula")) == 1){//tipo aula 1 (salon normal)  - ver
+                                    $("#salon-ver").show();
+                                    $("#salon-editar").hide();
+                                }else if(edo == 3 && parseInt($("#modal_aprobar .rep-aula").data("aula")) != 1){//aprobar (con salón especial)
+                                    $("#salon-ver").show();
+                                    $("#salon-editar").hide();
+                                }else{
+                                    $("#salon-ver").hide();
+                                    $("#salon-editar").show();
+                                }
+                            }
+
+                            if(result["aula_supervisor"]){//Solo supervisor
+                                <?php if($supervisor){ ?>
+                                    $("#salon-editar").attr("disabled", false);
+                                <?php }else{?>
+                                    $("#salon-editar").attr("disabled", true);
+                                <?php } ?>
+                            }else{// Facultad
+                                <?php if(!$supervisor){ ?>
+                                    $("#salon-editar").attr("disabled", false);
+                                <?php }else{?>
+                                    $("#salon-editar").attr("disabled", true);
+                                <?php } ?>
+                            }                        
+
+                        }
+                    },
+                    error: function(jqXHR, textStatus, errorThrown ){
+                        triggerMessage(errorThrown, "Error");
+                    }
+                });//ajax
+            }
+            
+            
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
         });
         /*
         $(".btn-borrar").click(function(){
@@ -777,6 +1163,11 @@ if($user->periodo_id!= ""){
             var edo =  parseInt($("#edo").val());
             console.log(edo)
             if((edo == 3 && valida()) || edo == 2){
+<<<<<<< HEAD
+=======
+                $("#loadingGroup").show();
+                $("#submitGroup").hide();
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                 $("#formaModal").submit();
             }      
         });

+ 35 - 0
reposiciones_crear.php

@@ -407,10 +407,18 @@ if(!is_null($user->periodo_id)){
                                             <div class="datalist-input">Salón</div>
                                             <span class="ing-buscar icono"></span>
                                             <ul style="display:none">
+<<<<<<< HEAD
                                                 <li data-id="1">Salón</li>
                                                 <li data-id="2">Sala de cómputo</li>
                                                 <li data-id="3">Salón/Taller de la facultad</li>
                                                 <li data-id="4">Virtual</li>
+=======
+                                                <?php
+                                                $tipoaula_rs = $db->query('select * from tipoaula t order by t.tipoaula_id ');
+                                                foreach($tipoaula_rs as $ta){ ?>
+                                                    <li data-id="<?php echo $ta["tipoaula_id"];?>"><?php echo $ta["tipoaula_nombre"];?></li>
+                                                <?php } ?>
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                                             </ul>
                                             <input type="hidden" id="aula" name="aula" value="1">
                                         </div>
@@ -461,12 +469,26 @@ if(!is_null($user->periodo_id)){
                                 </div>
                             </div>
                             
+<<<<<<< HEAD
                             <div class="form-group row mt-3">
+=======
+                            <div class="form-group row mt-3" id="submitGroup">
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                                 <div class="offset-4 col-8">
                                     <button type="submit" class="btn btn-outline-primary  materia-block" id="submitBtn" data-tipo="1"><?php echo $ICO["aceptar"];?> Guardar</button>
                                     <button type="reset" class="btn btn-outline-danger" data-dismiss="modal"><?php echo $ICO["cancelar"];?> Cancelar</button>
                                 </div>
                             </div>
+<<<<<<< HEAD
+=======
+                            <div class="form-group row mt-3" id="loadingGroup" style="display:none">
+                                <div class="col-12 text-center">
+                                    <div class="spinner-border text-primary" role="status">
+                                        <span class="sr-only">Loading...</span>
+                                    </div>
+                                </div>
+                            </div>
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                         </form>
                     </div>
                 </div>
@@ -761,6 +783,13 @@ if(!is_null($user->periodo_id)){
         }else{
             $('#formaModal').prop("action", "./action/reposicion_insert.php");
         }
+<<<<<<< HEAD
+=======
+        if(!error){
+            $("#loadingGroup").show();
+            $("#submitGroup").hide();
+        }
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
         return !error;
     }
 
@@ -947,6 +976,12 @@ if(!is_null($user->periodo_id)){
             var button = $(event.relatedTarget); // Button that triggered the modal
             var tipo = button.data('tipo'); // 1 alta, 2 edicion
             var modal = $(this);
+<<<<<<< HEAD
+=======
+
+            $("#loadingGroup").hide();
+            $("#submitGroup").show();
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
             
             $("#modal .is-invalid").removeClass("is-invalid");
             //$(this).find(".form-control:first-child").focus();

+ 36 - 0
rest/horarios.php

@@ -198,6 +198,7 @@ try{
                         "per"=>$per["periodo_id"]
                     );
                 }else{//reposición
+<<<<<<< HEAD
                     
                     if(in_array($row["ClaveCarrera"] , $arreglo_claves)){
                         //busca yyyy-mm-dd hh:mm:ss en la cadena
@@ -216,6 +217,29 @@ try{
                             if($debug)
                                 echo "No se encontró fecha y hora en: ".$row["Observaciones"]."<br>";
                         }
+=======
+                    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();
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                     }
                 }
             }
@@ -284,11 +308,23 @@ try{
         //Update fecha_fin
         $log_desc = "";
         foreach($elementos_no_en_sgu as $row){
+<<<<<<< HEAD
             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"].") ## ";
+=======
+            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();
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
             }
         }
         if(!$debug && !empty($log_desc)){

+ 22 - 0
rest/materias.php

@@ -199,6 +199,7 @@ $periodos = $db
                                 </thead>
                                 <tbody>
                                     <script>
+<<<<<<< HEAD
                                         async function borrarMateria(id) {
                                             const url = `https://paad.lci.ulsa.mx/postgrest/materia?materia_id=eq.${id}`;
 
@@ -210,11 +211,29 @@ $periodos = $db
 
                                             console.log(`Materia borrada: ${id}`);
 
+=======
+                                        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");
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                                         }
                                     </script>
                                     <?php foreach ($materias as $materia) { ?>
                                         <tr>
                                             <td>
+<<<<<<< HEAD
+=======
+                                                <input type="checkbox" name="materia_id" id="materia_id"
+                                                    value="<?= $materia["materia_id"] ?>">
+                                            </td>
+                                            <td>
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                                                 <?= $materia["materia_id"] ?>
                                                 <small>
                                                     (
@@ -236,11 +255,14 @@ $periodos = $db
                                                 </small>
                                                 <?= $materia["facultad_nombre"] ?>
                                             </td>
+<<<<<<< HEAD
                                             <td>
                                                 <button
                                                     onclick="borrarMateria(<?= $materia['materia_id'] ?>)">Borrar</button>
                                                 <button>Editar</button>
                                             </td>
+=======
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                                         </tr>
                                     <?php } ?>
                                 </tbody>

+ 75 - 0
ts/auditoría.ts

@@ -77,6 +77,10 @@ $('div.modal#cargando').modal({
 
 const store = reactive({
     loading: false,
+<<<<<<< HEAD
+=======
+    perido: null as Periodo | null,
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
     current: {
         comentario: '',
         clase_vista: null,
@@ -216,8 +220,13 @@ const store = reactive({
             registro_fecha_justificacion: Date;
         };
         try {
+<<<<<<< HEAD
             const res = await fetch('action/action_justificar.php', {
                 method: 'PUT',
+=======
+            const res = await fetch('action/justificar.php', {
+                method: 'POST',
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
                 headers: {
                     'Content-Type': 'application/json'
                 },
@@ -237,6 +246,44 @@ const store = reactive({
         store.current.justificada.justificador_rol = data.justificador_rol
         store.current.justificada.registro_fecha_justificacion = data.registro_fecha_justificacion
     },
+<<<<<<< HEAD
+=======
+    async justificarBloque(fecha: Date, bloques: Array<number>, justificacion: string) {
+        if (bloques.length === 0) {
+            alert('No se ha seleccionado ningún bloque');
+            return;
+        }
+        if (!justificacion) {
+            alert('No se ha ingresado ninguna observación');
+            return;
+        }
+        try {
+            const res = await fetch('action/action_justificar.php', {
+                method: 'PUT',
+                headers: {
+                    'Content-Type': 'application/json'
+                },
+                body: JSON.stringify({
+                    fecha,
+                    bloques,
+                    justificacion,
+                })
+            })
+            const resData = await res.json();
+            if (resData.status === 'success') {
+                alert('Se ha justificado el bloque');
+                store.current.modal_state = 'Cargando datos...';
+                $('div.modal#cargando').modal('show');
+                await store.registros.fetch();
+                $('div.modal#cargando').modal('hide');
+            } else {
+                alert('No se ha podido justificar el bloque');
+            }
+        } catch (error) {
+            alert('Error al justificar');
+        }
+    },
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
     registros: {
         data: [] as Registro[],
         async fetch(fecha?: Date, fecha_inicio?: Date, fecha_fin?: Date) {
@@ -284,7 +331,11 @@ const store = reactive({
                 if one of the filters is null, then it is not relevant
     
             */
+<<<<<<< HEAD
             const filters = Object.keys(store.filters).filter((filtro) => store.filters[filtro] !== null || store.filters[filtro]?.length > 0 )
+=======
+            const filters = Object.keys(store.filters).filter((filtro) => store.filters[filtro] !== null || store.filters[filtro]?.length > 0)
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
             return this.data.filter((registro: Registro) => {
                 return filters.every((filtro) => {
                     switch (filtro) {
@@ -365,6 +416,10 @@ type Profesor = {
 }
 createApp({
     store,
+<<<<<<< HEAD
+=======
+    messages: [] as Array<{ title: string, text: string, type: string, timestamp: string }>,
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
     get clase_vista() {
         return store.current.clase_vista
     },
@@ -381,6 +436,7 @@ createApp({
     profesores: [] as Profesor[],
     async mounted() {
         $('div.modal#cargando').modal('show');
+<<<<<<< HEAD
 
         // await store.registros.fetch()
         await store.facultades.fetch()
@@ -390,5 +446,24 @@ createApp({
         this.profesores = await (await fetch('action/action_profesor.php')).json() as Profesor[];
 
         $('div.modal#cargando').modal('hide');
+=======
+        try {
+
+            // await store.registros.fetch()
+            await store.facultades.fetch()
+            await store.estados.fetch()
+            await store.bloques_horario.fetch()
+            await store.filters.switchFechas();
+            store.periodo = await fetch('action/periodo_datos.php').then(res => res.json()) as Periodo;
+            this.profesores = await (await fetch('action/action_profesor.php')).json() as Profesor[];
+            
+            this.messages.push({ title: 'Datos cargados', text: 'Los datos se han cargado correctamente', type: 'success', timestamp: new Date() })
+        } catch (error) {
+            this.messages.push({ title: 'Error al cargar datos', text: 'No se pudieron cargar los datos', type: 'danger', timestamp: new Date() })
+        }
+        finally {
+            $('div.modal#cargando').modal('hide');
+        }
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
     }
 }).mount('#app')

+ 207 - 0
ts/avisos.ts

@@ -0,0 +1,207 @@
+import { createApp, reactive } from 'https://unpkg.com/petite-vue?module'
+
+type Profesor = {
+    profesor_clave: string;
+    profesor_correo: null | string;
+    profesor_grado: null | string;
+    profesor_id: number;
+    profesor_nombre: string;
+}
+
+type Carrera = {
+    carrera_activa: boolean;
+    carrera_comun: boolean;
+    carrera_id: number;
+    carrera_nombre: string;
+    clave_carrera: string;
+    facultad_id: number | null;
+    nivel_id: number;
+}
+
+type Periodo = {
+    created_at: Date;
+    estado_id: number;
+    fecha_final: Date;
+    id_periodo_sgu: number;
+    nivel_id: number;
+    periodo_clave: string;
+    periodo_fecha_fin: Date;
+    periodo_fecha_inicio: Date;
+    periodo_id: number;
+    periodo_nombre: string;
+}
+
+type Aviso = {
+    aviso_estado: boolean;
+    aviso_titulo: string;
+    aviso_fecha_final: Date;
+    aviso_fecha_inicial: Date;
+    aviso_id: number;
+    aviso_texto: string;
+    carreras: Carrera[];
+    facultad_id: null;
+    profesores: Profesor[];
+}
+
+const new_aviso = reactive({
+    titulo: '',
+    descripcion: '',
+    fechaInicio: '',
+    fechaFin: '',
+    profesores: [] as Array<Profesor>,
+    carreras: [] as Array<Carrera>,
+    reset() {
+        this.titulo = ''
+        this.descripcion = ''
+        this.fechaInicio = ''
+        this.fechaFin = ''
+        this.profesores = []
+        this.carreras = []
+    },
+    get isValid() {
+        return this.titulo !== '' && this.descripcion !== '' && this.fechaInicio !== '' && this.fechaFin !== '' && (this.profesores.length > 0 || this.carreras.length > 0) && this.facultad_id !== null
+    },
+})
+// define datepicker method
+
+const app = createApp({
+    new_aviso,
+    profesores: [] as Array<Profesor>,
+    carreras: [] as Array<Carrera>,
+    avisos: [] as Array<Aviso>,
+
+    profesor: null as String | null,
+    formatProfesor(profesor: Profesor) {
+        return `(${profesor.profesor_clave}) ${profesor.profesor_nombre}`
+    },
+    addProfesor() {
+        const profesorObj = this.profesores.find((profesor: Profesor) => this.profesor === this.formatProfesor(profesor))
+        if (profesorObj) {
+            this.new_aviso.profesores.push(profesorObj)
+            this.profesor = null
+        }
+    },
+
+    aviso_shown: null as Aviso | null,
+    // int?
+    aviso_suspendido: null as number | null,
+    suspenderAviso() {
+        if (this.aviso_suspendido) {
+            const aviso = this.avisos.find((aviso: Aviso) => aviso.aviso_id === this.aviso_suspendido)
+            if (aviso) {
+                this.deleteAviso(aviso)
+            }
+        }
+    },
+
+    get relevant_profesores() {
+        // not in array new_aviso.profesores
+        const relevant = this.profesores.filter((profesor: Profesor) => !this.new_aviso.profesores.map((profesor: Profesor) => profesor.profesor_id).includes(profesor.profesor_id))
+        // console.log('profesores:', this.profesores.map((profesor: Profesor) => profesor.profesor_nombre), 'relevant:', relevant.map((profesor: Profesor) => profesor.profesor_nombre), 'new_aviso:', this.new_aviso.profesores.map((profesor: Profesor) => profesor.profesor_nombre))
+        return relevant
+    },
+
+    get relevant_carreras() {
+        // not in array new_aviso.carreras
+        return this.carreras.filter((carrera: Carrera) => !this.new_aviso.carreras.includes(carrera))
+    },
+
+    createAviso() {
+        const data = {
+            aviso_titulo: this.new_aviso.titulo,
+            aviso_texto: this.new_aviso.descripcion,
+            aviso_fecha_inicial: this.new_aviso.fechaInicio,
+            aviso_fecha_final: this.new_aviso.fechaFin,
+            profesores: this.new_aviso.profesores.map((profesor: Profesor) => profesor.profesor_id),
+            carreras: this.new_aviso.carreras.map((carrera: Carrera) => carrera.carrera_id),
+        }
+        fetch('/action/avisos.php', {
+            method: 'POST',
+            body: JSON.stringify(data)
+        }).then(res => res.json()).then(res => {
+            if (res.success) {
+                // hydrate with carreras and profesores
+                this.avisos.push({
+                    ...data,
+                    carreras: this.carreras.filter((carrera: Carrera) => data.carreras.includes(carrera.carrera_id)),
+                    profesores: this.profesores.filter((profesor: Profesor) => data.profesores.includes(profesor.profesor_id)),
+                    aviso_estado: true,
+                    aviso_id: res.aviso_id,
+                })
+                this.new_aviso.reset()
+            }
+            else {
+                alert(res.error)
+                console.log(res.errors)
+            }
+        })
+    },
+
+    deleteAviso(aviso: Aviso) {
+        fetch(`/action/avisos.php`, {
+            method: 'DELETE',
+            body: JSON.stringify({ aviso_id: aviso.aviso_id })
+        }).then(res => res.json()).then(res => {
+            if (res.success) {
+                this.avisos = this.avisos.filter((aviso: Aviso) => aviso.aviso_id !== this.aviso_suspendido)
+                this.aviso_suspendido = null
+            }
+            else {
+                alert(res.error)
+                console.log(res.errors)
+            }
+        })
+    },
+
+    updateAviso() {
+        fetch(`/action/avisos.php`, {
+            method: 'PUT',
+            body: JSON.stringify({
+                aviso_id: this.aviso_shown.aviso_id,
+                aviso_fecha_final: this.aviso_shown.aviso_fecha_final,
+            })
+        }).then(res => res.json()).then(res => {
+            if (res.success) {
+            }
+            else {
+                alert(res.error)
+                console.log(res.errors)
+            }
+        })
+    },
+
+    async initializeDatepickers($el: HTMLElement) {
+        const periodo = await fetch('action/periodo_datos.php');
+        const periodo_data = await periodo.json() as Periodo;
+
+        $('.date-picker').datepicker({
+            dateFormat: 'yy-mm-dd',
+            maxDate: periodo_data.periodo_fecha_fin,
+            minDate: 0,
+        });
+
+        $($el).on('change', () => {
+            this.aviso_shown.aviso_fecha_final = $($el).val() as string;
+        });
+    },
+
+    async mounted() {
+        this.avisos = await fetch("/action/avisos.php").then(res => res.json()) as Array<Aviso>
+        this.profesores = await fetch('/action/action_profesor.php').then(res => res.json()) as Array<Profesor>
+        this.carreras = await fetch('/action/action_carreras.php').then(res => res.json()) as Array<Carrera>
+
+        await this.initializeDatepickers()
+
+        const fechaInicio = $('#fechaInicio.date-picker')
+        const fechaFin = $('#fechaFin.date-picker')
+        fechaInicio.on("change", function () {
+            new_aviso.fechaInicio = fechaInicio.val() as string
+            fechaFin.datepicker("option", "minDate", fechaInicio.val());
+        });
+
+        fechaFin.on("change", function () {
+            new_aviso.fechaFin = fechaFin.val() as string
+            fechaInicio.datepicker("option", "maxDate", fechaFin.val());
+        });
+    }
+}).mount('#app')

+ 63 - 0
ts/carreras.ts

@@ -0,0 +1,63 @@
+import { createApp, reactive } from 'https://unpkg.com/petite-vue?module'
+
+type Carrera = {
+    carrera_id: number;
+    carrera_nombre: string;
+    clave_carrera: string;
+    facultad_id: number;
+    facultad_nombre: string;
+    nivel_id: number;
+    nivel_nombre: string;
+}
+
+type Nivel = {
+    nivel_id: number;
+    nivel_nombre: string;
+}
+
+const app = createApp({
+    carreras: [] as Carrera[],
+    niveles: [] as Nivel[],
+    message: {} as Record<string, string>,
+    async setNivel(carrera: Carrera, nivel: Nivel) {
+        if (carrera.nivel_id === nivel.nivel_id) {
+            return
+        }
+        carrera.nivel_id = nivel.nivel_id
+        carrera.nivel_nombre = nivel.nivel_nombre
+
+        await fetch('action/carrera.php', {
+            method: 'PUT',
+            body: JSON.stringify({
+                carrera_id: carrera.carrera_id,
+                nivel_id: nivel.nivel_id
+            })
+        })
+            .then(res => res.json())
+            .then(res => {
+                this.message.title = "Actualización"
+                this.message.text = res.error ?? res.success
+                this.message.type = res.error ? 'danger' : 'success'
+                this.message.timestamp = new Date().toLocaleTimeString()
+            })
+
+
+    },
+    async mounted() {
+        this.carreras = await fetch('action/carrera.php').then(res => res.json())
+        this.niveles = await fetch('action/nivel.php').then(res => res.json())
+        // group by facultad_id
+        const carreras = this.carreras.reduce((acc, cur) => {
+            const { facultad_nombre } = cur
+            if (!acc[facultad_nombre]) {
+                acc[facultad_nombre] = []
+            }
+            acc[facultad_nombre].push(cur)
+            return acc
+        }, {} as Record<number, Carrera[]>)
+        this.carreras = Object.entries(carreras).map(([facultad_nombre, carreras]) => ({
+            facultad_nombre: facultad_nombre,
+            carreras
+        }))
+    }
+}).mount('#app') 

+ 149 - 0
ts/client.ts

@@ -0,0 +1,149 @@
+// @ts-ignore Import module
+import { createApp, reactive } from 'https://unpkg.com/petite-vue?module'
+
+export interface PeridoV1 {
+    IdNivel: number;
+    IdPeriodo: number;
+    NombreNivel: string;
+    NombrePeriodo: string;
+    in_db: boolean;
+    linked: boolean;
+}
+
+
+export interface PeridoV2 {
+    ClaveCarrera: string;
+    FechaFin: string;
+    FechaInicio: string;
+    IdPeriodo: number;
+    NombreCarrera: string;
+}
+
+const webServices = {
+    getPeriodosV1: async (): Promise<PeridoV1[]> => {
+        try {
+            const response = await fetch('periodos.v1.php');
+            return await response.json();
+        } catch (error) {
+            console.log(error);
+            return [];
+        }
+    },
+    getPeriodosV2: async (): Promise<PeridoV2[]> => {
+        try {
+            const response = await fetch('periodos.v2.php');
+            return await response.json();
+        } catch (error) {
+            console.log(error);
+            return [];
+        }
+    }
+}
+
+const store = reactive({
+    periodosV1: [] as PeridoV1[],
+    periodosV2: [] as PeridoV2[],
+
+    errors: [] as string[],
+    fechas(idPeriodo: number): { inicio: string, fin: string } {
+        const periodo = this.periodosV2.find((periodo: PeridoV2) => periodo.IdPeriodo === idPeriodo);
+        return {
+            inicio: periodo ? periodo.FechaInicio : '',
+            fin: periodo ? periodo.FechaFin : ''
+        }
+    },
+    periodov1(idPeriodo: number): PeridoV1 | undefined {
+        return this.periodosV1.find((periodo: PeridoV1) => periodo.IdPeriodo === idPeriodo);
+    },
+    periodov2(idPeriodo: number): PeridoV2[] {
+        return this.periodosV2.filter((periodo: PeridoV2) => periodo.IdPeriodo === idPeriodo);
+    },
+    async addPeriodo(periodo: PeridoV1 | PeridoV2) {
+        try {
+            const result = await fetch('backend/periodos.php', {
+                method: 'POST',
+                body: JSON.stringify({
+                    ...periodo,
+                    ...this.fechas(periodo.IdPeriodo)
+                }),
+                headers: {
+                    'Content-Type': 'application/json'
+                }
+            }).then((response) => response.json());
+            if (result.success) {
+                this.periodosV1 = this.periodosV1.map((periodoV1: PeridoV1) => {
+                    if (periodoV1.IdPeriodo === periodo.IdPeriodo) {
+                        periodoV1.in_db = true;
+                    }
+                    return periodoV1;
+                });
+                return result;
+            }
+            else {
+                this.errors.push(result.message);
+            }
+        } catch (error) {
+            this.errors.push(error);
+        }
+    },
+
+    async addCarreras(idPeriodo: number) {
+        try {
+            const periodoV1 = this.periodov1(idPeriodo) as PeridoV1;
+            const periodoV2 = this.periodov2(idPeriodo) as PeridoV2[];
+
+            const data = periodoV2.map(({ ClaveCarrera, NombreCarrera }: PeridoV2) =>
+            ({
+                ClaveCarrera: ClaveCarrera,
+                NombreCarrera: NombreCarrera,
+                IdNivel: periodoV1.IdNivel,
+            })
+            );
+
+            const result = await fetch('backend/carreras.php', {
+                method: 'POST',
+                body: JSON.stringify(data),
+                headers: {
+                    'Content-Type': 'application/json'
+                }
+            }).then((response) => response.json());
+            if (result.success) {
+                await webServices.getPeriodosV1().then((periodosV1) => {
+                    this.periodosV1 = periodosV1;
+                });
+
+                await webServices.getPeriodosV2().then((periodosV2) => {
+                    this.periodosV2 = periodosV2;
+                });
+            }
+
+        } catch (error) {
+            this.errors.push(error);
+        }
+    }
+})
+
+
+createApp({
+    store,
+    info(IdPeriodo: number): PeridoV2 {
+        const periodo = store.periodosV2.find((periodo: PeridoV2) => periodo.IdPeriodo === IdPeriodo &&
+            periodo.FechaInicio != '' && periodo.FechaFin != '');
+        return periodo
+    },
+    complete(IdPeriodo: number): boolean {
+        const info = this.info(IdPeriodo);
+        return info !== undefined;
+    },
+    mounted: async () => {
+
+        await webServices.getPeriodosV1().then((periodosV1) => {
+            store.periodosV1 = periodosV1;
+        });
+
+        await webServices.getPeriodosV2().then((periodosV2) => {
+            store.periodosV2 = periodosV2;
+        });
+
+    }
+}).mount()

+ 1 - 0
ts/declaration.ts

@@ -0,0 +1 @@
+declare module 'https://*'

+ 4 - 0
ts/faltas.ts

@@ -23,8 +23,12 @@ const app = createApp({
     },
 
     async refresh() {
+<<<<<<< HEAD
         alert(`Facultad: ${filter.facultad} - Profesor: ${filter.profesor} - Porcentaje: ${filter.porcentaje}%`
         if(filter.facultad == -1 || filter.porcetaje < 10) {
+=======
+        if(filter.facultad == -1 || filter.porcentaje < 10) {
+>>>>>>> 7688f1aac1824c234bc5f19b154e9ad1f4808d4f
             return;
         }
 

+ 181 - 0
ts/horario.ts

@@ -0,0 +1,181 @@
+import { createApp, reactive } from 'https://unpkg.com/petite-vue?module'
+type Profesor = {
+    profesor_clave: string;
+    profesor_correo: string;
+    profesor_grado: null | string;
+    profesor_id: number;
+    profesor_nombre: string;
+}
+
+type Horario = {
+    carrera: string;
+    carrera_id: number;
+    dia: string;
+    duracion: string;
+    duracion_id: number;
+    facultad: string;
+    facultad_id: number;
+    fecha_carga: Date;
+    horario_dia: number;
+    horario_fecha_fin: null;
+    horario_fecha_inicio: Date;
+    horario_fin: string;
+    horario_grupo: string;
+    horario_hora: string;
+    horario_id: number;
+    limite: null;
+    materia: string;
+    materia_id: number;
+    nivel: string;
+    nivel_id: number;
+    periodo: string;
+    periodo_fecha_fin: Date;
+    periodo_fecha_inicio: Date;
+    periodo_id: number;
+    profesor_id: number;
+    salon: string;
+    salon_id: number;
+    bloques: number;
+}
+
+type Facultad = {
+    clave_dependencia: string;
+    facultad_id: number;
+    facultad_nombre: string;
+    carreras: Carrera[];
+}
+
+type Carrera = {
+    carrera_id: number;
+    carrera_nombre: string;
+    clave_carrera: string;
+    facultad_id: number;
+}
+
+
+
+const profesores = reactive({
+    data: [] as Profesor[],
+    search: null as null | string,
+    fetch: async function () {
+        const response = await fetch('action/action_profesor.php')
+        this.data = await response.json() as Profesor[]
+    },
+    get clave() {
+        const match = this.search.match(/^\((.+)\)/)
+        return match ? match[1] : ''
+    },
+    get current() {
+        return this.data.find((profesor: Profesor) => profesor.profesor_clave === profesores.clave)
+    },
+})
+
+const facultades = reactive({
+    data: [] as Facultad[],
+    fetch: async function () {
+        const facultades = await fetch('action/action_facultad.php').then(response => response.json()) as Facultad[]
+        const carreras = await fetch(`action/carrera.php`).then(response => response.json()) as Carrera[]
+        this.data = await Promise.all(facultades.map(async facultad => ({
+            ...facultad,
+            carreras: await Promise.all(carreras.filter((carrera: Carrera) => carrera.facultad_id === facultad.facultad_id).map(async (carrera: Carrera) => {
+                const grupos = await fetch(`action/action_grupo.php?carrera_id=${carrera.carrera_id}`).then(response => response.json())
+                return {
+                    ...carrera,
+                    grupos,
+                }
+            })),
+        })))
+
+        this.data = this.data.filter((facultad: Facultad) => facultad.carreras.length > 0)
+    }
+})
+
+type Structure = {
+    sábado: boolean;
+    hora_mínima: number;
+    hora_máxima: number;
+    horas_totales: number;
+}
+
+const horarios = reactive({
+    data: [] as Horario[],
+    fetch: async function (grupo: number | null = null, carrera_id: number | null = null) {
+        if (grupo && carrera_id) {
+            const response = await fetch(`action/action_horario.php?grupo=${grupo}&carrera_id=${carrera_id}`)
+            this.data = await response.json()
+        }
+        else if (profesores.current) {
+            const response = await fetch(`action/action_horario.php?profesor_id=${profesores.current.profesor_id}`)
+            this.data = await response.json()
+        }
+    },
+    get structure() {
+        if (this.data.length === 0) return null;
+
+        const structure: Structure = {
+            sábado: this.data.some((horario: Horario) => horario.horario_dia === 6),
+            hora_mínima: Math.min(...this.data.map((horario: Horario) => parseInt(horario.horario_hora.split(':')[0]))),
+            hora_máxima: Math.max(...this.data.map((horario: Horario) => {
+                const [hour, minute] = horario.horario_fin.split(':').map(Number);
+                return hour + Math.ceil(minute / 60);
+            })),
+            horas_totales: 0
+        };
+
+        structure.horas_totales = structure.hora_máxima - structure.hora_mínima;
+
+        return structure;
+    },
+    get blocks() {
+        if (this.data.length === 0) return null;
+        return [...Array(this.structure.horas_totales).keys()].flatMap(hora => {
+            const baseHour = hora + this.structure.hora_mínima;
+            return [0, 15, 30, 45].map(block => ({ hour: baseHour, block }));
+        });
+    },
+    getHorarioData(hour: number, block: number, día: number) {
+        const foundHorario = this.data.find((horario: Horario) =>
+            parseInt(horario.horario_hora.split(':')[0]) === hour &&
+            parseInt(horario.horario_hora.split(':')[1]) === block &&
+            horario.horario_dia === día
+        );
+        return foundHorario;
+    },
+    isOccupied(hora: number, bloque: number, day: number) {
+        if (this.getHorarioData(hora, bloque, day)) {
+            return false;
+        }
+        const currentTimeInMinutes = hora * 60 + bloque;
+
+        for (const item of this.data) {
+            if (item.horario_dia !== day) {
+                continue; // Skip items that are not on the specified day
+            }
+
+            // Split the hour and minute from horario_hora
+            const [startHour, startMinute] = item.horario_hora.split(":").map(Number);
+            const startTimeInMinutes = startHour * 60 + startMinute;
+
+            // Calculate end time using duracion
+            const [durationHours, durationMinutes] = item.duracion.split(":").map(Number);
+            const endTimeInMinutes = startTimeInMinutes + (durationHours * 60) + durationMinutes;
+
+            if (currentTimeInMinutes >= startTimeInMinutes && currentTimeInMinutes < endTimeInMinutes) {
+                return true;  // The block is occupied
+            }
+        }
+
+        return false;  // The block is not occupied by any class
+    }
+
+})
+
+const app = createApp({
+    profesores,
+    horarios,
+    facultades,
+    mounted: async function () {
+        await profesores.fetch()
+        await facultades.fetch()
+    }
+}).mount('#app')

+ 145 - 0
ts/periodos.ts

@@ -0,0 +1,145 @@
+import { createApp, reactive } from 'https://unpkg.com/petite-vue?module'
+
+interface Periodo {
+    created_at: Date;
+    estado_id: number;
+    id_periodo_sgu: number;
+    nivel: string;
+    nivel_id: number | '';
+    periodo_clave: string;
+    periodo_fecha_fin: Date;
+    periodo_fecha_inicio: Date;
+    periodo_id: number;
+    periodo_nombre: string;
+}
+
+interface Nivel {
+    nivel_id: number;
+    nivel_nombre: string;
+}
+
+const app = createApp({
+    periodos: [] as Array<Periodo>,
+    niveles: [] as Array<Nivel>,
+    messages: [] as Array<{ title: string, text: string, type: string, timestamp: string }>,
+
+    addMessage(title: string, text: string, type: string) {
+        this.messages.push({ title, text, type, timestamp: new Date() });
+    },
+
+    async sendRequest(action: string, periodo_id: number, data: any) {
+        const response = await fetch('action/periodos.php', {
+            method: 'PUT',
+            headers: {
+                'Content-Type': 'application/json'
+            },
+            body: JSON.stringify({
+                action: action,
+                periodo_id: periodo_id,
+                ...data
+            })
+        })
+        return await response.json()
+    },
+
+    async changeNivel(periodo: Periodo, nivel_id: number) {
+        if (periodo.nivel_id === nivel_id) return
+
+        const result = await this.sendRequest('changeNivel', periodo.periodo_id, { nivel_id: nivel_id })
+        if (result.success) {
+            this.addMessage('Nivel cambiado', `El nivel del periodo ${periodo.periodo_nombre} ha sido cambiado a ${this.niveles.find((nivel: Nivel) => nivel.nivel_id === nivel_id)?.nivel_nombre}`, 'success')
+            periodo.nivel_id = nivel_id
+            periodo.nivel = this.niveles.find((nivel: Nivel) => nivel.nivel_id === nivel_id)?.nivel_nombre || ''
+        } else {
+            this.addMessage('Error al cambiar nivel', `No se pudo cambiar el nivel del periodo ${periodo.periodo_nombre}`, 'danger')
+        }
+    },
+
+    async changeFechaInicio(periodo: Periodo, fecha_inicio: Date) {
+        const result = await this.sendRequest('changeFechaInicio', periodo.periodo_id, { periodo_fecha_inicio: fecha_inicio })
+        if (result.success) {
+            this.addMessage('Fecha de inicio cambiada', `La fecha de inicio del periodo ${periodo.periodo_nombre} ha sido cambiada a ${fecha_inicio}`, 'success')
+
+            periodo.periodo_fecha_inicio = fecha_inicio
+        } else {
+            this.addMessage('Error al cambiar fecha de inicio', `No se pudo cambiar la fecha de inicio del periodo ${periodo.periodo_nombre}`, 'danger')
+        }
+    },
+
+    async changeFechaFin(periodo: Periodo, fecha_fin: Date) {
+        const result = await this.sendRequest('changeFechaFin', periodo.periodo_id, { periodo_fecha_fin: fecha_fin })
+        if (result.success) {
+            this.addMessage('Fecha de fin cambiada', `La fecha de fin del periodo ${periodo.periodo_nombre} ha sido cambiada a ${fecha_fin}`, 'success')
+            periodo.periodo_fecha_fin = fecha_fin
+        } else {
+            this.addMessage('Error al cambiar fecha de fin', `No se pudo cambiar la fecha de fin del periodo ${periodo.periodo_nombre}`, 'danger')
+        }
+    },
+
+
+    async updatePeriodo(periodo: Periodo) {
+        const result = await this.sendRequest('updatePeriodo', periodo.periodo_id, {
+            periodo_nombre: periodo.periodo_nombre,
+            id_periodo_sgu: periodo.id_periodo_sgu,
+            periodo_clave: periodo.periodo_clave,
+        })
+        if (result.success) {
+            this.addMessage('Periodo actualizado', `El periodo ${periodo.periodo_nombre} ha sido actualizado`, 'success')
+        } else {
+            this.addMessage('Error al actualizar periodo', `No se pudo actualizar el periodo ${periodo.periodo_nombre}`, 'danger')
+        }
+    },
+
+
+    async createPeriodo(newPeriodo: Periodo) {
+
+        if (newPeriodo.periodo_nombre === null || newPeriodo.nivel_id === null || newPeriodo.periodo_fecha_inicio === null || newPeriodo.periodo_fecha_fin === null) {
+            this.addMessage('Error al crear periodo', `No se pudo crear el periodo ${newPeriodo.periodo_nombre}`, 'danger')
+            return
+        }
+
+        const result = await fetch('action/periodos.php', {
+            method: 'POST',
+            headers: {
+                'Content-Type': 'application/json'
+            },
+            body: JSON.stringify(newPeriodo)
+        }).then(res => res.json())
+
+        if (result.success) {
+            this.addMessage('Periodo creado', `El periodo ${newPeriodo.periodo_nombre} ha sido creado`, 'success')
+
+            this.periodos
+            Object.keys(newPeriodo).forEach(key => newPeriodo[key] = null);
+            newPeriodo.nivel_id = '';
+            this.periodos = await fetch('action/periodos.php').then(res => res.json())
+        } else {
+            this.addMessage('Error al crear periodo', `No se pudo crear el periodo ${newPeriodo.periodo_nombre}`, 'danger')
+        }
+    },
+
+    async deletePeriodo(periodo: Periodo) {
+        const response = await fetch('action/periodos.php', {
+            method: 'DELETE',
+            headers: {
+                'Content-Type': 'application/json'
+            },
+            body: JSON.stringify({
+                periodo_id: periodo.periodo_id,
+            })
+        })
+        const result = await response.json()
+
+        if (result.success) {
+            this.addMessage('Periodo eliminado', `El periodo ${periodo.periodo_nombre} ha sido eliminado`, 'success')
+            this.periodos = this.periodos.filter((p: Periodo) => p.periodo_id !== periodo.periodo_id)
+        } else {
+            this.addMessage('Error al eliminar periodo', `No se pudo eliminar el periodo ${periodo.periodo_nombre}`, 'danger')
+        }
+    },
+
+    async mounted() {
+        this.periodos = await fetch('action/periodos.php').then(res => res.json())
+        this.niveles = await fetch('action/nivel.php').then(res => res.json())
+    }
+}).mount('#app') 

+ 106 - 0
ts/puestos.ts

@@ -0,0 +1,106 @@
+import { createApp, reactive } from 'https://unpkg.com/petite-vue?module'
+type Puesto = {
+    puesto_id: number,
+    nombre: string,
+    facultad_id: number,
+}
+
+type Carrera = {
+    carrera_id: number;
+    carrera_nombre: string;
+    clave_carrera: string;
+}
+
+type Materia = {
+    carrera_id: number;
+    clave_materia: string;
+    materia_id: number;
+    materia_nombre: string;
+}
+
+type Usuario = {
+    usuario_clave: string;
+    usuario_id: number;
+    usuario_nombre: string;
+}
+
+const app = createApp({
+    message: null,
+    puestos: [] as Puesto[],
+    carreras: [] as Carrera[],
+    materias: [] as Materia[],
+    usuarios: [] as Usuario[],
+
+    async nuevoPuesto(nuevoPuesto: string) {
+        try {
+            const res = await fetch('action/puesto.php', {
+                method: 'POST',
+                body: JSON.stringify({
+                    puesto_nombre: nuevoPuesto
+                })
+            })
+            const data = await res.json()
+            this.puestos.push(data)
+            // order by puesto.nombre
+            this.puestos.sort((a: Puesto, b: Puesto) => a.nombre.localeCompare(b.nombre))
+        } catch (error) {
+            alert(`Error: ${error}`)
+
+        }
+    },
+
+    to_delete: null as Puesto | null,
+    async eliminarPuesto(puesto_id: number) {
+        try {
+            const res = await fetch('action/puesto.php', {
+                method: 'DELETE',
+                body: JSON.stringify({
+                    puesto_id
+                })
+            })
+            const data = await res.json()
+            this.message = data.msg;
+
+            // after 3 seconds, remove the message
+            setTimeout(() => {
+                this.message = null
+            }, 3000)
+
+            this.puestos = this.puestos.filter((p: Puesto) => p.puesto_id !== puesto_id)
+            // order by puesto.nombre
+            this.puestos.sort((a: Puesto, b: Puesto) => a.nombre.localeCompare(b.nombre))
+        } catch (error) {
+            alert(`Error: ${error}`)
+
+        }
+    },
+
+    async actualizarPuesto(puesto_id: number, materias: Materia[], usuario_id: number | null) {
+        try {
+            const res = await fetch('action/puesto.php', {
+                method: 'PUT',
+                body: JSON.stringify({
+                    puesto_id,
+                    materias: materias.map(m => m.materia_id),
+                    usuario_id
+                })
+            })
+            const data = await res.json()
+            this.message = data.msg;
+
+            // after 3 seconds, remove the message
+            setTimeout(() => {
+                this.message = null
+            }, 3000)
+        } catch (error) {
+            alert(`Error: ${error}`)
+        }
+    },
+
+    async mounted() {
+        this.puestos = await fetch('action/puesto.php').then(res => res.json())
+        this.carreras = await fetch('action/action_carreras.php').then(res => res.json())
+        this.materias = await fetch('action/action_materias.php').then(res => res.json())
+        this.usuarios = await fetch('action/usuarios.php').then(res => res.json())
+    }
+}).mount('#app')

+ 272 - 0
ts/reposiciones.ts

@@ -0,0 +1,272 @@
+import { type } from "os";
+
+declare function triggerMessage(message: string, title: string, type?: string): void;
+declare const write: boolean;
+declare const moment: any;
+// from this 'horario_id', 'fecha', 'hora', 'duracion_id', 'descripcion', 'profesor_id', 'salon', 'unidad', 'periodo_id', 'fecha_clase' make a type of ReposicionParams
+export interface ReposicionParams {
+    horario_id: number;
+    fecha: string;
+    hora: string;
+    duracion_id: number;
+    descripcion: string;
+    profesor_id: number;
+    salon: string;
+    unidad: number;
+    periodo_id: number;
+    fecha_clase: string;
+}
+
+type Horario = {
+    id: number;
+    carrera_id: number;
+    materia_id: number;
+    grupo: string;
+    profesores: Profesor[];
+    dia: string;
+    hora: string;
+    hora_final: string;
+    salon: string;
+    fecha_inicio: string;
+    fecha_final: string;
+    fecha_carga: string;
+    nivel_id: number;
+    periodo_id: number;
+    facultad_id: number;
+    materia: string;
+    horas: number;
+    minutos: number;
+    duracion: number;
+    retardo: boolean;
+    original_id: number;
+    last: boolean;
+    bloques: number;
+};
+
+type Profesor = {
+    id: number;
+    clave: string;
+    grado: string;
+    profesor: string;
+    nombre: string;
+    facultad_id: number;
+};
+// Get references to the HTML elements
+const form = document.getElementById('form') as HTMLFormElement;
+const steps = Array.from(form.querySelectorAll('.step')) as HTMLElement[];
+
+const nextButton = document.getElementById('next-button') as HTMLButtonElement;
+const prevButton = document.getElementById('prev-button') as HTMLButtonElement;
+
+let currentStep = 0;
+
+// #clave_profesor on change => show step 2
+const clave_profesor = document.getElementById('clave_profesor') as HTMLInputElement;
+const horario_reponer = document.getElementById('horario_reponer') as HTMLInputElement;
+const fechas_clase = document.getElementById('fechas_clase') as HTMLInputElement;
+
+const fecha_reponer = $('#fecha_reponer') as JQuery<HTMLElement>;
+const hora_reponer = $('#hora_reponer') as JQuery<HTMLElement>;
+const minutos_reponer = $('#minutos_reponer') as JQuery<HTMLElement>;
+
+clave_profesor.addEventListener('change', async () => {
+    const step2 = document.getElementById('step-2') as HTMLElement;
+    clave_profesor.disabled = true;
+    // get option which value is the same as clave_profesor.value
+    const option = document.querySelector(`option[value="${clave_profesor.value}"]`) as HTMLOptionElement;
+
+    // make a form data with #form
+    const profesor_id = document.getElementById('profesor_id') as HTMLInputElement;
+    profesor_id.value = option.dataset.id;
+
+    const formData = new FormData(form);
+
+    const response = await fetch(`./action/action_horario_profesor.php`, {
+        method: 'POST',
+        body: formData
+    });
+    const data = await response.json();
+    if (data['success'] === false) {
+        const message = "Hubo un error al obtener los horarios del profesor."
+        const title = 'Error';
+        const color = 'danger';
+        triggerMessage(message, title, color);
+        return;
+    }
+    const horarios = data.data as Horario[];
+    const initial = document.createElement('option');
+    initial.value = '';
+    initial.textContent = 'Seleccione un horario';
+    initial.selected = true;
+    initial.disabled = true;
+    horario_reponer.innerHTML = '';
+    horario_reponer.appendChild(initial);
+
+    horarios.forEach((horario) => {
+        const dias = ['Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado', 'Domingo'];
+        const option = document.createElement('option');
+        option.value = `${horario.id}`;
+        // materia máx 25 caracteres, if materia.length > 25 then slice(0, 20)
+        const max = 25;
+        option.textContent = `${horario.materia.slice(0, max) + (horario.materia.length > max ? '...' : '')} - Grupo: ${horario.grupo} - ${horario.hora.slice(0, 5)}-${horario.hora_final.slice(0, 5)} - Salon: ${horario.salon} - ${horario.dia}`;
+
+        option.dataset.materia = `${horario.materia}`;
+        option.dataset.grupo = `${horario.grupo}`;
+        option.dataset.hora = `${horario.hora.slice(0, 5)}`; // slice(0, 5) => HH:MM
+        option.dataset.hora_final = `${horario.hora_final.slice(0, 5)}`;
+        option.dataset.salon = `${horario.salon}`;
+        option.dataset.dia = `${horario.dia}`;
+
+        option.dataset.id = `${horario.id}`;
+        horario_reponer.appendChild(option);
+    });
+    currentStep = 1;
+    step2.style.display = 'block';
+    prevButton.disabled = false;
+});
+// disable clave_profesor
+
+// from second step to first step
+prevButton.addEventListener('click', () => {
+    const inputs = [clave_profesor, horario_reponer, fechas_clase, fecha_reponer, hora_reponer] as HTMLInputElement[];
+    switch (currentStep) {
+        case 1:
+        case 2:
+        case 3:
+            const step = document.getElementById(`step-${currentStep + 1}`) as HTMLElement;
+            step.style.display = 'none';
+            inputs[currentStep - 1].disabled = false;
+            inputs[currentStep - 1].value = '';
+            if (--currentStep === 0) {
+                prevButton.disabled = true;
+            }
+            break;
+        case 4:
+            const step5 = document.getElementById('step-5') as HTMLElement;
+            step5.style.display = 'none';
+            fecha_reponer.prop('disabled', false);
+            fecha_reponer.val('');
+
+            hora_reponer.parent().removeClass('disabled');
+            hora_reponer.siblings('.datalist-input').text('hh');
+            hora_reponer.val('');
+
+            minutos_reponer.parent().removeClass('disabled');
+            minutos_reponer.siblings('.datalist-input').text('mm');
+            minutos_reponer.val('');
+
+            currentStep--;
+            break;
+    }
+
+    nextButton.disabled = true;
+
+});
+
+// #horario_reponer on change => show step 3
+horario_reponer.addEventListener('change', async () => {
+    const selected = horario_reponer.querySelector(`option[value="${horario_reponer.value}"]`) as HTMLOptionElement;
+    horario_reponer.title = `Materia: ${selected.dataset.materia} - Grupo: ${selected.dataset.grupo} - Horario: ${selected.dataset.hora}-${selected.dataset.hora_final} - Salon: ${selected.dataset.salon} - Día: ${selected.dataset.dia}`;
+    const step3 = document.getElementById('step-3') as HTMLElement;
+    horario_reponer.disabled = true;
+    // make a form data with #form
+    const response = await fetch(`./action/action_fechas_clase.php?horario_id=${horario_reponer.value}`, {
+        method: 'GET',
+    });
+
+    const data = await response.json();
+    if (data['success'] === false) {
+        const message = "Hubo un error al obtener las fechas de clase."
+        const title = 'Error';
+        const color = 'danger';
+        triggerMessage(message, title, color);
+        return;
+    }
+    type Fecha = {
+        fecha: string;
+        dia_mes: number;
+        day: number;
+        month: number;
+        year: number;
+    }
+
+    const meses = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
+
+    const fechas = data.data as Fecha[];
+    const initial = document.createElement('option');
+    initial.value = '';
+    initial.textContent = 'Seleccione la fecha de la falta';
+    initial.selected = true;
+    initial.disabled = true;
+    fechas_clase.innerHTML = '';
+    fechas_clase.appendChild(initial);
+    fechas_clase.title = 'Seleccione la fecha de la falta';
+
+    fechas.forEach((fecha) => {
+        const option = document.createElement('option');
+        option.value = `${fecha}`;
+        option.textContent = `${fecha.dia_mes} de ${meses[fecha.month - 1]} de ${fecha.year}`;
+        fechas_clase.appendChild(option);
+    });
+
+
+    step3.style.display = 'block';
+    currentStep = 2;
+});
+
+// #fechas_clase on change => show step 4
+fechas_clase.addEventListener('change', () => {
+    const step4 = document.getElementById('step-4') as HTMLElement;
+    step4.style.display = 'block';
+    fechas_clase.disabled = true;
+    currentStep = 3;
+});
+
+// when both #fecha_reponer and #hora_reponer are selected => show step 5
+
+const lastStep = () => {
+    // timeout to wait for the value to be set 
+    setTimeout(() => {
+        if (fecha_reponer.val() !== '' && hora_reponer.val() !== '' && minutos_reponer.val() !== '') {
+            const step5 = document.getElementById('step-5') as HTMLElement;
+            step5.style.display = 'block';
+            // disable both
+            fecha_reponer.prop('disabled', true);
+            hora_reponer.parent().addClass('disabled');
+            minutos_reponer.parent().addClass('disabled');
+
+            const nextButton = document.getElementById('next-button') as HTMLButtonElement;
+            // remove property disabled
+            nextButton.removeAttribute('disabled');
+            currentStep = 4;
+        }
+    }, 100);
+}
+fecha_reponer.on('change', lastStep);
+// on click on the sibling ul>li of #hora_reponer and #minutos_reponer
+
+hora_reponer.siblings('ul').children('li').on('click', lastStep);
+minutos_reponer.siblings('ul').children('li').on('click', lastStep);
+
+// Initialize the form
+hideSteps();
+showCurrentStep();
+
+
+function hideSteps() {
+    steps.forEach((step) => {
+        step.style.display = 'none';
+    });
+}
+
+function showCurrentStep() {
+    steps[currentStep].style.display = 'block';
+    prevButton.disabled = currentStep === 0;
+}
+
+function handleSubmit(event: Event) {
+    event.preventDefault();
+
+    // Handle form submission
+    // You can access the form data using the FormData API or serialize it manually
+}

+ 14 - 0
tsconfig.json

@@ -0,0 +1,14 @@
+{
+    "compilerOptions": {
+        "lib": [
+            "ESNext",
+            "dom"
+        ],
+        "outDir": "js",
+        "rootDir": "ts",
+        "target": "ES2022",
+        "moduleResolution": "node",
+        "module": "ESNext",
+        // ts/auditoría.ts:1:37 - error TS2307: Cannot find module 'https://unpkg.com/petite-vue?module' or its corresponding type declarations.
+    }
+}