Pequeños pasos con fullcalendar

This commit is contained in:
Markines16 2021-05-30 23:42:30 +02:00 committed by GitHub
parent 4692af8ddd
commit af0d9ccd25
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 274 additions and 2 deletions

139
panel_manager/eventos.php Normal file
View File

@ -0,0 +1,139 @@
<?php
require_once __DIR__.'/includes/config.php';
use es\ucm\fdi\aw\eventos\Evento;
use es\ucm\fdi\aw\Aplicacion as App;
use es\ucm\fdi\aw\http\ContentTypeNoSoportadoException;
use es\ucm\fdi\aw\http\ParametroNoValidoException;
// Procesamos la cabecera Content-Type
$contentType= $_SERVER['CONTENT_TYPE'] ?? 'application/json';
$contentType = strtolower(str_replace(' ', '', $contentType));
// Verificamos corresponde con uno de los tipos soportados
$acceptedContentTypes = array('application/json;charset=utf-8', 'application/json');
$found = false;
foreach ($acceptedContentTypes as $acceptedContentType) {
if (substr($contentType, 0, strlen($acceptedContentType)) === $acceptedContentType) {
$found=true;
break;
}
}
if (!$found) {
throw new ContentTypeNoSoportadoException('Este servicio REST sólo soporta el content-type application/json');
}
$result = null;
/**
* Las API REST usan la semántica de los métoods HTTP para gestionar las diferentes peticiones:
* https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods
*/
switch($_SERVER['REQUEST_METHOD']) {
// Consulta de datos
case 'GET':
// Comprobamos si es una consulta de un evento concreto -> eventos.php?idEvento=XXXXX
$idEvento = filter_input(INPUT_GET, 'idEvento', FILTER_VALIDATE_INT);
if ($idEvento) {
$result = [];
$result[] = Evento::buscaPorId((int)$idEvento);
} else {
// Comprobamos si es una lista de eventos entre dos fechas -> eventos.php?start=XXXXX&end=YYYYY
$start = filter_input(INPUT_GET, 'start', FILTER_VALIDATE_REGEXP, array("options" => array("regexp"=>"/\d{4}-((0[1-9])|(1[0-2]))-((0[1-9])|([1-2][0-9])|(3[0-1]))/")));
$end = filter_input(INPUT_GET, 'end', FILTER_VALIDATE_REGEXP, array("options" => array("default" => null, "regexp"=>"/\d{4}-((0[1-9])|(1[0-2]))-((0[1-9])|([1-2][0-9])|(3[0-1]))/")));
if ($start) {
$startDateTime = $start . ' 00:00:00';
$endDateTime = $end;
if ($end) {
$endDateTime = $end. ' 00:00:00';
}
$result = Evento::buscaEntreFechas(1, $startDateTime, $endDateTime);
} else {
// Comprobamos si es una lista de eventos completa
$result = Evento::buscaTodosEventos(1); // HACK: normalmente debería de ser App::getSingleton()->idUsuario();
}
}
// Generamos un array de eventos en formato JSON
$json = json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
http_response_code(200); // 200 OK
header('Content-Type: application/json; charset=utf-8');
header('Content-Length: ' . mb_strlen($json));
echo $json;
break;
// Añadir un nuevo evento
case 'POST':
// 1. Leemos el contenido que nos envían
$entityBody = file_get_contents('php://input');
// 2. Verificamos que nos envían un objeto
$dictionary = json_decode($entityBody);
if (!is_object($dictionary)) {
throw new ParametroNoValidoException('El cuerpo de la petición no es valido');
}
// 3. Reprocesamos el cuerpo de la petición como un array PHP
$dictionary = json_decode($entityBody, true);
$dictionary['userId'] = 1;// HACK: normalmente debería de ser App::getSingleton()->idUsuario();
$e = Evento::creaDesdeDicionario($dictionary);
error_log("hmmm");
// 4. Guardamos el evento en BD
$result = Evento::guardaOActualiza($e);
// 5. Generamos un objecto como salida.
$json = json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
http_response_code(201); // 201 Created
header('Content-Type: application/json; charset=utf-8');
header('Content-Length: ' . mb_strlen($json));
echo $json;
break;
case 'PUT':
// 1. Comprobamos si es una consulta de un evento concreto -> eventos.php?idEvento=XXXXX
$idEvento = filter_input(INPUT_GET, 'idEvento', FILTER_VALIDATE_INT);
// 2. Leemos el contenido que nos envían
$entityBody = file_get_contents('php://input');
// 3. Verificamos que nos envían un objeto
$dictionary = json_decode($entityBody);
if (!is_object($dictionary)) {
throw new ParametroNoValidoException('El cuerpo de la petición no es valido');
}
// 4. Reprocesamos el cuerpo de la petición como un array PHP
$dictionary = json_decode($entityBody, true);
$e = Evento::buscaPorId($idEvento);
$e->actualizaDesdeDiccionario($dictionary, ['id', 'userId']);
$result = Evento::guardaOActualiza($e);
// 5. Generamos un objecto como salida.
$json = json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
http_response_code(200); // 200 OK
header('Content-Type: application/json; charset=utf-8');
header('Content-Length: ' . mb_strlen($json));
echo $json;
break;
case 'DELETE':
// 1. Comprobamos si es una consulta de un evento concreto -> eventos.php?idEvento=XXXXX
$idEvento = filter_input(INPUT_GET, 'idEvento', FILTER_VALIDATE_INT);
// 2. Borramos el evento
Evento::borraPorId($idEvento);
http_response_code(204); // 204 No content (como resultado)
header('Content-Type: application/json; charset=utf-8');
header('Content-Length: 0');
break;
default:
throw new MetodoNoSoportadoException($_SERVER['REQUEST_METHOD']. ' no está soportado');
break;
}

View File

@ -1,5 +1,8 @@
<?php
<?php
//General Config File:
require_once('../assets/php/config.php');
//Controller file:
@ -146,6 +149,9 @@
case "success":
$panel = Manager_panel::success();
break;
case "calendar":
$panel = Manager_panel::calendar($manager);
break;
default:
$panel = Manager_panel::welcome($manager);
break;
@ -165,10 +171,13 @@
//Specific page content:
$section = '<!-- Manager Panel -->
<link rel="stylesheet" href="../assets/css/manager.css">
<section id="manager_panel">
<!-- Contents -->
<div class="row">
'.$panel.'
</div>
</section>';
@ -176,3 +185,11 @@
//General page content:
require RAIZ_APP.'/HTMLtemplate.php';
?>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
<script src="./sessioncalendar.js"></script>

View File

@ -30,6 +30,8 @@
<p>Dirección: '.$c_dir.'</p>
<p>Telefono: '.$c_tel.'</p> <br>
<p>Espero que estes pasando un buen dia</p>
<a href="?state=calendar"> calendario </a>
</div>';
return $panel;
@ -72,7 +74,14 @@
return $panel;
}
static function calendar(){
$panel = '
<div class="code">
<div id="calendar"></div>
</div>';
return $panel;
}
static function success(){
$panel = '<div class="code info">
<h1>Operacion completada.</h1>

View File

@ -0,0 +1,107 @@
$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
editable:true,
header:{
left:'prev,next today',
center:'title',
right:''
},
events: 'eventos.php',
selectable:true,
selectHelper:true,
select: function(start, end, allDay)
{
var title = confirm("¿Estas son las fechas correctas?");
if(title)
{
var e = {
"start" : $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss"),
"end" : $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss"),
};
$.ajax({
url:"eventos.php",
type:"POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data:JSON.stringify(e),
success:function()
{
calendar.fullCalendar('refetchEvents');
alert("Added Successfully");
}
})
}
},
editable:true,
eventResize:function(event)
{
var e = {
"id" : event.id,
"userId": event.userId,
"start" : $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss"),
"end" : $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss"),
"title" : event.title
};
$.ajax({
url:"eventos.php?idEvento="+event.id,
type:"PUT",
contentType: 'application/json; charset=utf-8',
dataType:"json",
data:JSON.stringify(e),
success:function(){
calendar.fullCalendar('refetchEvents');
alert('Event Update');
}
})
},
eventDrop:function(event)
{
var e = {
"id" : event.id,
"userId": event.userId,
"start" : $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss"),
"end" : $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss"),
"title" : event.title
};
$.ajax({
url:"eventos.php?idEvento="+event.id,
contentType: 'application/json; charset=utf-8',
dataType: "json",
type:"PUT",
data:JSON.stringify(e),
success:function()
{
calendar.fullCalendar('refetchEvents');
alert("Event Updated");
}
});
},
eventClick:function(event)
{
if(confirm("Are you sure you want to remove it?"))
{
var id = event.id;
$.ajax({
url:"eventos.php?idEvento="+id,
contentType: 'application/json; charset=utf-8',
dataType: "json",
type:"DELETE",
success:function()
{
calendar.fullCalendar('refetchEvents');
alert("Event Removed");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
})
}
},
});
});