Initial Commit

This commit is contained in:
Cloud User
2024-03-06 17:45:49 -06:00
commit 8986493161
250 changed files with 43078 additions and 0 deletions

View File

@@ -0,0 +1,39 @@
<?php
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
$user = Login::get_user();
extract($_POST);
$initial_date = DateTime::createFromFormat('d/m/Y', $fecha_inicial);
$final_date = DateTime::createFromFormat('d/m/Y', $fecha_final);
if ($initial_date > $final_date) {
echo json_encode(['error' => 'La fecha inicial no puede ser mayor a la fecha final']);
die;
}
// Nombre del profesor es opcional
$params = [
':carrera' => empty($carrera) ? null : $carrera,
':periodo' => $periodo,
':nombre' => empty($nombre) ? null : $nombre,
':clave' => empty($clave) ? null : $clave,
':initial_date' => $initial_date->format('Y-m-d'),
':final_date' => $final_date->format('Y-m-d'),
':facultad' => $facultad,
];
$response = json_encode(
[
"retardo" => query("SELECT FS_HAS_RETARDO(:facultad) retardo", [
'facultad' => $facultad
]),
"reporte" => queryAll(
"SELECT * FROM fs_asistencia_reporte(:carrera, :periodo, :clave, :nombre, :facultad, :initial_date, :final_date) where total > 0",
$params
)
]
);
$user->print_to_log("Genera reporte de asistencias", old: $params);
echo $response;

View File

@@ -0,0 +1,98 @@
<?php
$ruta = "../";
require_once "../vendor/autoload.php";
require_once "../class/c_login.php";
$user = Login::get_user();
$user->print_to_log('Genera excel de asistencias');
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());
// In POST
/** Array
* * nombre
* * clave
* * id
* * total
* * asistencias
* * faltas
* * justificaciones
* * retardos
*/
$retardo = query("SELECT COALESCE(FS_HAS_RETARDO(:facultad), FALSE) AS retardo", [':facultad' => $user->facultad['facultad_id']])['retardo'];
extract($_POST);
$row = 6;
$sheet->setCellValue("A$row", 'Clave');
$sheet->setCellValue("B$row", 'Profesor');
$sheet->setCellValue("C$row", 'Asistencias');
$sheet->setCellValue("D$row", 'Faltas');
$sheet->setCellValue("E$row", 'Justificaciones');
$sheet->setCellValue("F$row", 'Retardos');
$sheet->setCellValue("G$row", 'Total');
// $row++;
$col = 0;
# die(print_r($asistencias, true));
foreach (json_decode($asistencias, true) as $profesor) {
$row++;
$sheet->setCellValue("A$row", $profesor['profesor_clave']);
$sheet->setCellValue("B$row", $profesor['profesor_nombre']);
$sheet->setCellValue("C$row", $profesor['asistencias']);
$sheet->setCellValue("D$row", $profesor['faltas']);
$sheet->setCellValue("E$row", $profesor['justificaciones']);
$sheet->setCellValue("F$row", $profesor['retardos']);
$sheet->setCellValue("G$row", $profesor['total']);
}
# Style
$sheet->getStyle("A6:G$row")->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
$sheet->getStyle("A6:G$row")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
$sheet->getStyle("A6:G$row")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$sheet->getStyle("A6:G$row")->getAlignment()->setWrapText(true);
$sheet->getStyle("A6:G$row")->getFont()->setSize(12);
$sheet->getStyle("A6:G$row")->getFont()->setName('Indivisa Sans');
# Autosize columns
foreach (range('A', 'G') as $column) {
$sheet->getColumnDimension($column)->setAutoSize(true);
}
# filters in the column
$sheet->setAutoFilter("A6:G6");
if (!$retardo) # hide column
$sheet->getColumnDimension('F')->setVisible(false);
#$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');

128
action/action_auditoria.php Normal file
View File

@@ -0,0 +1,128 @@
<?
#input $_GET['id_espacio_sgu']
#output rutas: [ ...ruta, salones: [{...salon}] ]
header('Content-Type: application/json charset=utf-8');
ini_set('memory_limit', '500M');
ini_set('post_max_size', '500M');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ruta = "../";
require_once $ruta . "class/c_login.php";
if (!isset($_SESSION['user'])) {
http_response_code(401);
die(json_encode(['error' => 'unauthorized']));
}
$user = unserialize($_SESSION['user']);
// check method
try {
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$baseDate = $_GET['fecha'] ?? $_GET['fecha_fin'] ?? null;
$params = [
':periodo_id' => $_GET['periodo_id'] == 1 ? $user->periodo_id : null,
':facultad_id' => $user->facultad['facultad_id'],
':fecha_inicio' => $_GET['fecha'] ?? $_GET['fecha_inicio'] ?? date('Y-m-d'),
':fecha_fin' => $baseDate ? date('Y-m-d H:i:s', strtotime($baseDate . ' +24 hours')) : date('Y-m-d H:i:s'),
];
$data = $db->query(
"WITH horarios AS (
SELECT
horario_id,
horario.facultad_id,
horario_fecha_inicio,
horario_fecha_fin,
horario_grupo,
horario_hora,
PERIODO.periodo_fecha_inicio,
PERIODO.periodo_fecha_fin,
salon,
COALESCE(materia_nombre, materia_asignacion_materia) as materia,
coalesce(carrera_nombre, materia_asignacion_carrera) as carrera,
facultad_nombre as facultad,
nivel_nombre as nivel,
horario_fin
FROM horario
left JOIN materia USING (materia_id)
left join carrera using (carrera_id)
left join materia_asignacion using (horario_id)
join facultad on facultad.facultad_id = horario.facultad_id
JOIN PERIODO USING (periodo_id)
JOIN nivel on periodo.nivel_id = nivel.nivel_id
JOIN SALON USING (salon_id)
WHERE (PERIODO.periodo_id, horario.facultad_id) = (COALESCE(:periodo_id, PERIODO.periodo_id), COALESCE(:facultad_id, horario.facultad_id))
),
fechas AS (
SELECT fechas_clase(h.horario_id, true) as registro_fecha_ideal, h.horario_id
FROM horarios h
)
SELECT
usuario.usuario_nombre,
registro.registro_id,
registro.registro_fecha,
registro.registro_retardo,
registro.registro_justificada,
registro_fecha_supervisor,
justificacion,
comentario,
registro_fecha_justificacion,
profesor.profesor_id, profesor_nombre, profesor_clave, profesor_correo,
horario_id,
materia, carrera, horarios.facultad_id, facultad, nivel, horario_hora, horario_fin, horario_grupo, horarios.salon,
fechas.registro_fecha_ideal,
estado_supervisor.estado_supervisor_id as estado_supervisor_id,
estado_supervisor.nombre as nombre,
estado_supervisor.estado_color as estado_color,
estado_supervisor.estado_icon as estado_icon,
justificador.usuario_nombre as justificador_nombre,
justificador.usuario_clave as justificador_clave,
facultad.facultad_nombre as justificador_facultad,
rol.rol_titulo as justificador_rol,
registro.reposicion_id,
reposicion_fecha,
reposicion_hora,
salon_reposicion.salon as reposicion_salon,
CASE WHEN registro_retardo THEN 'warning' ELSE 'primary' END as color
FROM horarios
JOIN fechas using (horario_id)
JOIN horario_profesor using (horario_id)
JOIN profesor using (profesor_id)
LEFT JOIN registro USING (horario_id, registro_fecha_ideal, profesor_id)
LEFT JOIN reposicion USING (reposicion_id)
LEFT JOIN salon as salon_reposicion ON salon_reposicion.salon_id = reposicion.salon_id
join estado_supervisor ON estado_supervisor.estado_supervisor_id = COALESCE(registro.estado_supervisor_id, 0)
LEFT JOIN USUARIO ON USUARIO.usuario_id = REGISTRO.supervisor_id
LEFT JOIN USUARIO JUSTIFICADOR ON JUSTIFICADOR.usuario_id = REGISTRO.justificador_id
LEFT JOIN ROL on ROL.rol_id = justificador.rol_id
left join facultad on facultad.facultad_id = justificador.facultad_id
WHERE (fechas.registro_fecha_ideal + HORARIO_HORA) BETWEEN
GREATEST(HORARIO_FECHA_INICIO, PERIODO_FECHA_INICIO, :fecha_inicio) AND LEAST(PERIODO_FECHA_FIN, HORARIO_FECHA_FIN, :fecha_fin)
ORDER BY fechas.registro_fecha_ideal DESC, horarios.horario_id, profesor_nombre",
$params
);
$db->delete('general_log');
$db->insert('general_log', [
'general_log_json' => json_encode($params, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT),
]);
echo json_encode(array_merge($data), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} else {
http_response_code(405);
echo json_encode(['error' => 'method not allowed']);
exit;
}
} catch (PDOException $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
// 'query' => $db->getLastQuery(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_PARTIAL_OUTPUT_ON_ERROR);
exit;
} catch (Exception $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
}

52
action/action_avisos.php Normal file
View File

@@ -0,0 +1,52 @@
<?
#input $_GET['id_espacio_sgu']
#output rutas: [ ...ruta, salones: [{...salon}] ]
header('Content-Type: application/json charset=utf-8');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ruta = "../";
require_once $ruta . "class/c_login.php";
if (!isset($_SESSION['user'])) {
http_response_code(401);
die(json_encode(['error' => 'unauthorized']));
}
$user = unserialize($_SESSION['user']);
// check method
try {
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$data = $db->query(
'SELECT * FROM AVISO',
[
':facultad_id' => $user->facultad['facultad_id'],
':fecha_inicio' => $_GET['fecha'] ?? $_GET['fecha_inicio'] ?? null,
':fecha_fin' => $_GET['fecha'] ?? $_GET['fecha_fin'] ?? null,
]
);
$last_query = [
'query' => $db->getLastQuery(),
];
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} else {
http_response_code(405);
echo json_encode(['error' => 'method not allowed']);
exit;
}
} catch (PDOException $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
'query' => $db->getLastQuery(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_PARTIAL_OUTPUT_ON_ERROR);
exit;
} catch (Exception $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
}

View File

@@ -0,0 +1,27 @@
<?php
header('Content-Type: application/json');
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
$ruta = "../";
require_once "../include/bd_pdo.php";
$facultad_id = $user->facultad['facultad_id'];
$carreras = $db->query(
"SELECT carrera_id, carrera_nombre, clave_carrera
FROM carrera
WHERE
(facultad_id = :facultad_id OR :facultad_id IS NULL)
ORDER BY carrera_nombre DESC",
array('facultad_id' => $facultad_id)
);
// $user->print_to_log("Crea carrera", old: $_POST);
die(json_encode($carreras));

View File

@@ -0,0 +1,19 @@
<?php
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
$ruta = "../";
require_once "../include/bd_pdo.php";
$sql = "SELECT fi_carrera(:nombre, :idfacultad, :idnivel, true, :estado)";
$params = [':nombre' => mb_strtoupper($_POST['nombre']), ':idfacultad' => $_POST['facultad'], ':idnivel' => $_POST['nivel'], ':estado' => $_POST['estado']];
print_r($_POST);
echo json_encode(query($sql, $params, true));
$user->print_to_log("Crea carrera", new: $params);
header("Location: ../carreras.php?facultad=" . $_POST['facultad']);
exit();

View File

@@ -0,0 +1,16 @@
<?php
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
$ruta = "../";
require_once "../include/bd_pdo.php";
global $pdo;
$sql = "SELECT * FROM fs_carreras(:idfacultad, :idcarrera, null)";
$params = [':idfacultad' => $_POST['idfacultad'], ':idcarrera' => $_POST['idcarrera']];
$user->print_to_log("Crea carrera", old: $params);
echo json_encode(query($sql, $params, true));

View File

@@ -0,0 +1,19 @@
<?php
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
$ruta = "../";
require_once "../include/bd_pdo.php";
$old = query("SELECT * FROM FS_CARRERA WHERE ID = :id", [':id' => $_POST['id']]);
$sql = "SELECT fu_updatecarrera(:idcarrera, :nombre, :activa, :idnivel)";
print_r($_POST);
$params = [':idcarrera' => $_POST['id'], ':nombre' => mb_strtoupper($_POST['nombre']), ':activa' => $_POST['estado'], ':idnivel' => $_POST['nivel']];
query($sql, $params, true);
$user->print_to_log("Actualiza carrera.", old: $old, new: $params);
header("Location: ../carreras.php?facultad=" . $_POST['facultad']);
exit();

View File

@@ -0,0 +1,15 @@
<?php
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
$ruta = "../";
require_once "../include/bd_pdo.php";
#$sql = "SELECT * FROM diasfestivos WHERE diasfestivos_id = :id";
$sql = "DELETE FROM diasfestivos WHERE diasfestivos_id = :id";
$params = [':id' => $_POST['id']];
echo json_encode(query($sql, $params, false));

View File

@@ -0,0 +1,57 @@
<?php
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
$ruta = "../";
require_once "../include/bd_pdo.php";
global $pdo;
//print_r($_POST);
if (!isset($_POST['periodo']) || count($_POST["periodo"])==0) {
header("Location: ../días_festivos.php?error=0");
exit();
}
$periodoArr = $_POST['periodo'];
if (isset($_POST['rango'])) {
$diaInicio = new DateTime(date("Y-m-d", strtotime(str_replace("/", "-", $_POST['diaFestivo']))));
$diaFin = new DateTime(date("Y-m-d", strtotime(str_replace("/", "-", $_POST['diaFestivoFin']))));
$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]);
/*$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");
exit();
} else {
/*$sql = "SELECT * FROM fs_diasfestivos(null, :dia)";
$params = [':dia' => $_POST['diaFestivo']];
$dia_general = query($sql, $params, false);
$sql = "SELECT * FROM fs_diasfestivos(null, null, :periodo, :dia)";
$params = [':periodo' => $periodo, ":dia" => $_POST['diaFestivo']];
$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']]);
/*$sql = "SELECT fi_diasfestivos(:periodo, :dia)";
$params = [':periodo' => $periodo, ":dia" => $_POST['diaFestivo']];
$id = query($sql, $params, false);*/
}
header("Location: ../días_festivos.php");
exit();
/*} else {
header("Location: ../días_festivos.php?error=1");
exit();
}*/
}

View File

@@ -0,0 +1,19 @@
<?php
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
$ruta = "../";
require_once "../include/bd_pdo.php";
global $pdo;
$params = [':id' => $_POST['id']];
if ($_POST['periodo'] == 0) {
$sql = "SELECT * FROM fs_diasfestivos(:id, null)";
} else {
$sql = "SELECT * FROM fs_diasfestivos(null, :id, null, null)";
}
echo json_encode(query($sql, $params, true));

View File

@@ -0,0 +1,31 @@
<?php
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
$ruta = "../";
require_once "../include/bd_pdo.php";
global $pdo;
if ($_POST['periodo'] == 0) {
$periodo = null;
} else
$periodo = $_POST['periodo'];
$sql = "SELECT * FROM fs_diasfestivos(null, :dia) WHERE diasfestivos_id != :id";
$params = [':dia' => $_POST['diaFestivo'], ':id' => $_POST['id']];
$dia_general = query($sql, $params, false);
$sql = "SELECT * FROM fs_diasfestivos(null, null, :periodo, :dia) WHERE diasfestivos_id != :id";
$params = [':periodo' => $periodo, ':dia' => $_POST['diaFestivo'], ':id' => $_POST['id']];
$dia = query($sql, $params, false);
if (!$dia && !$dia_general) { //no hay repetidos
$sql = "SELECT fu_update_diasfestivos(:id, :dia, :periodo)";
query($sql, $params, false);
header("Location: ../días_festivos.php");
exit();
} else { //es repetido
header("Location: ../días_festivos.php?error=1");
exit();
}

View File

@@ -0,0 +1,42 @@
<?
#input $_GET['id_espacio_sgu']
define("INFORMATION", [
'GET' => [
],
]);
#output rutas: [ ...ruta, salones: [{...salon}] ]
header('Content-Type: application/json charset=utf-8');
#return html
$ruta = "../";
require_once "../class/c_login.php";
// check method
try {
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
// check parameters
$raw = file_get_contents('php://input');
$post_get = json_decode($raw, true);
$data = $db->get('estado_supervisor');
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} else {
http_response_code(405);
echo json_encode(['error' => 'method not allowed']);
exit;
}
} catch (PDOException $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
'query' => $db->getLastQuery(),
'post_data' => $post_get,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
} catch (Exception $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
}

View File

@@ -0,0 +1,57 @@
<?
$information = [
'GET' => [],
];
header('Content-Type: application/json charset=utf-8');
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (!isset($_SESSION['user'])) {
http_response_code(500);
echo json_encode([
'error' => 'No se ha iniciado sesión'
]);
exit;
}
$user = unserialize($_SESSION['user']);
try {
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
// check parameters
array_walk($information['GET'], function ($value) {
if (!array_key_exists($value, $_GET)) {
http_response_code(400);
echo json_encode(['error' => "$value is required"]);
exit;
}
});
$data = $db->query(<<<SQL
SELECT facultad_nombre, facultad_id, clave_dependencia
FROM facultad
WHERE facultad_id = :facultad_id OR :facultad_id IS NULL
ORDER BY facultad_nombre ASC
SQL
,
[':facultad_id' => $user->facultad['facultad_id']]
);
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} else {
http_response_code(405);
echo json_encode(['error' => 'method not allowed']);
exit;
}
} catch (PDOException $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
'query' => $db->getLastQuery(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
} catch (Exception $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
}

View File

@@ -0,0 +1,23 @@
<?php
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
$ruta = "../";
require_once "../include/bd_pdo.php";
global $pdo;
$sql = "SELECT fi_facultad(:nombre, :activa)";
$params = [':nombre' => mb_strtoupper($_POST['nombre']), ':activa' => $_POST['estado']];
$fac_id = query($sql, $params, true);
$sql = "SELECT fi_tiempo_checado(:idfacultad, :idnivel, :antes, :despues, :retardo)";
$params = [':idfacultad' => $fac_id['fi_facultad'], ':idnivel' => 1, ':antes' => -15, ':despues' => 16, ':retardo' => 31];
query($sql, $params, false);
$params = [':idfacultad' => $fac_id['fi_facultad'], ':idnivel' => 2, ':antes' => -15, ':despues' => 16, ':retardo' => 31];
query($sql, $params, false);
print_r($fac_id);
header("Location: ../carreras.php?facultad=" . $fac_id['fi_facultad']);
exit();

View File

@@ -0,0 +1,15 @@
<?php
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
$ruta = "../";
require_once "../include/bd_pdo.php";
global $pdo;
$sql = "SELECT * FROM facultad WHERE facultad_id = :idFacultad";
$params = [':idFacultad' => $_POST['id_facultad']];
echo json_encode(query($sql, $params, false));

View File

@@ -0,0 +1,17 @@
<?php
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
$ruta = "../";
require_once "../include/bd_pdo.php";
global $pdo;
$sql = "SELECT fu_updatefacultad(:nombre, :activa, :id)";
$params = [':nombre' => mb_strtoupper($_POST['nombre']), ':activa' => $_POST['estado'], ':id' => $_POST['id']];
query($sql, $params, false);
header("Location: ../facultades.php");
exit();

View File

@@ -0,0 +1,26 @@
<?php
$ruta = "../";
require_once "../class/c_login.php";
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
$ruta = "../";
require_once "../include/bd_pdo.php";
// if method is get
header("Content-Type: application/json");
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$user->print_to_log("Acceso a reposiciones");
if (empty($_GET['horario_id']))
die(json_encode(['error' => 'No se ha enviado el id del horario']));
// fecha greater than today
$reposiciones = $db->query("SELECT fecha, EXTRACT(DOW FROM fecha) as day, EXTRACT(MONTH FROM fecha) as month, EXTRACT(YEAR FROM fecha) as year, EXTRACT(DAY FROM fecha) as dia_mes FROM fechas_clase(:horario_id) WHERE fecha > CURRENT_DATE", [
'horario_id' => $_GET['horario_id']
]);
echo json_encode([
'status' => 'success',
'data' => $reposiciones
]);
}

46
action/action_grupo.php Normal file
View File

@@ -0,0 +1,46 @@
<?php
header('Content-Type: application/json');
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (Login::is_logged())
$user = Login::get_user();
else {
header('HTTP/1.1 401 Unauthorized');
echo json_encode(['error' => 'No se ha iniciado sesión']);
exit();
}
$ruta = "../";
require_once("../include/bd_pdo.php");
if (!isset($_GET['carrera_id'])) {
echo json_encode([
'status' => 'error',
'error' => 'No se ha especificado una carrera'
]);
exit();
}
try {
$grupos = $db->query(<<<SQL
SELECT distinct substring(horario_grupo, 7, 3)::int - 1 as horario_grupo FROM horario_view WHERE
PERIODO_ID = :periodo_id AND
(FACULTAD_ID = :facultad_id OR :facultad_id IS NULL) AND
CARRERA_ID = :carrera_id
GROUP BY horario_grupo
ORDER BY horario_grupo ASC
SQL,
[
':periodo_id' => $user->periodo_id,
':facultad_id' => $user->facultad['facultad_id'],
':carrera_id' => $_GET['carrera_id'] ?? 0
]
);
} catch (PDOException $ex) {
echo json_encode([]);
exit();
}
echo json_encode(array_map(fn($grupo) => $grupo['horario_grupo'], $grupos));

View File

@@ -0,0 +1,28 @@
<?php
header('Content-Type: application/json');
$ruta = "../";
require_once("../include/bd_pdo.php");
$grupo = isset($_GET['grupo']) ? $_GET['grupo'] : 1;
$grupo_horarios = $db->querySingle(
"WITH bloques AS (
SELECT id, hora_inicio, hora_fin
FROM public.bloque_horario
WHERE grupo = ?
ORDER BY hora_inicio ASC
)
SELECT json_agg(json_build_object(
'id', id,
'hora_inicio', hora_inicio,
'hora_fin', hora_fin,
'selected', current_time between hora_inicio and hora_fin
)) AS bloque_horario
FROM bloques
",
[$grupo]
)['bloque_horario'];
echo $grupo_horarios;

70
action/action_horario.php Normal file
View File

@@ -0,0 +1,70 @@
<?
#input $_GET['id_espacio_sgu']
#output rutas: [ ...ruta, salones: [{...salon}] ]
header('Content-Type: application/json charset=utf-8');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ruta = "../";
require_once $ruta . "class/c_login.php";
if (!isset($_SESSION['user'])) {
http_response_code(401);
die(json_encode(['error' => 'unauthorized']));
}
$user = unserialize($_SESSION['user']);
// check method
try {
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
if (!(isset($_GET['profesor_id']) || isset($_GET['grupo']))) {
throw new Exception('missing parameters');
}
if (isset($_GET['profesor_id'])) {
$data = $db->query(
"SELECT *, (EXTRACT(EPOCH FROM (horario_fin - horario_hora) ) / EXTRACT(EPOCH FROM interval '15 minute'))::INT AS bloques
FROM horario_view
JOIN horario_profesor ON horario_profesor.horario_id = horario_view.horario_id
WHERE horario_profesor.profesor_id = :profesor_id
AND (facultad_id = :facultad_id OR :facultad_id IS NULL)",
[
'profesor_id' => $_GET['profesor_id'],
'facultad_id' => $user->facultad['facultad_id'],
]
);
} else if (isset($_GET['grupo'])) {
$data = $db->query(
"SELECT *, (EXTRACT(EPOCH FROM (horario_fin - horario_hora) ) / EXTRACT(EPOCH FROM interval '15 minute'))::INT AS bloques
FROM horario_view
WHERE substring(horario_grupo, 7, 3) = (CAST(:grupo AS INT) + 1)::varchar
AND (facultad_id = :facultad_id OR :facultad_id IS NULL) AND carrera_id = :carrera_id",
[
'grupo' => $_GET['grupo'],
'facultad_id' => $user->facultad['facultad_id'],
'carrera_id' => $_GET['carrera_id'],
]
);
}
$last_query = [
'query' => $db->getLastQuery(),
];
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} else {
throw new Exception('invalid method');
}
} catch (PDOException $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
'query' => $db->getLastQuery(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_PARTIAL_OUTPUT_ON_ERROR);
exit;
} catch (Exception $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
}

View File

@@ -0,0 +1,39 @@
<?php
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
$user = Login::get_user();
$ruta = "../";
require_once "../include/bd_pdo.php";
extract($_POST);
$params = [
"hora" => $hora,
"salon" => $salón,
"facultad_id" => $facultad,
"periodo" => $periodo,
"grupo" => $grupo,
"materia_id" => $materia,
"dia" => $día,
"duracion" => $duración,
"profesores" => "{{$profesores}}",
];
header("Content-Type: application/json");
$user->print_to_log("Creación de horario", new: $params);
try {
$db->insert("fs_horario", $params);
} catch (Exception $e) {
die(json_encode([
"status" => "error",
"message" => "No se pudo crear el horario",
]));
}
die(json_encode([
"status" => "success",
"message" => "Horario creado correctamente",
]));

View File

@@ -0,0 +1,38 @@
<?php
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
extract($_POST);
try {
$old = $db
->where('horario_id', $id)
->getOne('horario');
$user->print_to_log("Eliminación de horario", old: $old);
$horario = $db
->where('id', $id)
->delete('fs_horario');
} catch (Exception $e) {
// if message contains "Integrity constraint violation"
$message = (strpos($e->getMessage(), 'Foreign') !== false)
? "No se puede eliminar el registro, tiene datos asociados"
: "Error al eliminar el registro";
die(json_encode([
"status" => "error",
"message" => $message,
"response" => $e->getMessage(),
]));
}
die(json_encode([
"status" => "success",
"message" => "Horario eliminado correctamente",
]));

View File

@@ -0,0 +1,51 @@
<?php
$ruta = "../";
require_once "../include/bd_pdo.php";
require_once "../include/func_excel.php";
extract($_POST);
# $carrera;
# $facultad;
$horarios = json_decode($data, true);
// make sure profesores are in the database
foreach ($horarios as $horario) {
$params = [
'materia' => $horario['materia'],
'carrera' => $carrera,
];
$horario['materia'] = query("SELECT FI_MATERIA(:materia, :carrera) id", $params)['id'];
$params = [
'clave' => $horario['clave'],
'nombre' => $horario['nombre'],
'correo' => $horario['correo'],
'grado' => $horario['grado'],
'facultad' => $facultad,
];
$horario['profesor'] = query("SELECT FI_PROFESOR(:nombre, :clave, :facultad, :correo, :grado) id", $params)['id'];
$horario = array_diff_key($horario, array_flip(['clave', 'nombre', 'correo', 'grado', '']));
$horario['periodo'] = $periodo;
$horario['facultad'] = $facultad;
try {
query(
"SELECT FI_HORARIO(:horario::VARCHAR, :profesor::INT, :materia::INT, :facultad::INT, :periodo::INT, :grupo::VARCHAR, :salon::VARCHAR)",
$horario
);
} catch (Exception $e) {
die(json_encode([
"status" => "error",
"sql" => $e->getMessage(),
"message" => "Error al cargar el archivo",
]));
}
}
?>
<?= json_encode([
"status" => "success",
"message" => "Horarios guardado con éxito",
]) ?>

View File

@@ -0,0 +1,38 @@
<?php
header('Content-Type: application/json');
$ruta = "../";
require_once("../include/bd_pdo.php");
$dias = array("domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado");
try {
if(empty($_POST['profesor_id']))
throw new Exception("No se ha especificado un profesor");
// RECORD LAST QUERY
$horarios = $db->query("SELECT * FROM fs_horario(_periodo_id => ?, _last => true, _profesor_id => ?) ORDER BY MATERIA", [
$_POST['periodo_id'],
$_POST['profesor_id'],
]);
$horarios = array_map(function ($horario) use ($dias, $db) {
$horario['profesores'] = array_map(
fn ($profesor) =>
$db->where("id", $profesor)->getOne("fs_profesor"),
explode(",", substr($horario['profesores'], 1, -1))
);
$horario['dia'] = $dias[$horario['dia']];
return $horario;
}, $horarios);
die(json_encode([
"status" => "success",
"data" => $horarios,
// "data" => [],
]));
} catch (Exception $e) {
die(json_encode([
"status" => "error",
"message" => $e->getMessage(),
"query" => $db->getLastQuery(),
]));
}

View File

@@ -0,0 +1,48 @@
<?php
header('Content-Type: application/json');
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
$horario = array_map(fn ($value) => $_POST[$value], array_filter([
"hora" => "hora",
"dia" => "día",
"salon" => "salón",
"duracion" => "duración",
], fn ($value) => !empty($_POST[$value])));
if (!empty($_POST['profesores']))
$horario["profesores"] = "{ {$_POST['profesores']} }";
try {
$id = $_POST['id'] ?? 0;
$old = $db
->where("horario_id", $id)
->getOne("horario");
$horario = $db
->where("id", $id)
->update("fs_horario", $horario);
$new = $db
->orderBy("horario_id", "DESC")
->getOne("horario");
$user->print_to_log("Actualización de horario", old: $old, new: $new);
} catch (Exception $e) {
die(json_encode([
"status" => "error",
"message" => $e->getMessage(),
'POST' => $_POST,
]));
}
die(json_encode([
"status" => "success",
]));

View File

@@ -0,0 +1,94 @@
<?
header('Content-Type: application/json charset=utf-8');
#return html
$ruta = "../";
require_once "../class/c_login.php";
// check method
if (!isset($_SESSION['user'])) {
http_response_code(401);
echo json_encode(['error' => 'unauthorized']);
exit;
}
$user = unserialize($_SESSION['user']);
try {
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
// check parameters
$raw = file_get_contents('php://input');
$post_data = json_decode($raw, true);
// if it's a list
// step 1: get subrutas
if (empty($post_data)) {
http_response_code(400);
echo json_encode(['error' => 'No hay clases pendientes']);
exit;
}
if (!(isset($post_data['fecha'], $post_data['bloques'], $post_data['justificacion']))) {
http_response_code(400);
echo json_encode(['error' => 'Faltan parametros']);
exit;
}
$bloques = $db
->where('id', $post_data['bloques'])
->orderBy('hora_inicio')
->get('bloque_horario', null, 'hora_inicio, hora_fin');
$min_hora_inicio = $bloques[0]['hora_inicio'];
$max_hora_fin = $bloques[count($bloques) - 1]['hora_fin'];
$pdo->beginTransaction();
$data = $db->query(
"INSERT INTO registro (horario_id, registro_fecha_ideal, profesor_id, justificador_id, justificacion, registro_fecha_justificacion, registro_justificada)
SELECT DISTINCT
horario_id, :fecha::DATE, profesor_id, :justificador_id::INT, :justificacion, NOW(), true
from horario_view
join horario_profesor using (horario_id)
where
(:hora_inicio::TIME, :hora_fin::TIME) OVERLAPS (horario_hora, horario_fin) AND
horario_dia = EXTRACT(DOW FROM :fecha::DATE) AND
periodo_id = :periodo_id AND
(horario_view.facultad_id = :facultad_id OR :facultad_id IS NULL)
ON CONFLICT (horario_id, registro_fecha_ideal, profesor_id) DO UPDATE SET
justificador_id = :justificador_id,
justificacion = :justificacion,
registro_fecha_justificacion = NOW(),
registro_justificada = true
RETURNING *;",
array(
'justificador_id' => $user->user['id'],
'justificacion' => empty($post_data['justificacion']) ? null : $post_data['justificacion'],
'fecha' => $post_data['fecha'],
'periodo_id' => $user->periodo_id,
'facultad_id' => $user->facultad['facultad_id'],
'hora_inicio' => $min_hora_inicio,
'hora_fin' => $max_hora_fin,
)
);
$pdo->commit();
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} else {
http_response_code(405);
echo json_encode(['error' => 'method not allowed']);
exit;
}
} catch (PDOException $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
'query' => $db->getLastQuery(),
'post_data' => $post_data,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
$pdo->rollBack();
exit;
} catch (Exception $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
}

42
action/action_login.php Normal file
View File

@@ -0,0 +1,42 @@
<?php
/*
* Valida usuario con la BD y devuelve contraseña para validar con PHP
*
* Recibe:
* POST: usuario, password
*
* Error:
* 0 - No se recibieron datos
* 1 - Usuario/Contraseña incorrectos
* 2 - Usuario no esta en BD
* 3 - No existe usuario
*
* Success:
* Redirecciona a inicio.php
*/
include_once "../include/nocache.php"; //continue on error
$ruta = "../";
require_once "../include/bd_pdo.php"; //die on error
require_once "../class/c_login.php";
require_once "../include/util.php";
if (!isset($_POST["username"]) || !isset($_POST["passwd"]))
die(header("Location: ../index.php?error=0"));
$usr = trim(filter_input(INPUT_POST, "username")); //limpia texto
$pass = $_POST["passwd"];
$user = Login::validUser($usr, $pass);
if (is_array($user)) {
$_SESSION['error'] = true;
// build query params
$params = http_build_query($user);
header("Location: ../index.php?$params");
} else {
$_SESSION['user'] = serialize($user);
header("Location: " . (isset($_SESSION['ruta']) ? $_SESSION['ruta'] : "../main.php"));
}
exit;

View File

@@ -0,0 +1,30 @@
<?php
header('Content-Type: application/json');
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
$ruta = "../";
require_once "../include/bd_pdo.php";
$facultad_id = $user->facultad['facultad_id'];
$materias = $db->query(<<<SQL
SELECT materia_id, materia_nombre, clave_materia, materia.carrera_id
FROM materia
JOIN carrera USING (carrera_id)
JOIN facultad USING (facultad_id)
WHERE
(facultad_id = :facultad_id OR :facultad_id IS NULL)
ORDER BY carrera_nombre DESC
SQL,
array('facultad_id' => $facultad_id)
);
// $user->print_to_log("Crea carrera", old: $_POST);
die(json_encode($materias));

View File

@@ -0,0 +1,8 @@
<?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));
?>

View File

@@ -0,0 +1,11 @@
<?php
$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();
?>

View File

@@ -0,0 +1,17 @@
<!-- fi_horario(
p_hora character varying,
p_materia character varying,
p_clave character varying,
p_nombre character varying,
p_grado character varying,
p_correo character varying,
p_facultad integer,
p_carrera integer,
p_grupo character varying DEFAULT NULL::character varying,
p_salon character varying DEFAULT NULL::character varying) -->
<?php
$ruta = "../";
require_once "../include/bd_pdo.php";
$sql = "SELECT fi_horario(:hora, :materia, :clave, :nombre, :grado, :correo, :facultad, :carrera, :grupo, :salon)";

View File

@@ -0,0 +1,17 @@
<?php
$ruta = "../";
require_once "../include/bd_pdo.php";
global $pdo;
$sql = "SELECT fi_periodo(:fecha_inicio, :fecha_fin, :estado, :nombre, :nivel, :facultad)";
$params = [
':fecha_inicio' => $_POST['fecha_inicial'],
':fecha_fin' => $_POST['fecha_final'],
':estado' => $_POST['estadoP'],
':nombre' => mb_strtoupper($_POST['nombreP']),
':nivel' => $_POST['nivelP'],
':facultad' => $_POST['facultadP']
];
echo json_encode(query($sql, $params, true));
header("Location: ../carreras.php?facultad=".$_POST['facultadP']);
exit();
?>

View File

@@ -0,0 +1,8 @@
<?php
$ruta = "../";
require_once "../include/bd_pdo.php";
global $pdo;
$sql = "SELECT * FROM fs_periodo WHERE facultad_id = :idfacultad AND id = :idperiodo";
$params = [':idfacultad' => $_POST['idfacultad'], ':idperiodo' => $_POST['idperiodo']];
echo json_encode(query($sql, $params, true));
?>

View File

@@ -0,0 +1,17 @@
<?php
$ruta = "../";
require_once "../include/bd_pdo.php";
global $pdo;
print_r($_POST);
$sql = "SELECT fu_update_periodo(:periodo_id, :fecha_inicio, :fecha_final, :estado, :nombre, :nivel)";
$params = [
':periodo_id' => $_POST['idP'],
':fecha_inicio' => $_POST['fecha_inicial'],
':fecha_final' => $_POST['fecha_final'],
':estado' => $_POST['estadoP'],
':nombre' => mb_strtoupper($_POST['nombreP']),
':nivel' => $_POST['nivelP']
];
echo json_encode(query($sql, $params, true));
header("Location: ../carreras.php?facultad=" . $_POST['facultadP']);
exit();

View File

@@ -0,0 +1,17 @@
<?php
$ruta = "../";
require_once "../class/c_login.php";
if (!isset($_SESSION['user'])) {
header('Location: index.php');
exit;
} else
$user = unserialize($_SESSION['user']);
$params = array(':id' => $user->user['id'], ':per' => $_POST['id']);
$user->print_to_log('Actualizando periodo from ' . $user->periodo_id . ' to ' . $_POST['id']);
query("SELECT FU_UPDATEPERIODO(:id, :per)", $params);
$_SESSION['user'] = serialize($user);
header("Location: {$_POST["target"]}");

View File

@@ -0,0 +1,36 @@
<?php
$ruta = "../";
require_once "../include/bd_pdo.php";
global $db;
if(isset($_POST['lectura']))
$ver = $_POST['lectura'];
if(isset($_POST['editar']))
$editar = $_POST['editar'];
foreach($editar as $edit){
$edit_separado = explode("_", $edit);
$completo[]=$edit_separado;
}
$db->query("SELECT fd_permiso()");
foreach($ver as $lectura){
$igual=false;
$ver_separado = explode("_", $lectura);
foreach($completo as $comp){
if($ver_separado[0] == $comp[0] && $ver_separado[1] == $comp[1]){
$igual=true;
break;
}
}
if(!$igual)
$completo[]=$ver_separado;
}
foreach($completo as $actual){
$db->insert('permiso', [
'pagina_id' => $actual['0'],
'rol_id' => $actual['1'],
'permiso_tipo' => $actual['2'],
]);
}
header("Location: ../permisos.php");
exit();
?>

View File

@@ -0,0 +1,57 @@
<?
#input $_GET['id_espacio_sgu']
#output rutas: [ ...ruta, salones: [{...salon}] ]
header('Content-Type: application/json charset=utf-8');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ruta = "../";
require_once $ruta . "class/c_login.php";
if (!isset($_SESSION['user'])) {
http_response_code(401);
die(json_encode(['error' => 'unauthorized']));
}
$user = unserialize($_SESSION['user']);
// check method
try {
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$data = $db->query(
"SELECT DISTINCT profesor.*
FROM profesor
JOIN horario_profesor using (profesor_id)
JOIN horario using (horario_id)
JOIN materia using (materia_id)
JOIN carrera using (carrera_id)
WHERE carrera.facultad_id = :facultad_id OR :facultad_id IS NULL
ORDER BY profesor.profesor_nombre",
array(
":facultad_id" => $user->facultad['facultad_id']
)
);
$last_query = [
'query' => $db->getLastQuery(),
];
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} else {
http_response_code(405);
echo json_encode(['error' => 'method not allowed']);
exit;
}
} catch (PDOException $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
'query' => $db->getLastQuery(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_PARTIAL_OUTPUT_ON_ERROR);
exit;
} catch (Exception $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
}

View File

@@ -0,0 +1,40 @@
<?php
$ruta = "../";
require_once "../include/bd_pdo.php";
// die(print_r($_POST, true));
extract($_POST);
// if hora fin is null, then subtract half an hour from hora inicio and set hora fin to hora inicio + half an hour
$hora_fin = empty($hora_fin) ? $hora_inicio : $hora_fin;
$hora_inicio = date('H:i:s', strtotime($hora_inicio < '07:00' ? '07:00' : $hora_inicio) - 1800);
$hora_fin = date('H:i:s', strtotime($hora_fin > '22:00' ? '22:00' : $hora_fin) + 1800);
die(json_encode(
array_map(fn ($row) => array_merge(
$db->where('id', $row['profesor_id'])->getOne('fs_profesor'),
$db->where('id', $row['materia_id'])->getOne('fs_materia'),
$row
),
queryAll(
"SELECT REPORTE.*
FROM fs_asistencia_profesorreporte(null, :periodo, null, :fecha, :fecha) AS REPORTE
JOIN PROFESOR P ON P.PROFESOR_ID = REPORTE.PROFESOR_ID
WHERE HORA_CHECADO IS NULL
AND HORA BETWEEN :inicio AND :fin
AND P.PROFESOR_CLAVE ILIKE COALESCE(:clave, P.PROFESOR_CLAVE) and UNACCENT(P.PROFESOR_NOMBRE) ILIKE UNACCENT(COALESCE(:nombre, P.PROFESOR_NOMBRE))
AND FECHA = :fecha
ORDER BY HORA, MATERIA",
[
'periodo' => $periodo,
'fecha' => $fecha,
'inicio' => $hora_inicio,
'fin' => $hora_fin,
'clave' => empty($clave) ? null : "%$clave%",
'nombre' => empty($nombre) ? null : "%$nombre%"
]
))));
#ECHO "$hora_inicio - $hora_fin";

View File

@@ -0,0 +1,7 @@
<?php
$ruta = "../";
require_once "../include/bd_pdo.php";
$sql = "SELECT fu_estado_facultad_profesor(:idprofesor, :idfacultad, :estado)";
$params = [':idprofesor' => $_POST['id_profesor'], ':idfacultad' => $_POST['id_facultad'], ':estado' => $_POST['estado']];
echo json_encode(query($sql, $params, false));
?>

View File

@@ -0,0 +1,75 @@
<?php
$ruta = "../";
require_once "../include/bd_pdo.php";
$id = trim(filter_input(INPUT_POST, "id", FILTER_SANITIZE_STRING,array('flags' => FILTER_FLAG_STRIP_LOW)));
if(isset($_POST["dlfacultad"]))
$facultad = trim(filter_input(INPUT_POST, "dlfacultad", FILTER_SANITIZE_STRING,array('flags' => FILTER_FLAG_STRIP_LOW)));
else
$facultad = trim(filter_input(INPUT_POST, "mfacultad", FILTER_SANITIZE_STRING,array('flags' => FILTER_FLAG_STRIP_LOW)));
$clave = trim(filter_input(INPUT_POST, "mclave", FILTER_SANITIZE_STRING,array('flags' => FILTER_FLAG_STRIP_LOW)));
$grado = trim(filter_input(INPUT_POST, "grado", FILTER_SANITIZE_STRING,array('flags' => FILTER_FLAG_STRIP_LOW)));
$nombre = trim(filter_input(INPUT_POST, "nombre", FILTER_SANITIZE_STRING,array('flags' => FILTER_FLAG_STRIP_LOW)));
$grado = mb_strtoupper($grado);
if(!empty($grado)){
if(!ctype_space($grado)){
if($grado[strlen($grado)-1] != '.')
$grado.='.';
}
else{
$grado="";
}
}
$fs_profesores = query(//revisar si existe la clave del profesor
"SELECT * FROM fs_profesor WHERE clave = :clave",
array(":clave" => $_POST["mclave"]),
true
);
if(!$fs_profesores){//hay que crearlo desde 0 (profesor) y agregarlo a su facultad(facultad_profesor)
$profesor_id = query(
"SELECT public.fi_profesor(
:nombre,
:clave,
:facultad,
null,
:grado
)",
array(":nombre" => mb_strtoupper($nombre), ":clave" => $clave, ":facultad" => $facultad, ":grado" => $grado),
true
);
header("Location: ../profesores.php");
exit();
}
else{//el profesor ya existe
$profac = query(
"SELECT * FROM facultad_profesor WHERE facultad_id = :facultad AND profesor_id = :profesor",
array(":facultad" => $facultad, ":profesor" => $fs_profesores["id"]),
true
);
if(!$profac){//agregarlo a la facultad (facultad_profesor)
query(
"SELECT fi_facultad_profesor(
:facultad,
:profesor
)",
array(":facultad" => $facultad, ":profesor" => $fs_profesores["id"]),
true
);
header("Location: ../profesores.php");
exit();
}
else{//regresar error (ya existe este profesor en esta facultad)
//print_r($profac);
if(!$profac['fp_activo']){
query(
"SELECT fu_estado_facultad_profesor(:idprofesor, :idfacultad, :estado)",
array(":idprofesor" => $fs_profesores["id"], ":idfacultad" => $facultad, ":estado" => true),
true
);
header("Location: ../profesores.php");
exit();
}
header("Location: ../profesores.php?error=1");
#exit();
}
}
?>

View File

@@ -0,0 +1,10 @@
<?php
$ruta = "../";
require_once "../include/bd_pdo.php";
global $pdo;
$sql = "SELECT * FROM profesor WHERE profesor_id = :idProfesor";
$params = [':idProfesor' => $_POST['profesor']];
echo json_encode(query($sql, $params, false));

View File

@@ -0,0 +1,23 @@
<?php
$ruta = "../";
/* ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL); */
require_once "../include/bd_pdo.php";
global $db;
$grado = $_POST['grado'];
$grado = mb_strtoupper($grado);
if (!empty($grado)) {
if (!ctype_space($grado)) {
if ($grado[strlen($grado) - 1] != '.')
$grado .= '.';
} else {
$grado = "";
}
}
// print_r($_POST);
$db->where('profesor_id', $_POST['id'])->update('profesor', ['profesor_grado' => $_POST['grado']]);
header("Location: ../profesores.php", true, 307);
exit();

View File

@@ -0,0 +1,54 @@
<?php
$ruta = "../";
require_once "../class/c_login.php";
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
$ruta = "../";
require_once "../include/bd_pdo.php";
// if method is get
header("Content-Type: application/json");
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$user->print_to_log("Acceso a reposiciones");
$reposiciones = $db
->where('periodo_id', $_GET['periodo_id'] ?? null)
->where('profesor_id', $_GET['profesor_id'] ?? [])
->get("reposicion");
echo json_encode([
'status' => 'success',
'reposiciones' => $reposiciones
]);
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
$user->print_to_log("Creación de reposición", new: $params);
try {
$requiredParams = ['horario_id', 'fecha', 'hora', 'duracion_id', 'descripcion', 'profesor_id', 'salon', 'unidad', 'periodo_id', 'fecha_clase'];
// Filter params based on requiredParams
$params = array_filter($_POST, function ($key) use ($requiredParams) {
return in_array($key, $requiredParams);
}, ARRAY_FILTER_USE_KEY);
// Check if all required params are present
if (count($params) !== count($requiredParams)) {
throw new Exception('Falta uno o más parámetros requeridos');
}
$db->insert("reposicion", $params);
// Return success response
echo json_encode([
"status" => "success",
"message" => "Reposición creada correctamente",
]);
} catch (Exception $e) {
// Return error response
echo json_encode([
"status" => "error",
"message" => "No se pudo crear la reposición",
"error" => $e->getMessage(),
]);
}
}

View File

@@ -0,0 +1,50 @@
<?php
#display PHP errors
$ruta = "../";
require_once "../include/bd_pdo.php";
require_once "../include/func_excel.php";
require_once "../include/func_string.php";
use PhpOffice\PhpSpreadsheet\IOFactory;
$reader = IOFactory::createReader("Xlsx");
$reader->setReadDataOnly(true);
$file = $_FILES['archivo'];
$spreadsheet = $reader->load($file['tmp_name'][0]);
$data = [];
try {
foreach_sheet(
$spreadsheet, // object $spreadsheet
function (array $row_data, int $i, string $sheet) {
global $horario, $data;
if (renglón_vacío($row_data)) return;
validar_registro($row_data, $i);
$horario["horario"] = horario($row_data, $i, $sheet);
foreach (array_filter($row_data) as $key => $value)
$horario = array_merge($horario, ($key == 'maestro') ? columna_nombre($value) : [$key => $value]);
$data[] = $horario;
}
);
die(json_encode([
"status" => "success",
"message" => "Horario revisado con éxito, se leyeron: " . count($data) . " registros",
"data" => $data
]));
} catch (Exception $e) {
die(json_encode([
"status" => "error",
"message" => $e->getMessage(),
]));
}

View File

@@ -0,0 +1,11 @@
<?php
$ruta = "../";
require_once "../include/bd_pdo.php";
global $pdo;
print_r($_POST);
$sql = "INSERT INTO rol (rol_titulo) VALUES (:nombre)";
$params = [':nombre' => mb_strtoupper($_POST['mtitulo'])];
$hecho = query($sql, $params, true);
header("Location: ../roles.php");
exit();
?>

View File

@@ -0,0 +1,11 @@
<?php
$ruta = "../";
require_once "../include/bd_pdo.php";
global $pdo;
$sql = "SELECT * FROM rol WHERE rol_id = :idRol";
$params = [':idRol' => $_POST['rol']];
echo json_encode( query($sql, $params, true));
?>

View File

@@ -0,0 +1,11 @@
<?php
$ruta = "../";
require_once "../include/bd_pdo.php";
global $pdo;
$sql = "UPDATE rol SET rol_titulo = :nombre WHERE rol_id = :id";
$params = array(':nombre' => mb_strtoupper($_POST['mtitulo']), ':id' => $_POST['id']);
print_r($_POST);
$hecho = query($sql, $params, false);
header("Location: ../roles.php", true, 307);
exit();
?>

View File

@@ -0,0 +1,37 @@
<?php
$ruta = "../";
require_once "../include/bd_pdo.php";
print_r($_POST);
$fs_tiempo = query(
"SELECT * FROM fs_tiempo_checado(:facultad, 1)", [':facultad' => $_POST['facultadT']], true
);
if($fs_tiempo){
$sql = "SELECT fu_update_tiempo_checado(:idfacultad, :idnivel, :antes, :despues, :retardo)";
$params = [':idfacultad' => $_POST['facultadT'], ':idnivel' => 1, ':antes' => -1*$_POST['antesL'], ':despues' => $_POST['despuesL']+1, ':retardo' => $_POST['retardoL']+$_POST['despuesL']+1];
}
else{
$sql = "SELECT fi_tiempo_checado(:idfacultad, :idnivel, :antes, :despues, :retardo)";
$params = [':idfacultad' => $_POST['facultadT'], ':idnivel' => 1, ':antes' => -1*$_POST['antesL'], ':despues' => $_POST['despuesL']+1, ':retardo' => $_POST['retardoL']+$_POST['despuesL']+1];
}
query($sql, $params, false);
$fs_tiempo2 = query(
"SELECT * FROM fs_tiempo_checado(:facultad, 2)", [':facultad' => $_POST['facultadT']], true
);
if($fs_tiempo2){
$sql = "SELECT fu_update_tiempo_checado(:idfacultad, :idnivel, :antes, :despues, :retardo)";
$params = [':idfacultad' => $_POST['facultadT'], ':idnivel' => 2, ':antes' => -1*$_POST['antesP'], ':despues' => $_POST['despuesP']+1, ':retardo' => $_POST['retardoP']+$_POST['despuesP']+1];
}
else{
$sql = "SELECT fi_tiempo_checado(:idfacultad, :idnivel, :antes, :despues, :retardo)";
$params = [':idfacultad' => $_POST['facultadT'], ':idnivel' => 2, ':antes' => -1*$_POST['antesP'], ':despues' => $_POST['despuesP']+1, ':retardo' => $_POST['retardoP']+$_POST['despuesP']+1];
}
query($sql, $params, false);
header("Location: ../carreras.php?facultad=".$_POST['facultadT']);
exit();
?>

22
action/action_usuario.php Normal file
View File

@@ -0,0 +1,22 @@
<?php
$ruta = "../";
require_once '../class/c_login.php';
// print_r($_POST); exit;
if (($user = Login::validUser($_POST['username'], $_POST['passwd'])) === false) {
echo json_encode("error");
exit;
}
$facultades = queryAll("SELECT DISTINCT ID, FACULTAD FROM FS_FACULTAD WHERE ACTIVA");
for ($i = 0; $i < count($facultades); $i++) {
# print_r($facultades[$i]);
$facultades[$i]['usuarios'] = queryAll(
"SELECT ID, USERNAME FROM FS_USUARIO WHERE facultad = :facultad",
array(":facultad" => $facultades[$i]["id"])
);
}
echo json_encode($facultades);

View File

@@ -0,0 +1,15 @@
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ruta = "../";
require_once "../include/bd_pdo.php";
global $db;
try {
$db->querySingle("UPDATE usuario SET estado_baja = TRUE WHERE usuario_id = ?", [$_GET['id']]);
header("Location: ../usuarios.php", true, 307);
} catch (PDOException $e) {
header("Location: ../usuarios.php?error=2");
exit;
}

View File

@@ -0,0 +1,29 @@
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ruta = "../";
require_once "../include/bd_pdo.php";
global $db;
if (isset($_POST['dlfacultad']))
$facultad = $_POST['dlfacultad'];
else
$facultad = $_POST['mfacultad'];
if ($db->where('usuario_clave', $_POST['mclave'])->has('usuario')) {
header("Location: ../usuarios.php?error=1");
exit;
}
try {
$db->insert('usuario', [
'usuario_nombre' => mb_strtoupper($_POST['mnombre']),
'usuario_correo' => $_POST['mcorreo'],
'usuario_clave' => $_POST['mclave'],
'rol_id' => $_POST['mrol'] ?? null,
'facultad_id' => empty($facultad) ? null : $facultad,
]);
header("Location: ../usuarios.php", true, 307);
} catch (PDOException $e) {
header("Location: ../usuarios.php?error=2");
exit;
}

View File

@@ -0,0 +1,8 @@
<?php
$ruta = "../";
require_once "../include/bd_pdo.php";
global $pdo;
$sql = "SELECT * FROM usuario WHERE usuario_id = :idUsuario";
$params = [':idUsuario' => $_POST['usuario']];
echo json_encode(query($sql, $params, true));
?>

View File

@@ -0,0 +1,26 @@
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ruta = "../";
require_once "../include/bd_pdo.php";
global $db;
print_r($_POST);
if (isset($_POST['dlfacultad']))
$facultad = $_POST['dlfacultad'];
else
$facultad = $_POST['mfacultad'];
$db->where('usuario_clave', $_POST['mclave'])
->update(
'usuario',
array(
'usuario_nombre' => mb_strtoupper($_POST['mnombre']),
'usuario_correo' => $_POST['mcorreo'],
'usuario_clave' => $_POST['mclave'],
'rol_id' => $_POST['mrol'],
'facultad_id' => empty($facultad) ? null : $facultad,
)
);
header("Location: ../usuarios.php", true, 307);
exit();

View File

@@ -0,0 +1,166 @@
<?php
/*
* Inserta reposición
*/
$pag = "../reposiciones_crear.php";
$ruta = "../";
require_once "../class/c_login.php";
require_once "../class/mailer.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']);
//$user->access();
$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(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"];
//-- 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));
//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);*/
exit();
}
//Obtiene materia
$materia_rs = $db->querySingle('SELECT materia_nombre from materia where materia_id = :mat',[':mat' => $materia]);
//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"];
}
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();
}
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);*/
}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">
'.$texto.'
</body>';
require_once('../include/phpmailer/PHPMailerAutoload.php');
if($_ENV['DB_NAME'] == "paad_pruebas"){
$asunto = "PRUEBAS-".$asunto;
Mailer::enviarCorreo("alejandro.rosales@lasalle.mx", $asunto, $texto, true);
}else{
Mailer::enviarCorreo($to, $asunto, $texto, true);
}
}
exit();
header("Location: ".$pag."?ok=0");
?>

View File

@@ -0,0 +1,26 @@
<?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']);
if(empty($_POST["id"]) || empty($_POST["hor"])){
$return["error"] = "Error! No se recibió la información del usuario.";
}else{
$id = filter_input(INPUT_POST, "id", FILTER_SANITIZE_NUMBER_INT);//limpia texto
$hor = filter_input(INPUT_POST, "hor", FILTER_SANITIZE_NUMBER_INT);//limpia texto
$rs = $db->query('SELECT * from fs_asistenciaprofesor_horario(:id, :hor)', [':id' => $id, ':hor' => $hor]);
$asistArr = array();
foreach($rs as $row){
$asistArr[] = $row["registro_fecha_ideal"];
}
$return["asistenciaArr"] = $asistArr;
}
echo json_encode($return);
?>

293
action/avisos.php Normal file
View File

@@ -0,0 +1,293 @@
<?
require_once "{$_SERVER['DOCUMENT_ROOT']}/class/c_login.php";
header('Content-Type: application/json');
if (!Login::is_logged()) {
header('HTTP/1.1 401 Unauthorized');
echo json_encode(array('error' => 'No se ha iniciado sesión'));
exit();
}
$user = Login::get_user();
try {
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
$facultad_id = $user->facultad['facultad_id'];
$avisos = $db->query(
"SELECT * FROM aviso
WHERE
(CURRENT_DATE BETWEEN aviso_fecha_inicial AND aviso_fecha_final) AND
(facultad_id = :facultad_id OR :facultad_id IS NULL) AND
aviso_estado
ORDER BY aviso_id DESC",
array('facultad_id' => $facultad_id)
);
/*
if (empty($avisos)) {
header('HTTP/1.1 404 Not Found');
echo json_encode(array('error' => 'No hay avisos disponibles'));
exit();
}
*/
$avisos = array_map(fn($aviso) => array(
...$aviso,
'carreras' => $db->query(
"SELECT carrera_id, carrera_nombre FROM aviso_carrera
JOIN carrera USING (carrera_id)
WHERE aviso_id = :aviso_id",
array('aviso_id' => $aviso['aviso_id'])
),
'profesores' => $db->query(
"SELECT profesor_id, profesor_clave, profesor_nombre FROM aviso_profesor
JOIN profesor USING (profesor_id)
WHERE aviso_id = :aviso_id",
array('aviso_id' => $aviso['aviso_id'])
),
), $avisos);
echo json_encode($avisos);
break;
case 'POST':
$raw_input = file_get_contents('php://input');
if (empty($raw_input)) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(array('error' => 'No se recibieron parámetros'));
exit();
}
$input_data = json_decode($raw_input);
if (json_last_error() !== JSON_ERROR_NONE) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(array('error' => 'Invalid JSON format'));
exit();
}
$schema = <<<JSON
{
"\$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["aviso_fecha_inicial", "aviso_fecha_final", "aviso_titulo", "aviso_texto"],
"properties": {
"aviso_fecha_inicial": {
"type": "string",
"format": "date"
},
"aviso_fecha_final": {
"type": "string",
"format": "date"
},
"aviso_texto": {
"type": "string"
},
"aviso_titulo": {
"type": "string"
},
"carreras": {
"type": "array",
"items": {
"type": "integer",
"minimum": 1
},
"minItems": 0,
"uniqueItems": true
},
"profesores": {
"type": "array",
"items": {
"type": "integer",
"minimum": 1
},
"minItems": 0,
"uniqueItems": true
}
},
"anyOf": [
{"required": ["carreras"]},
{"required": ["profesores"]}
]
}
JSON;
// VALIDATE JSON SCHEMA
$validate = new JsonSchema\Validator();
$validate->validate($input_data, json_decode($schema));
if (!$validate->isValid()) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(
array(
'error' => 'El formato de la solicitud es incorrecto',
'success' => false,
'errors' => $validate->getErrors()
)
);
exit();
}
$aviso_id = $db->insert(
'aviso',
array(
'aviso_fecha_inicial' => $input_data->aviso_fecha_inicial,
'aviso_fecha_final' => $input_data->aviso_fecha_final,
'aviso_texto' => $input_data->aviso_texto,
'facultad_id' => $user->facultad['facultad_id'],
),
'aviso_id'
);
if (isset($input_data->carreras)) {
array_walk($input_data->carreras, fn($carrera_id) => $db->insert('aviso_carrera', array('aviso_id' => $aviso_id, 'carrera_id' => $carrera_id)));
}
if (isset($input_data->profesores)) {
array_walk($input_data->profesores, fn($profesor_id) => $db->insert('aviso_profesor', array('aviso_id' => $aviso_id, 'profesor_id' => $profesor_id)));
}
echo json_encode(
array(
'aviso_id' => $aviso_id,
'msg' => 'Aviso creado exitosamente',
'success' => true
)
);
break;
case 'PUT':
$raw_input = file_get_contents('php://input');
if (empty($raw_input)) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(array('error' => 'No se recibieron parámetros'));
exit();
}
$input_data = json_decode($raw_input);
if (json_last_error() !== JSON_ERROR_NONE) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(array('error' => 'Invalid JSON format'));
exit();
}
$schema = <<<JSON
{
"\$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["aviso_id", "aviso_fecha_final"],
"properties": {
"aviso_id": {
"type": "integer",
"minimum": 1
},
"aviso_fecha_final": {
"type": "string",
"format": "date"
}
}
}
JSON;
// VALIDATE JSON SCHEMA
$validate = new JsonSchema\Validator();
$validate->validate($input_data, json_decode($schema));
if (!$validate->isValid()) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(
array(
'error' => 'El formato de la solicitud es incorrecto',
'errors' => $validate->getErrors(),
'success' => false,
)
);
exit();
}
$db->where('aviso_id', $input_data->aviso_id)
->update(
'aviso',
array(
'aviso_fecha_final' => $input_data->aviso_fecha_final,
),
);
if (isset($input_data->carreras)) {
$db->where('aviso_id', $input_data->aviso_id)->delete('aviso_carrera');
array_walk($input_data->carreras, fn($carrera_id) => $db->insert('aviso_carrera', array('aviso_id' => $input_data->aviso_id, 'carrera_id' => $carrera_id)));
}
if (isset($input_data->profesores)) {
$db->where('aviso_id', $input_data->aviso_id)->delete('aviso_profesor');
array_walk($input_data->profesores, fn($profesor_id) => $db->insert('aviso_profesor', array('aviso_id' => $input_data->aviso_id, 'profesor_id' => $profesor_id)));
}
echo json_encode(
array(
'msg' => 'Aviso actualizado exitosamente',
'success' => true
)
);
break;
case 'DELETE':
$raw_input = file_get_contents('php://input');
if (empty($raw_input)) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(array('error' => 'No se recibieron parámetros'));
exit();
}
$input_data = json_decode($raw_input);
if (json_last_error() !== JSON_ERROR_NONE) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(array('error' => 'Invalid JSON format'));
exit();
}
$schema = <<<JSON
{
"\$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["aviso_id"],
"properties": {
"aviso_id": {
"type": "integer",
"minimum": 1
}
}
}
JSON;
// VALIDATE JSON SCHEMA
$validate = new JsonSchema\Validator();
$validate->validate($input_data, json_decode($schema));
if (!$validate->isValid()) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(
array(
'error' => 'El formato de la solicitud es incorrecto',
'errors' => $validate->getErrors(),
'success' => false,
)
);
exit();
}
$result = $db->where('aviso_id', $input_data->aviso_id)->update('aviso', array('aviso_estado' => false));
echo json_encode(
array(
'msg' => 'Aviso eliminado exitosamente',
'success' => true,
'result' => $result
)
);
break;
}
} catch (PDOException $e) {
echo json_encode(
array(
'error' => $e->getMessage(),
'query' => $db->getLastQuery(),
'exception' => $e->getTraceAsString()
)
);
}

66
action/carrera.php Normal file
View File

@@ -0,0 +1,66 @@
<?php
require_once "{$_SERVER['DOCUMENT_ROOT']}/class/c_login.php";
header('Content-Type: application/json');
if (!Login::is_logged()) {
header('HTTP/1.1 401 Unauthorized');
echo json_encode(['error' => 'No se ha iniciado sesión']);
exit();
}
$user = Login::get_user();
try {
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
// Fetch all puestos
$facultad_id = $user->facultad['facultad_id'];
$periodo_nivel_id = $db->where('periodo_id', $user->periodo_id)->getOne('periodo', 'nivel_id')['nivel_id'];
$carreras = $db->query(<<<SQL
SELECT carrera_id, carrera_nombre, clave_carrera,
facultad_id, facultad_nombre,
nivel_id, nivel_nombre
FROM carrera
join nivel using (nivel_id)
join facultad using (facultad_id)
WHERE facultad_id = :facultad_id OR :facultad_id IS NULL AND
nivel.nivel_id = :periodo_nivel_id
ORDER BY facultad_nombre, carrera_nombre
SQL, [
'facultad_id' => $facultad_id,
'periodo_nivel_id' => $periodo_nivel_id
]);
echo json_encode($carreras);
break;
case 'PUT':
// Update carrera {nivel_id}
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if (!isset($data['carrera_id'], $data['nivel_id'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['error' => 'Falta el id de la carrera o el nivel']);
exit();
}
$carrera_id = $data['carrera_id'];
$nivel_id = $data['nivel_id'];
$db->where('carrera_id', $carrera_id)->update('carrera', ['nivel_id' => $nivel_id]);
$carrera_nombre = $db->where('carrera_id', $carrera_id)->getOne('carrera', 'carrera_nombre')['carrera_nombre'];
$nivel_nombre = $db->where('nivel_id', $nivel_id)->getOne('nivel', 'nivel_nombre')['nivel_nombre'];
echo json_encode(['success' => "$carrera_nombre actualizada a $nivel_nombre"]);
break;
default:
header('HTTP/1.1 405 Method Not Allowed');
echo json_encode(['error' => 'Método no permitido']);
break;
}
} catch (PDOException $e) {
echo json_encode([
'error' => $e->getMessage(),
'query' => $db->getLastQuery(),
'exception' => $e->getTraceAsString()
]);
}

10
action/carrera_find.php Normal file
View File

@@ -0,0 +1,10 @@
<?php
$ruta = '../';
require_once '../include/bd_pdo.php';
global $pdo;
$sql = "SELECT * FROM fs_carreras(:fac, null, null)";
$params = [':fac' => $_POST['fac_id']];
echo json_encode(query($sql, $params, false));
?>

20
action/correo.php Normal file
View File

@@ -0,0 +1,20 @@
<?php
require_once '../class/mailer.php';
require_once('../include/phpmailer/PHPMailerAutoload.php');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if(!isset($_GET["correo"])){
echo "Debes especificar la dirección a la que se enviará el correo <strong>?correo=</strong>";
exit();
}
$to = $_GET["correo"];
$texto = "<h1>Esto es una prueba automatizada</h1><p>El correo se envió atutomáticamente, no debes hacer nada más.</p>";
$asunto="Prueba";
Mailer::enviarCorreo($to, $asunto, $texto, true);
echo "Enviado!".date("H:i:s");
?>

37
action/force_session.php Normal file
View File

@@ -0,0 +1,37 @@
<?php
$ruta = "../";
require_once '../class/c_login.php';
# print_r($_POST); exit;
extract($_POST); // $usuario
Login::log_out();
$user = query("SELECT * FROM FS_USUARIO WHERE ID = :id", [":id" => $usuario]);
// die(json_encode($user));
$facultad = [
"facultad_id" => $user["facultad"],
"facultad" => $user["facultad_nombre"]
];
$rol = [
"rol_id" => $user["rol"],
"rol" => $user["titulo"]
];
$admin = false;
$periodo = $user["periodo"];
$user = [
"id" => $user["id"],
"nombre" => $user["username"]
];
$user = new Login($user, $facultad, $rol, $admin, $periodo);
if (isset($_SESSION))
session_start();
$_SESSION['user'] = serialize($user);
header("Location: ../main.php");
exit;

View File

@@ -0,0 +1,46 @@
<?php
require_once "{$_SERVER['DOCUMENT_ROOT']}/class/c_login.php";
header('Content-Type: application/json');
if (!Login::is_logged()) {
header('HTTP/1.1 401 Unauthorized');
echo json_encode(['error' => 'No se ha iniciado sesión']);
exit();
}
$user = Login::get_user();
try {
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
$profesor_id = $db
->where('profesor_clave', $_GET['profesor'])
->getOne('profesor', 'profesor_id');
// Fetch all puestos
$horarios = $db->query(<<<SQL
SELECT * FROM horario
NATURAL JOIN horario_profesor
NATURAL JOIN facultad
NATURAL LEFT JOIN materia
NATURAL LEFT JOIN carrera
WHERE periodo_id = ? AND profesor_id = ?
SQL,
[$user->periodo_id, $profesor_id['profesor_id']]
);
echo json_encode($horarios);
break;
default:
header('HTTP/1.1 405 Method Not Allowed');
echo json_encode(['error' => 'Método no permitido']);
break;
}
} catch (PDOException $e) {
echo json_encode([
'error' => $e->getMessage(),
'query' => $db->getLastQuery(),
'exception' => $e->getTraceAsString()
]);
}

76
action/justificar.php Normal file
View File

@@ -0,0 +1,76 @@
<?php
require_once "{$_SERVER['DOCUMENT_ROOT']}/class/c_login.php";
header('Content-Type: application/json');
if (!Login::is_logged()) {
header('HTTP/1.1 401 Unauthorized');
echo json_encode(['error' => 'No se ha iniciado sesión']);
exit();
}
$user = Login::get_user();
try {
switch ($_SERVER['REQUEST_METHOD']) {
case 'POST':
// check parameters
$raw = file_get_contents('php://input');
$post_data = json_decode($raw, true);
$data = $db->querySingle(
'WITH HORARIOS AS (
SELECT *
FROM horario
JOIN horario_profesor USING (horario_id)
WHERE horario.periodo_id = :periodo_id
)
INSERT INTO registro (profesor_id, horario_id, registro_fecha_ideal, registro_justificada, justificador_id, registro_fecha_justificacion, justificacion)
VALUES (:profesor_id, :horario_id, :registro_fecha_ideal, :registro_justificada, :justificador_id, NOW(), :justificacion)
ON CONFLICT (profesor_id, horario_id, registro_fecha_ideal)
DO UPDATE SET registro_justificada = :registro_justificada, justificador_id = :justificador_id, registro_fecha_justificacion = NOW(), justificacion = :justificacion
RETURNING *',
array(
'periodo_id' => $user->periodo_id,
'profesor_id' => $post_data['profesor_id'],
'horario_id' => $post_data['horario_id'],
'registro_fecha_ideal' => $post_data['registro_fecha_ideal'],
'registro_justificada' => $post_data['registro_justificada'],
'justificador_id' => $user->user['id'],
'justificacion' => empty($post_data['justificacion']) ? null : $post_data['justificacion'],
)
);
$data_justificador = $db->querySingle(
"SELECT justificador.usuario_nombre as justificador_nombre,
justificador.usuario_clave as justificador_clave,
facultad.facultad_nombre as justificador_facultad, rol.rol_titulo as justificador_rol
FROM USUARIO JUSTIFICADOR
JOIN ROL on ROL.rol_id = justificador.rol_id
LEFT JOIN facultad on facultad.facultad_id = justificador.facultad_id
where justificador.usuario_id = :justificador_id",
array(
'justificador_id' => $user->user['id'],
)
);
// exit('exit');
echo json_encode(array_merge($data, $data_justificador), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
break;
default:
header('HTTP/1.1 405 Method Not Allowed');
echo json_encode(['error' => 'Método no permitido']);
}
} catch (PDOException $e) {
echo json_encode([
'error' => $e->getMessage(),
'query' => $db->getLastQuery(),
'exception' => $e->getTraceAsString()
]);
} catch (Exception $e) {
echo json_encode([
'error' => $e->getMessage(),
'exception' => $e->getTraceAsString()
]);
}

7
action/mail_javier.php Normal file
View File

@@ -0,0 +1,7 @@
<?php
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);
echo "Correo enviado";

31
action/nivel.php Normal file
View File

@@ -0,0 +1,31 @@
<?php
require_once "{$_SERVER['DOCUMENT_ROOT']}/class/c_login.php";
header('Content-Type: application/json');
if (!Login::is_logged()) {
header('HTTP/1.1 401 Unauthorized');
echo json_encode(['error' => 'No se ha iniciado sesión']);
exit();
}
$user = Login::get_user();
try {
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
// Fetch all puestos
$nivel = $db->get('nivel');
echo json_encode($nivel);
break;
default:
header('HTTP/1.1 405 Method Not Allowed');
echo json_encode(['error' => 'Método no permitido']);
break;
}
} catch (PDOException $e) {
echo json_encode([
'error' => $e->getMessage(),
'query' => $db->getLastQuery(),
'exception' => $e->getTraceAsString()
]);
}

44
action/periodo_datos.php Normal file
View File

@@ -0,0 +1,44 @@
<?
#input $_GET['id_espacio_sgu']
#output rutas: [ ...ruta, salones: [{...salon}] ]
header('Content-Type: application/json charset=utf-8');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ruta = "../";
require_once $ruta . "class/c_login.php";
if (!isset($_SESSION['user'])) {
http_response_code(401);
die(json_encode(['error' => 'unauthorized']));
}
$user = unserialize($_SESSION['user']);
// check method
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
http_response_code(405);
die(json_encode(['error' => 'method not allowed']));
}
const JSON_OPTIONS = JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_PARTIAL_OUTPUT_ON_ERROR;
try {
$data = $db->querySingle("SELECT *, LEAST(periodo_fecha_fin, CURRENT_DATE) as fecha_final FROM periodo WHERE periodo_id = ?", array($user->periodo_id));
$last_query = [
'query' => $db->getLastQuery(),
];
echo json_encode($data, JSON_OPTIONS);
} catch (PDOException $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
'query' => $db->getLastQuery(),
], JSON_OPTIONS);
exit;
} catch (Exception $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
], JSON_OPTIONS);
exit;
}

204
action/periodos.php Normal file
View File

@@ -0,0 +1,204 @@
<?php
require_once "{$_SERVER['DOCUMENT_ROOT']}/class/c_login.php";
header('Content-Type: application/json');
if (!Login::is_logged()) {
header('HTTP/1.1 401 Unauthorized');
echo json_encode(['error' => 'No se ha iniciado sesión']);
exit();
}
$user = Login::get_user();
try {
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
// Fetch all puestos
$periodo_id = $user->periodo_id;
if (is_null($user->facultad['facultad_id'])) {
$periodos = $db
//->where('CURRENT_DATE BETWEEN periodo_fecha_inicio AND periodo_fecha_fin')
->join('nivel', 'nivel.nivel_id = periodo.nivel_id')
->orderBy('periodo_id')
->get('periodo', null, 'periodo.*, nivel_nombre as nivel');
} else {
$periodos = $db->query(
"SELECT DISTINCT periodo.*, nivel_nombre as nivel FROM periodo
JOIN horario_view USING (periodo_id)
JOIN nivel ON nivel.nivel_id = periodo.nivel_id
WHERE /*CURRENT_DATE BETWEEN periodo.periodo_fecha_inicio AND periodo.periodo_fecha_fin
AND */facultad_id = :facultad_id
ORDER BY periodo_id
",
['facultad_id' => $user->facultad['facultad_id']]
);
}
echo json_encode($periodos);
break;
case 'PUT':
// Update nivel_id of a periodo
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if (!isset($data['action'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['error' => 'Falta la acción a realizar']);
exit();
}
switch ($data['action']) {
case 'changeNivel':
if (!isset($data['periodo_id'], $data['nivel_id'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['error' => 'Falta el id del periodo o el nivel']);
exit();
}
$periodo_id = $data['periodo_id'];
$nivel_id = $data['nivel_id'];
$db->where('periodo_id', $periodo_id)->update('periodo', ['nivel_id' => $nivel_id]);
$periodo_nombre = $db->where('periodo_id', $periodo_id)->getOne('periodo', 'periodo_nombre')['periodo_nombre'];
$nivel_nombre = $db->where('nivel_id', $nivel_id)->getOne('nivel', 'nivel_nombre')['nivel_nombre'];
echo json_encode([
'success' =>
"El nivel del periodo $periodo_nombre ha sido cambiado a $nivel_nombre"
]);
break;
case 'changeFechaInicio':
if (!isset($data['periodo_id'], $data['periodo_fecha_inicio'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['error' => 'Falta el id del periodo o la fecha de inicio']);
exit();
}
$periodo_id = $data['periodo_id'];
$periodo_fecha_inicio = $data['periodo_fecha_inicio'];
$db->where('periodo_id', $periodo_id)->update('periodo', ['periodo_fecha_inicio' => $periodo_fecha_inicio]);
$periodo_nombre = $db->where('periodo_id', $periodo_id)->getOne('periodo', 'periodo_nombre')['periodo_nombre'];
echo json_encode([
'success' =>
"La fecha de inicio del periodo $periodo_nombre ha sido cambiada a $periodo_fecha_inicio"
]);
break;
case 'changeFechaFin':
if (!isset($data['periodo_id'], $data['periodo_fecha_fin'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['error' => 'Falta el id del periodo o la fecha de fin']);
exit();
}
$periodo_id = $data['periodo_id'];
$periodo_fecha_fin = $data['periodo_fecha_fin'];
$db->where('periodo_id', $periodo_id)->update('periodo', ['periodo_fecha_fin' => $periodo_fecha_fin]);
$periodo_nombre = $db->where('periodo_id', $periodo_id)->getOne('periodo', 'periodo_nombre')['periodo_nombre'];
echo json_encode([
'success' =>
"La fecha de fin del periodo $periodo_nombre ha sido cambiada a $periodo_fecha_fin"
]);
break;
case 'updatePeriodo':
if (!isset($data['periodo_id'], $data['periodo_nombre'], $data['id_periodo_sgu'], $data['periodo_clave'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['error' => 'Faltan datos para actualizar el periodo']);
exit();
}
$periodo_id = $data['periodo_id'];
$db->where('periodo_id', $periodo_id)->update('periodo', array_filter($data, fn($key) => in_array($key, [
'periodo_nombre',
'id_periodo_sgu',
'periodo_clave',
]), ARRAY_FILTER_USE_KEY));
$periodo_nombre = $db->where('periodo_id', $periodo_id)->getOne('periodo', 'periodo_nombre')['periodo_nombre'];
echo json_encode([
'success' =>
"El periodo $periodo_nombre ha sido actualizado"
]);
break;
default:
header('HTTP/1.1 400 Bad Request');
echo json_encode(['error' => 'Acción no válida']);
exit();
}
break;
case 'POST':
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if (!isset($data['periodo_nombre'], $data['nivel_id'], $data['periodo_fecha_inicio'], $data['periodo_fecha_fin'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['error' => 'Faltan datos para crear el periodo']);
exit();
}
$newPeriodo = $db->insert(
'periodo',
array_filter($data, fn($key) => in_array($key, [
'periodo_nombre',
'nivel_id',
'periodo_fecha_inicio',
'periodo_fecha_fin',
'periodo_clave',
'id_periodo_sgu',
]), ARRAY_FILTER_USE_KEY)
);
echo json_encode([
'success' => true,
'message' => 'El periodo ha sido creado',
'periodo' => $newPeriodo
]);
break;
case 'DELETE':
// Delete a periodo
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if (!isset($data['periodo_id'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['error' => 'Falta el id del periodo']);
exit();
}
$periodo_id = $data['periodo_id'];
$periodo_nombre = $db->where('periodo_id', $periodo_id)->getOne('periodo', 'periodo_nombre')['periodo_nombre'];
$db->where('periodo_id', $periodo_id)->delete('periodo');
echo json_encode([
'success' => true,
'message' => "El periodo $periodo_nombre ha sido eliminado"
]);
break;
default:
header('HTTP/1.1 405 Method Not Allowed');
echo json_encode(['error' => 'Método no permitido']);
break;
}
} catch (PDOException $e) {
echo json_encode([
'error' => $e->getMessage(),
'query' => $db->getLastQuery(),
'exception' => $e->getTraceAsString()
]);
} catch (Exception $e) {
echo json_encode([
'error' => $e->getMessage(),
'exception' => $e->getTraceAsString()
]);
}

135
action/profesor_faltas.php Normal file
View File

@@ -0,0 +1,135 @@
<?
require_once "{$_SERVER['DOCUMENT_ROOT']}/class/c_login.php";
header('Content-Type: application/json');
if (!Login::is_logged()) {
header('HTTP/1.1 401 Unauthorized');
echo json_encode(['error' => 'No se ha iniciado sesión']);
exit();
}
$user = Login::get_user();
try {
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
$facultad = $_GET['facultad'] ?? $user->facultad['facultad_id'] ?? null;
$porcentaje = $_GET['porcentaje'] ?? null;
$faltas = $_GET['faltas'] ?? null;
if (!isset($facultad) || !is_numeric($facultad)) {
$error = 'No se ha seleccionado una facultad';
} else if ((!isset($faltas) || !is_numeric($faltas)) && (!isset($porcentaje) || !is_numeric($porcentaje))) {
$error = 'Debe especificar las faltas o el porcentaje';
} else if (isset($faltas) && (!is_numeric($faltas) || $faltas <= 0)) {
$error = 'Las faltas deben ser un número mayor a 0';
} else if (isset($porcentaje) && (!is_numeric($porcentaje) || $porcentaje <= 0)) {
$error = 'El porcentaje debe ser un número mayor a 0';
} else if (isset($faltas) && isset($porcentaje)) {
$error = 'No se puede especificar las faltas y el porcentaje al mismo tiempo';
} else if (!isset($facultad) || !is_numeric($facultad)) {
$error = 'Debe especificar una facultad';
}
if (isset($error)) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['error' => $error]);
exit();
}
// Initialize the data array
$data = array();
// Check if 'profesor' or 'supervisor' is set and prepare the specific part of the SQL query accordingly.
if (isset($_GET['profesor']) || isset($_GET['supervisor'])) {
$condition = isset($_GET['profesor'])
? "r.registro_fecha IS NULL AND NOT COALESCE(r.registro_justificada, FALSE)"
: "estado_supervisor_id = 2";
$filter = isset($faltas)
? "afcp.faltas >= :faltas"
: "afcp.porcentaje >= :porcentaje";
// Prepare the SQL query with placeholders for parameters
$data = array_column($db->query(
"WITH fechas AS (
SELECT
h.horario_id,
fechas_clase(h.horario_id, true) AS registro_fecha_ideal,
hp.profesor_id
FROM horario h
JOIN horario_profesor hp USING (horario_id)
WHERE (h.PERIODO_ID, h.FACULTAD_ID) = (:periodo_id, :facultad_id) AND hp.profesor_id <> 0
),
asistencia_faltas AS (
SELECT
f.profesor_id,
COUNT(1) AS total,
COUNT(1) FILTER (WHERE $condition AND f.registro_fecha_ideal <= current_date) AS faltas
FROM fechas f
LEFT JOIN registro r USING (registro_fecha_ideal, horario_id, profesor_id)
GROUP BY f.profesor_id
),
asistencia_faltas_con_porcentaje AS (
SELECT
af.profesor_id,
af.faltas,
af.total,
CASE
WHEN af.total > 0 THEN ROUND((af.faltas::NUMERIC / af.total) * 100, 2)
ELSE NULL
END AS porcentaje
FROM asistencia_faltas af
WHERE af.faltas > 0
)
SELECT
json_build_object(
'profesor', json_build_object(
'profesor_nombre', p.profesor_nombre,
'profesor_clave', p.profesor_clave,
'profesor_correo', p.profesor_correo
),
'profesor_id', afcp.profesor_id,
'faltas', afcp.faltas,
'total', afcp.total,
'porcentaje', afcp.porcentaje
) AS result_json
FROM asistencia_faltas_con_porcentaje afcp
JOIN profesor p USING (profesor_id)
WHERE $filter
ORDER BY afcp.porcentaje DESC;
",
[
'periodo_id' => $user->periodo_id,
'facultad_id' => $facultad,
] + (isset($faltas)
? ['faltas' => $faltas]
: ['porcentaje' => $porcentaje])
), 'result_json');
} else {
// Send a 400 Bad Request header and an error message in JSON format
header('HTTP/1.1 400 Bad Request');
echo json_encode(['error' => 'Especifique si las faltas son de profesor o supervisor']);
exit();
}
if (empty($data)) {
header('HTTP/1.1 404 Not Found');
echo json_encode(['error' => 'No se encontraron faltas']);
} else {
echo json_encode(
array_map(fn($item) => json_decode($item), $data)
);
}
break;
default:
header('HTTP/1.1 405 Method Not Allowed');
echo json_encode(['error' => 'Método no permitido']);
break;
}
} catch (PDOException $e) {
echo json_encode([
'error' => $e->getMessage(),
'query' => $db->getLastQuery(),
]);
}

113
action/puesto.php Normal file
View File

@@ -0,0 +1,113 @@
<?php
require_once "{$_SERVER['DOCUMENT_ROOT']}/class/c_login.php";
header('Content-Type: application/json');
if (!Login::is_logged()) {
header('HTTP/1.1 401 Unauthorized');
echo json_encode(['error' => 'No se ha iniciado sesión']);
exit();
}
$user = Login::get_user();
try {
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
// Fetch all puestos
$facultad_id = $user->facultad['facultad_id'] ?? -1;
$puestos = array_map(
fn($p) => array(
...$p,
'materias' => $db->where('puesto_id', $p['puesto_id'])
->join('puesto_materia', 'puesto_materia.materia_id = materia.materia_id', 'LEFT')
->get(tableName: 'materia', columns: ['materia.materia_id', 'materia_nombre', 'clave_materia',]),
'encargado' => $db->where('puesto_id', $p['puesto_id'])
->join('puesto_usuario', 'puesto_usuario.usuario_id = usuario.usuario_id', 'LEFT')
->getOne('usuario', ['usuario.usuario_id', 'usuario_nombre', 'usuario_clave']),
),
$db->orderBy('puesto.nombre', 'desc')
->where('facultad_id', $facultad_id)
->get(tableName: 'puesto', columns: 'puesto_id, nombre'),
);
echo json_encode($puestos);
break;
case 'POST':
$raw_input = file_get_contents('php://input');
$input_data = json_decode($raw_input, true);
if (!$input_data || !isset($input_data['puesto_nombre'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['error' => 'Datos inválidos']);
exit();
}
$puesto = $db->insert('puesto', [
'nombre' => $input_data['puesto_nombre'],
'facultad_id' => $user->facultad['facultad_id'],
], ['puesto_id', 'nombre', 'facultad_id']);
echo json_encode(
array(
...$puesto,
'materias' => [],
'encargado' => null,
),
);
break;
case 'PUT':
$raw_input = file_get_contents('php://input');
$input_data = json_decode($raw_input, true);
if (!$input_data || !isset($input_data['puesto_id'], $input_data['materias'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['error' => 'Datos inválidos']);
exit();
}
$db->where('puesto_id', $input_data['puesto_id'])->delete('puesto_materia');
$db->where('puesto_id', $input_data['puesto_id'])->delete('puesto_usuario');
foreach ($input_data['materias'] as $materia_id) {
$db->insert('puesto_materia', [
'puesto_id' => $input_data['puesto_id'],
'materia_id' => $materia_id,
]);
}
if (isset($input_data['usuario_id']))
$db->insert('puesto_usuario', [
'puesto_id' => $input_data['puesto_id'],
'usuario_id' => $input_data['usuario_id'],
]);
echo json_encode(['msg' => 'Puesto actualizado exitosamente']);
break;
case 'DELETE':
$raw_input = file_get_contents('php://input');
$input_data = json_decode($raw_input, true);
if (!$input_data || !isset($input_data['puesto_id'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['error' => 'Datos inválidos']);
exit();
}
$db->where('puesto_id', $input_data['puesto_id'])->delete('puesto');
echo json_encode(['msg' => 'Puesto eliminado exitosamente']);
break;
default:
header('HTTP/1.1 405 Method Not Allowed');
echo json_encode(['error' => 'Método no permitido']);
break;
}
} catch (PDOException $e) {
echo json_encode([
'error' => $e->getMessage(),
'query' => $db->getLastQuery(),
'exception' => $e->getTraceAsString()
]);
}

View File

@@ -0,0 +1,60 @@
<?
#input $_GET['id_espacio_sgu']
define("INFORMATION", [
'POST' => [
'profesor_id',
'horario_id',
'estado',
'comentario',
'supervisor_id',
],
]);
#output rutas: [ ...ruta, salones: [{...salon}] ]
header('Content-Type: application/json charset=utf-8');
#return html
$ruta = "../";
require_once "../class/c_login.php";
// check method
try {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// check parameters
$raw = file_get_contents('php://input');
$post_data = json_decode($raw, true);
// if it's a list
// step 1: get subrutas
if (empty($post_data)) {
http_response_code(400);
echo json_encode(['error' => 'No hay clases pendientes']);
exit;
}
$data = $db->query(
'INSERT INTO registro (profesor_id, horario_id, registro_fecha_supervisor, estado_supervisor_id, registro_fecha_ideal, supervisor_id, comentario)
VALUES' .
implode(',', array_map(fn($x) => "({$x['profesor_id']} , {$x['horario_id']}, NOW()," . (is_null($x['estado']) ? 'null' : $x['estado']) . ", NOW(), {$x['supervisor_id']}," . (empty($x['comentario']) ? 'null' : "'{$x['comentario']}'") . ')', $post_data))
. ' ON CONFLICT (profesor_id, horario_id, registro_fecha_ideal) DO UPDATE SET estado_supervisor_id = EXCLUDED.estado_supervisor_id, registro_fecha_supervisor = NOW(), comentario = EXCLUDED.comentario, supervisor_id = EXCLUDED.supervisor_id
RETURNING *'
);
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} else {
http_response_code(405);
echo json_encode(['error' => 'method not allowed']);
exit;
}
} catch (PDOException $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
'query' => $db->getLastQuery(),
'post_data' => $post_data,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
} catch (Exception $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
}

View File

@@ -0,0 +1,195 @@
<?php
/*
Cambia de estado la reposición
*/
$pag = "../reposiciones_crear.php";
$ruta = "../";
require_once "../class/c_login.php";
require_once "../class/mailer.php";
define("COORDINADOR", 9);
define("SUPERVISOR", 7);
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']);
$pag = "../reposiciones_autorizar.php";
if(!isset($_POST["id"]) || !isset($_POST["edo"]) ){
header("Location: ".$pag."?error=0");
exit();
}
$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
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)){
$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 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();
$prof_correos=array();
$jefe_correos=[];
$coord_correos=[];
foreach($correos_rs as $correo){
if( count($prof_correos)==0 && $correo["profesor_correo"]!=""){
if( !isset($prof_correos["correo"]) || !in_array($correo["profesor_correo"], $prof_correos["correo"]) ){
array_push($prof_correos, $correo["profesor_correo"]);
}
}
if( count($jefe_correos)==0 && $correo["jefe_correo"]!=""){
if(!isset($jefe_correos["correo"]) || !in_array($correo["jefe_correo"], $jefe_correos["correo"])){
array_push($jefe_correos, $correo["jefe_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->query("SELECT DISTINCT sup.usuario_correo as supervisor_correo
FROM horario_supervisor hs
inner join usuario sup on sup.usuario_id =hs.usuario_id
where :facultad = ANY(hs.facultad_id_array)",
[':facultad'=>$reposicion_rs["facultad_id"]] );
$sup_correos=[];
foreach($correosSup_rs as $correo){
array_push($sup_correos, $correo["supervisor_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]
);
}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];
$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>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;
}
if($to!= "" && ENVIO_CORREOS){
$texto = '<body >
<img src="https://paad.lci.ulsa.mx/imagenes/logo_lasalle.png" alt="La Salle" style="margin-bottom:60px">
'.$texto.'
</body>';
require_once('../include/phpmailer/PHPMailerAutoload.php');
if($_ENV['DB_NAME'] == "paad_pruebas"){
$asunto = "PRUEBAS-".$asunto;
Mailer::enviarCorreo("alejandro.lara@lasalle.mx", $asunto, $texto, true);
}else{
Mailer::enviarCorreo($to, $asunto, $texto, true);
}
}
/*
$log->appendLog($_SESSION["usuario_id"], $_SESSION["usuario_nombre"]." ".$_SESSION["usuario_apellidos"], $desc_log);
*/
header("Location: ".$pag."?ok=".$ok);
exit();
?>

View File

@@ -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_reposicion_solicitud(:id, :creador)', [":id"=> $id, ":creador"=>$creador]);
$return["ok"] = "La reposición se borró correctamente";
}catch(Exception $e){
$return["error"] = "Ocurrió un error al borrar la reposición.";
}
}
echo json_encode($return);
?>

View File

@@ -0,0 +1,208 @@
<?php
/*
* Inserta reposición
*/
$pag = "../reposiciones_crear.php";
$ruta = "../";
require_once "../class/c_login.php";
require_once "../class/mailer.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']);
//$user->access();
$duracion_id = filter_input(INPUT_POST, "duracion", FILTER_SANITIZE_NUMBER_INT);//Id reposicion
$bloque = filter_input(INPUT_POST, "bloque", FILTER_SANITIZE_NUMBER_INT);//
$ciclo = filter_input(INPUT_POST, "ciclo", FILTER_SANITIZE_NUMBER_INT);//
$fecha_falta = trim(htmlspecialchars($_POST["fecha_falta"], ENT_QUOTES, "UTF-8"));//Reposicion
$fecha = trim(htmlspecialchars($_POST["fecha_inicial"], ENT_QUOTES, "UTF-8"));//Reposicion
$fecha_cambio = trim(htmlspecialchars($_POST["fecha_cambio"], ENT_QUOTES, "UTF-8"));//Cambio salón
$hora_ini = filter_input(INPUT_POST, "hora_ini", FILTER_SANITIZE_NUMBER_INT);//limpia texto hora reposicion
$min_ini = filter_input(INPUT_POST, "min_ini", FILTER_SANITIZE_NUMBER_INT);//limpia texto
$hor = filter_input(INPUT_POST, "horario", FILTER_SANITIZE_NUMBER_INT);//limpia texto
$alumnos = filter_input(INPUT_POST, "alumnos", FILTER_SANITIZE_NUMBER_INT);//limpia texto
$tipo = filter_input(INPUT_POST, "tipo", FILTER_SANITIZE_NUMBER_INT);//1 Repo , 0 Cambio
$aula = filter_input(INPUT_POST, "aula", FILTER_SANITIZE_NUMBER_INT);//1 regular , 2 sala computo, 3 otro facultad
$salon = NULL;
if(!$user->jefe_carrera){//coordinador
if(isset($_POST["salon"]) && $_POST["salon"] != "")
$salon = filter_input(INPUT_POST, "dlSalon", FILTER_SANITIZE_NUMBER_INT);//1 regular , 2 sala computo, 3 otro facultad
}
if(empty($_POST["prof"]))
$prof = $user->user["id"];
else
$prof = filter_input(INPUT_POST, "prof", FILTER_SANITIZE_NUMBER_INT);//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"];
//-- 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";
if($tipo == 1){//Reposición
$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));
}else{
$fecha_cambio = DateTime::createFromFormat('d/m/Y', $fecha_cambio)->format('Y-m-d');
$dia_falta = date('w', strtotime($fecha_cambio));
}
//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);*/
exit();
}
//Obtiene materia
$materia_rs = $db->querySingle('SELECT materia_nombre from materia where materia_id = :mat',[':mat' => $materia]);
//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) and coor.usuario_correo != \'\'',[':rol_coord' => COORDINADOR, ':id_usr' => $user->user["id"]]
);
if( count($correos_rs) > 0 ){
$to = $correos_rs["usuario_correo"];
}
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();
}
try{
if($user->jefe_carrera){//jefe
$db->query('SELECT * from fi_reposicion_solicitud(:f_falta, :f_nueva, :hora_nueva, :hor, :prof, 1, :desc, :alumnos, true, :aula, :duracion, :usr, :bloque, :ciclo)',
[':f_falta' => $fecha_falta, ':f_nueva' => $fecha_new, ':hora_nueva' => $hora, ':hor' => $hor,
':prof' => $prof, ':desc' => $comentario, ':alumnos' => $alumnos, ':aula' => $aula, ':duracion' => $duracion_tiempo, ':usr'=>$user->user["id"],
':bloque' => $bloque, ':ciclo' => $ciclo
]
);
}else{//coordinador
echo 'SELECT * from fi_reposicion_solicitud(:f_falta, :f_nueva, :hora_nueva, :hor, :prof, 2, :desc, :alumnos, true, :aula, :duracion, :usr, :bloque, :ciclo, '.$salon.')';
$db->query('SELECT * from fi_reposicion_solicitud(:f_falta, :f_nueva, :hora_nueva, :hor, :prof, 2, :desc, :alumnos, true, :aula, :duracion, :usr, :bloque, :ciclo, :salon)',
[':f_falta' => $fecha_falta, ':f_nueva' => $fecha_new, ':hora_nueva' => $hora, ':hor' => $hor,
':prof' => $prof, ':desc' => $comentario, ':alumnos' => $alumnos, ':aula' => $aula, ':duracion' => $duracion_tiempo, ':usr'=>$user->user["id"],
':bloque' => $bloque, ':ciclo' => $ciclo, ':salon'=>$salon
]
);
}
}catch(Exception $e){
echo "ERROR Reposición<br>".$e->getMessage();
//header("Location: ".$pag."?error=1");
exit();
}
$fecha_clase = date('d/m/Y', strtotime($fecha_falta));
$fecha_nueva = date('d/m/Y', strtotime($fecha_new));
$texto = "<p>Se creó una reposición nueva.</p>";
$texto .= "<p><b>".mb_strtoupper($materia_rs["materia_nombre"])."</b> del día <b>".$fecha_clase." a las ".$horario_rs["horario_hora"]." hrs. </b> se propone reponer el <b>".$fecha_nueva." 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);*/
}else{//Cambio salón / hora
try{
if($user->jefe_carrera){//jefe
$db->query('SELECT * from fi_reposicion_solicitud(:f_falta, :f_nueva, :hora_nueva, :hor, :prof, 1, :desc, :alumnos, false, :aula, :duracion, :usr, :bloque, :ciclo)',
[':f_falta' => $fecha_cambio, ':f_nueva' => $fecha_cambio, ':hora_nueva' => $hora, ':hor' => $hor,
':prof' => $prof, ':desc' => $comentario, ':alumnos' => $alumnos, ':aula' => $aula, ':duracion' => $duracion_tiempo, ':usr'=>$user->user["id"],
':bloque' => $bloque, ':ciclo' => $ciclo
]
);
}else{//coordinador
$db->query('SELECT * from fi_reposicion_solicitud(:f_falta, :f_nueva, :hora_nueva, :hor, :prof, 2, :desc, :alumnos, false, :aula, :duracion, :usr, :bloque, :ciclo, :salon)',
[':f_falta' => $fecha_cambio, ':f_nueva' => $fecha_cambio, ':hora_nueva' => $hora, ':hor' => $hor,
':prof' => $prof, ':desc' => $comentario, ':alumnos' => $alumnos, ':aula' => $aula, ':duracion' => $duracion_tiempo, ':usr'=>$user->user["id"],
':bloque' => $bloque, ':ciclo' => $ciclo, ':salon'=>$salon
]
);
}
}catch(Exception $e){
echo "ERROR Cambio<br>".$e->getMessage();
//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." 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">
'.$texto.'
</body>';
require_once('../include/phpmailer/PHPMailerAutoload.php');
if($_ENV['DB_NAME'] == "paad_pruebas"){
$asunto = "PRUEBAS-".$asunto;
Mailer::enviarCorreo("alejandro.lara@lasalle.mx", $asunto, $texto, true);
}else{
Mailer::enviarCorreo($to, $asunto, $texto, true);
}
}
header("Location: ".$pag."?ok=0");
exit();
?>

View File

@@ -0,0 +1,45 @@
<?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 del profesor.";
}else{
$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"]] );
}catch(Exception $e){
$return["error"] = "Ocurrió un error al leer los datos de las materias.";
echo json_encode($return);
}
$mat_arr = array();
foreach($rs as $m){
$mat_arr[] = array("horario_id"=>$m["horario_id"], "horario_dia"=>$m["horario_dia"],
"horario_hora"=>substr($m["horario_hora"], 0, 2), "horario_min"=>substr($m["horario_hora"], 3, 2),
"materia_nombre"=>$m["materia_nombre"].' - '.$m["horario_dia_nombre"]." ".substr($m["horario_hora"], 0, -3),
"grupo"=>$m["horario_grupo"], "duracion" => $m["duracion"]
);
}
$return["materias"] = $mat_arr;
}
echo json_encode($return);
?>

View File

@@ -0,0 +1,87 @@
<?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_reposicion_solicitud(:id, NULL, NULL, NULL, NULL, NULL, NULL, NULL, :sup)',
[':id' => $id, ':sup'=>$user->user["id"]]
);
}else{//coordinador
$rs = $db->querySingle('SELECT * from fs_reposicion_solicitud(:id, :fac, NULL, NULL, NULL, NULL, NULL, NULL, null)',
[':id' => $id, ":fac"=>$user->facultad["facultad_id"] ]
);
}
}catch(Exception $e){
$return["error"] = "Ocurrió un error al leer los datos de la reposición.";
echo json_encode($return);
exit();
}
$return["fecha_clase"] = date('d/m/Y', strtotime($rs["fecha_clase"]));
$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_interval"];
// $return["carrera"] = $rs["PlanEstudio_desc"];
$return["horario"] = $rs["horario_id"];
$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["ciclo"] = $rs["ciclo"];
$return["bloque"] = $rs["bloque"];
$return["profesor"] = $rs["profesor_id"];
$return["profesor_nombre"] = $rs["profesor_nombre"];
$return["comentario"] = $rs["descripcion"];
$return["alumnos"] = $rs["alumnos"];
$return["tipo"] = $rs["es_reposicion"];
$return["aula"] = $rs["tipoaula_id"];
$return["aula_desc"] = $rs["tipoaula_nombre"];
$return["aula_supervisor"] = $rs["tipoaula_supervisor"];
$return["dia"] = date('w', strtotime($rs["fecha_clase"]));
$return["motivo_cancelacion"] = $rs["motivo_cancelacion"];
$return["estado"] = $rs["estado_reposicion_id"];
$return["facultad"] = $rs["facultad_nombre"];
$return["carrera"] = $rs["carrera_nombre"];
$return["grupo"] = $rs["horario_grupo"];
}
echo json_encode($return);
?>

View File

@@ -0,0 +1,124 @@
<?php
/*
* Actualiza 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']);
/*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
$bloque = filter_input(INPUT_POST, "bloque", FILTER_SANITIZE_NUMBER_INT);//
$ciclo = filter_input(INPUT_POST, "ciclo", FILTER_SANITIZE_NUMBER_INT);//
$fecha_falta = trim(htmlspecialchars($_POST["fecha_falta"], ENT_QUOTES, "UTF-8"));//limpia texto
$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
$hor = filter_input(INPUT_POST, "horario", FILTER_SANITIZE_NUMBER_INT);//limpia texto
$alumnos = filter_input(INPUT_POST, "alumnos", FILTER_SANITIZE_NUMBER_INT);//limpia texto
$tipo = filter_input(INPUT_POST, "tipo", FILTER_SANITIZE_NUMBER_INT);//1 Repo , 0 Cambio
$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"];
$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));
//echo $fecha_new."<br>";
//echo $fecha_fin_new."<br>";
if($tipo == 1){//Reposición
$fecha_falta = DateTime::createFromFormat('d/m/Y', $fecha_falta)->format('Y-m-d');
$dia_falta = date('w', strtotime($fecha_falta));
}else{
$fecha_cambio = DateTime::createFromFormat('d/m/Y', $fecha_cambio)->format('Y-m-d');
$dia_falta = date('w', strtotime($fecha_cambio));
}
//Valida que tenga clase en la fecha de falta
if(intval($dia) != intval($dia_falta)){
//header("Location:".$pag."?error=11");
echo intval($dia)." != ".intval($dia_falta);
exit();
}
if($tipo == 1){//Reposición
// Valida que grupo no tenga clases
/*$result = validaConflictoHoras($pdo, $gpo, $dia, $hora, $materia, "-", $fecha_ini, $fecha_fin, $duracion);
if($result != ""){//error
//echo $result;
header("Location:".$pag."?error=7");
exit();
}
//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_profesor_reposicion"];
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_reposicion_solicitud(:id, :f_falta, :f_nueva, :hora_nueva, NULL, 1, :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
]
);
}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)'";
print_r(
[':id'=> $id, ':f_falta' => $fecha_falta, ':f_nueva' => $fecha_new, ':hora_nueva' => $hora,
':desc' => $comentario, ':alumnos' => $alumnos, ':aula' => $aula, ':duracion' => $duracion_tiempo
]);
exit();
}
header("Location: ".$pag);
exit();
?>

28
action/rutas.php Normal file
View File

@@ -0,0 +1,28 @@
<?
header('Content-Type: application/json charset=utf-8');
$ruta = "../";
require_once "../class/c_login.php";
$universidad_la_salle = $db
->where('salon', 'UNIVERSIDAD LA SALLE', 'ILIKE')
->getOne('salon_view_mat');
$rutas =
array_map(
function ($ruta) use ($db) {
$ruta['subrutas'] =
$db
->where('id_espacio_padre', $ruta['id_espacio_sgu'])
->orderBy('salon')
->get('salon_view_mat');
return $ruta;
},
$db
->where('id_espacio_padre', $universidad_la_salle['id_espacio_sgu'])
->orderBy('salon')
->get('salon_view_mat')
);
// echo json_encode($universidad_la_salle, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); EXIT;
echo json_encode($rutas, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

View File

@@ -0,0 +1,201 @@
<?
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
#input $_GET['id_espacio_sgu']
$information = [
'GET' => [
'id_espacio_sgu',
'bloque_horario_id',
],
];
#output rutas: [ ...ruta, salones: [{...salon}] ]
header('Content-Type: application/json charset=utf-8');
$ruta = "../";
require_once "../class/c_login.php";
// check method
try {
global $db;
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
// check parameters
array_walk($information['GET'], function ($value) {
if (!array_key_exists($value, $_GET)) {
http_response_code(400);
echo json_encode(['error' => "$value is required"]);
exit;
}
});
// step 1: get subrutas
$data = $db
->where('tiene_salones')
->where("{$_GET['id_espacio_sgu']} = ANY(id_espacio_sgu_array)")
->get('salon_view_mat', columns: 'id_espacio_sgu, salon, salon_id, salon_array');
$columns = [
// horario
'horario_view.horario_id',
'horario_hora',
'horario_grupo',
'horario_fin',
'materia',
'carrera',
'nivel',
'horario_view.salon',
'facultad',
// profesor
'profesor.profesor_id',
'profesor_clave',
'profesor_nombre',
'profesor_correo',
// registro
'registro_fecha',
'registro_retardo',
'registro.reposicion_id',
'estado_supervisor_id',
'comentario',
// reposicion
'reposicion_fecha',
'reposicion_hora',
'reposicion_hora_fin',
'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(
"SELECT " . implode(', ', $columns) . <<<SQL
FROM horario_view
NATURAL JOIN periodo
JOIN bloque_horario ON (bloque_horario.hora_inicio, bloque_horario.hora_fin) OVERLAPS (horario_view.horario_hora, horario_view.horario_hora + horario_view.duracion)
NATURAL JOIN salon_view_mat
NATURAL JOIN horario_profesor
NATURAL JOIN profesor
LEFT JOIN registro ON (registro.profesor_id, registro.horario_id, registro.registro_fecha_ideal) = (profesor.profesor_id, horario_view.horario_id, $fecha::DATE)
NATURAL LEFT JOIN reposicion
LEFT JOIN salon 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 horario_dia = EXTRACT(DOW FROM $fecha::DATE)
AND bloque_horario.id = :bloque_horario_id
AND salon_view_mat.id_espacio_padre = :id_espacio_sgu
ORDER BY horario_hora, salon_view_mat.salon;
SQL,
[
'bloque_horario_id' => $_GET['bloque_horario_id'],
'id_espacio_sgu' => $ruta['id_espacio_sgu'],
]
) ,
// 'query' => $db->getLastQuery(),
'reposiciones' => $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' => $ruta['id_espacio_sgu'],
]
)*/ ,
],
$ruta,
),
$data
);
$data = array_filter(
$data,
fn($ruta) => count($ruta['horarios']) > 0 || count($ruta['reposiciones']) > 0
);
echo json_encode(array_values($data), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} else {
http_response_code(405);
echo json_encode(['error' => 'method not allowed']);
exit;
}
} catch (PDOException $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
// 'query' => $db->getLastQuery(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
} catch (Exception $th) {
http_response_code(500);
echo json_encode([
'error' => $th->getMessage(),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
}

View File

@@ -0,0 +1,24 @@
{
"type": "array",
"items": {
"type": "object",
"properties": {
"profesor_id": {
"type": "integer"
},
"horario_id": {
"type": "integer"
},
"estado": {
"type": ["integer", "null"]
},
"comentario": {
"type": "string"
},
"supervisor_id": {
"type": "integer"
}
},
"required": ["profesor_id", "horario_id", "comentario", "supervisor_id"]
}
}

23
action/usuario_find.php Normal file
View File

@@ -0,0 +1,23 @@
<?php
$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'];
}
echo json_encode($db->query("SELECT * FROM fs_profesores(:nombre, :clave, :facultad) ORDER BY profesor_nombre", [':nombre' => $nombre, ':clave' => $clave, ':facultad' => $facultad]));
?>

28
action/usuarios.php Normal file
View File

@@ -0,0 +1,28 @@
<?php
header('Content-Type: application/json');
$ruta = "../";
require_once "../class/c_login.php";
// check if the session is started
if (!isset($_SESSION['user']))
die(json_encode(['error' => 'No se ha iniciado sesión']));
$user = unserialize($_SESSION['user']);
$ruta = "../";
require_once "../include/bd_pdo.php";
$facultad_id = $user->facultad['facultad_id'];
$materias = $db->query(<<<SQL
SELECT usuario_id, usuario_nombre, usuario_clave
FROM usuario
WHERE
(facultad_id = :facultad_id OR :facultad_id IS NULL)
ORDER BY usuario_nombre ASC
SQL,
array('facultad_id' => $facultad_id)
);
// $user->print_to_log("Crea carrera", old: $_POST);
die(json_encode($materias));