FC funcional entero

This commit is contained in:
Markines16 2021-06-06 13:35:19 +02:00 committed by GitHub
parent bb6355fdc1
commit a57751e699
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 733 additions and 165 deletions

View File

@ -0,0 +1,261 @@
<?php
require_once('../assets/php/config.php');
include_once($prefix.'assets/php/includes/event.php');
include_once($prefix.'assets/php/includes/session.php');
$contentType= $_SERVER['CONTENT_TYPE'] ?? 'application/json';
$contentType = strtolower(str_replace(' ', '', $contentType));
// Verify the content type is supported
$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;
}
}
switch($_SERVER['REQUEST_METHOD']) {
// Get Events
case 'GET':
error_log("GET");
$hall = $_GET["hall"];
$cinema = $_SESSION["cinema"];
// 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 = Event::searchEventsBetween2dates($startDateTime, $endDateTime, $hall,$cinema);
} else {
// Comprobamos si es una lista de eventos completa
$result = Event::searchAllEvents($hall,$cinema);
}
// 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;
// Add Session
case 'POST':
error_log("POST");
$errors = [];
$data = [];
//Correct reply to verify the session has been correctly added
$correct_response = 'Operación completada';
//Check if the body is ok
$entityBody = file_get_contents('php://input');
$dictionary = json_decode($entityBody);
if (!is_object($dictionary))
$errors['global'] = 'El cuerpo de la petición no es valido';
$price = $dictionary->{"price"} ?? "";
$format = $dictionary->{"format"} ?? "";
$hall = $dictionary->{"hall"} ?? "";
$startDate = $dictionary->{"startDate"} ?? "";
$endDate = $dictionary->{"endDate"} ?? "";
$startHour = $dictionary->{"startHour"} ?? "";
$idfilm = $dictionary->{"idFilm"} ?? "";
//Check errors in inputs
if (empty($price) || $price <= 0 )
$errors['price'] = 'El precio no puede ser 0.';
if (empty($format))
$errors['format'] = 'El formato no puede estar vacio. Ej: 3D, 2D, voz original';
if (empty($hall) || $hall<=0 )
$errors['hall'] = 'La sala no puede ser 0 o menor';
if (empty($startDate))
$errors['startDate'] = 'Las sesiones tienen que empezar algun dia.';
else if (empty($endDate))
$errors['endDate'] = 'Las sesiones tienen que teminar algun dia.';
else {
$start = strtotime($startDate);
$end = strtotime($endDate);
$start = date('Y-m-d', $start);
$end = date('Y-m-d', $end);
if($start > $end)
$errors['date'] = 'La fecha inicial no puede ser antes o el mismo dia que la final.';
}
if (empty($startHour))
$errors['startHour'] = 'Es necesario escoger el horario de la sesion.';
if (!is_numeric($idfilm) && $idfilm <= 0 )
$errors['idfilm'] = 'No se ha seleccionado una pelicula.';
//Create as many sessions as the diference between start and end date tell us. 1 session per day
while($startDate < $endDate && empty($errors)){
$msg = Session::create_session($_SESSION["cinema"], $hall, $startHour, $startDate, $idfilm, $price, $format);
if(strcmp($msg,$correct_response)!== 0)
$errors['global'] = $msg;
else
$data['message'] = $msg;
$startDate = date('Y-m-d H:i:s', strtotime( $startDate . ' +1 day'));
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
}
echo json_encode($data);
break;
//Edit session
case 'PUT':
//Correct reply to verify the session has been correctly edited
$correct_response = 'Se ha editado la session con exito';
$errors = [];
$data = [];
//Check if the body is ok
$entityBody = file_get_contents('php://input');
$dictionary = json_decode($entityBody);
if (!is_object($dictionary))
$errors['global'] = 'El cuerpo de la petición no es valido';
//Check if the user is droping an event in a new date
if(isset($_GET["drop"]) && $_GET["drop"]){
$or_hall = $dictionary->{"idhall"} ?? "";
$or_date = $dictionary->{"startDate"} ?? "";
$or_start = $dictionary->{"startHour"} ?? "";
$price = $dictionary->{"price"} ?? "";
$idfilm = $dictionary->{"idfilm"} ?? "";
$format = $dictionary->{"format"} ?? "";
$new_date = $dictionary->{"newDate"} ?? "";
$msg = Session::edit_session($_SESSION["cinema"], $or_hall, $or_date, $or_start, $or_hall, $new_date, $new_date, $idfilm, $price, $format);
if(strcmp($msg,$correct_response)!== 0)
http_response_code(400);
else
http_response_code(200);
}else{
//Edit session from a form
$price = $dictionary->{"price"} ?? "";
$format = $dictionary->{"format"} ?? "";
$hall = $dictionary->{"hall"} ?? "";
$startDate = $dictionary->{"startDate"} ?? "";
$endDate = $dictionary->{"endDate"} ?? "";
$startHour = $dictionary->{"startHour"} ?? "";
$idfilm = $dictionary->{"idFilm"} ?? "";
$or_hall = $dictionary->{"og_hall"} ?? "";
$or_date = $dictionary->{"og_date"} ?? "";
$or_start = $dictionary->{"og_start"} ?? "";
//Check errors in inputs
if (empty($price) || $price <= 0 )
$errors['price'] = 'El precio no puede ser 0.';
if (empty($format))
$errors['format'] = 'El formato no puede estar vacio. Ej: 3D, 2D, voz original';
if (empty($hall) || $hall<=0 )
$errors['hall'] = 'La sala no puede ser 0 o menor';
if (empty($startDate))
$errors['startDate'] = 'Las sesiones tienen que empezar algun dia.';
else if (empty($endDate))
$errors['endDate'] = 'Las sesiones tienen que teminar algun dia.';
else {
$start = strtotime($startDate);
$end = strtotime($endDate);
$start = date('Y-m-d', $start);
$end = date('Y-m-d', $end);
if($start > $end)
$errors['date'] = 'La fecha inicial no puede ser antes o el mismo dia que la final.';
}
if (empty($startHour))
$errors['startHour'] = 'Es necesario escoger el horario de la sesion.';
if (!is_numeric($idfilm) && $idfilm <= 0 )
$errors['idfilm'] = 'No se ha seleccionado una pelicula.';
if(empty($errors)){
$msg = Session::edit_session($_SESSION["cinema"], $or_hall, $or_date, $or_start, $hall, $startHour, $startDate, $idfilm, $price, $format);
if(strcmp($msg,$correct_response)!== 0)
$errors['global'] = $msg;
else
$data['message'] = $msg;
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
}
}
echo json_encode($data);
break;
//Delete a session
case 'DELETE':
$errors = [];
$data = [];
//Correct reply to verify the session has been correctly edited
$correct_response = 'Se ha eliminado la session con exito';
//Check if the body is ok
$entityBody = file_get_contents('php://input');
$dictionary = json_decode($entityBody);
if (!is_object($dictionary))
$errors['global'] = 'El cuerpo de la petición no es valido';
$or_hall = $dictionary->{"og_hall"} ?? "";
$or_date = $dictionary->{"og_date"} ?? "";
$or_start = $dictionary->{"og_start"} ?? "";
//Check errors in inputs
if(empty($or_hall))
$errors['global'] = 'El nº de sala a borrar no existe';
if(empty($or_date))
$errors['global'] = 'La fecha de donde borrar no existe';
if(empty($or_start))
$errors['global'] = 'La hora de donde borrar no existe';
if(empty($errors)){
$msg = Session::delete_session($_SESSION["cinema"], $or_hall, $or_start, $or_date);
if(strcmp($msg,$correct_response)!== 0)
$errors['global'] = $msg;
else
$data['message'] = $msg;
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
}
echo json_encode($data);
break;
default:
break;
}

View File

@ -0,0 +1,105 @@
<?php
require_once($prefix.'assets/php/includes/film_dao.php');
class SessionForm {
public static function getForm(){
$films = new Film_DAO("complucine");
$filmslist = $films->allFilmData();
$form='
<div id="operation_msg" class="operation_msg"> </div>
<form id="session_form" name="session_form" action="eventos.php" method="POST">
<input type="hidden" id="film_id" name="film_id" value=""/>
<input type="hidden" id="original_hall" name="film_id" value=""/>
<input type="hidden" id="original_date" name="film_id" value=""/>
<input type="hidden" id="original_start_time" name="film_id" value=""/>
<div id="global_group" class="form_group"></div>
<fieldset>
<legend>Datos</legend>
<div id="price_group" class="form_group">
<input type="number" step="0.01" id="price" name="price" value="" min="0" placeholder="Precio de la entrada" /> <br>
</div>
<div id="format_group" class="form_group">
<input type="text" id="format" name="format" value="" placeholder="Formato de pelicula" /> <br>
</div>
<div id="hall_group" class="form_group">
<select id="hall" name="hall" class="button large">>';
foreach(Hall::getListHalls($_SESSION["cinema"]) as $hll){
$form.= '
<option value="'. $hll->getNumber() .'"> Sala '. $hll->getNumber() .'</option>';
}
$form.=' </select>
</div>
</fieldset>
<fieldset>
<legend>Horario</legend>
<div id="date_group" class="form_group">
<div class="two-inputs-line">
<label> Fecha inicio </label>
<label> Fecha final </label>
<input type="date" id="startDate" name="startDate" value=""/>
<input type="date" id="endDate" name="endDate" value=""/>
</div>
</div>
<div id="hour_group" class="form_group">
<div class="one-input-line">
<label> Hora sesion </label>
<input type="time" id="startHour" name="startHour" value=""/>
</div>
</div>
</fieldset>
<input type="reset" id="reset" value="Limpiar Campos" >
<input type="submit" id="sumbit_new" name="sumbit_new" class="sumbit" value="Añadir" />
<div class="two-inputs-line" id="edit_inputs">
<input type="submit" id="sumbit_edit" name="sumbit_edit" class="sumbit" value="Editar" />
<input type="submit" id="submit_del" name="submit_del" class="black button" value="Borrar" />
</div>
<div id="film_msg_group" class="form_group"> </div>
<div id="film_group" class="form_group">
<div class="code showtimes">
<h2 id="film_title"> titulo </h2>
<hr />
<div class="img_desc">
<div class="image"> <img src="../img/films/iron_man.jpg" alt="iron man" id="film_img" /> </div>
<div class="blockquote">
<p id="film_desc">"Un empresario millonario construye un traje blindado y lo usa para combatir el crimen y el terrorismo."</p>
</div>
</div>
<li id="film_dur"> Duración: duracion minutos</li>
<li id="film_lan"> Lenguaje: idioma </li>
</div>
<button type="button" class="button large" id="return"> Cambiar pelicula </button>
</div>
<div class="film_list" id="film_list">
<ul class="tablelist col3">';
$parity = "odd";
$i = 0;
foreach($filmslist as $film){
$form .='<div class="'.$parity.'">
<input type="hidden" value="'.$film->getId().'" id="id'.$i.'"/>
<input type="hidden" value="'.$film->getImg().'" id="img'.$i.'"/>
<input type="hidden" value="'.$film->getLanguage().'" id="lan'.$i.'"/>
<input type="hidden" value="'.$film->getDescription().'" id="desc'.$i.'"/>
<li value="'.$film->getTittle().'"id="title'.$i.'"> '. str_replace('_', ' ',$film->getTittle()).'</li>
<li id="dur'.$i.'"> '.$film->getDuration().' min</li>
<li> <button type="button" class="film_button" id="'.$i.'"> Seleccionar </button> </li>
</div>
';
$parity = ($parity == "odd") ? "even" : "odd";
$i++;
}
$form.='
</ul>
</div>
</form>
';
return $form;
}
}
?>

View File

@ -30,7 +30,7 @@ class FormHall extends Form {
$rows = $data['rows'] ?? $this->og_hall->getNumRows() ?? "12";
$cols = $data['cols'] ?? $this->og_hall->getNumCol() ?? "8";
//Seats_map
//Init Seats_map
$seats = 0;
$seats_map = array();
for($i = 1;$i <= $rows; $i++){
@ -145,8 +145,6 @@ class FormHall extends Form {
return $html;
}
//Methods:
//Process form:
protected function procesaFormulario($datos){
$result = array();
@ -170,29 +168,24 @@ class FormHall extends Form {
}
}
}
//Check input errors
if ($seats == 0 && isset($datos["sumbit"]) ) {
$result['seats'] = "<li> No puede haber 0 asientos disponibles. </li> <br>";
}
if ($rows <= 0) {
$result['rows'] = "<li> No puede haber 0 o menos filas. </li> <br>";
}
if ($cols <= 0) {
$result['cols'] = "<li> No puede haber 0 o menos columnas. </li> <br>";
}
$number = $datos['number'] ?? null;
if (empty($number) && isset($datos["sumbit"])) {
$result['number'] = "<li> El numero de sala tiene que ser mayor que 0. </li> <br>";
}
if(isset($datos["restart"])){
return $result = "./?state=".$this->option."&number=".$this->og_hall->getNumber()."";
}
if (count($result) === 0 && isset($datos["sumbit"]) ) {
if($this->option == "new_hall"){
$_SESSION['msg'] = Hall::create_hall($number, $this->cinema, $rows, $cols, $seats, $seats_map);
@ -203,7 +196,6 @@ class FormHall extends Form {
return $result = './?state=success';
}
}
if (!isset($result['number']) && isset($datos["delete"]) ) {
if($this->option == "edit_hall"){
$_SESSION['msg'] = Hall::delete_hall($number, $this->cinema, $rows, $cols, $seats, $seats_map, $this->og_hall->getNumber());

View File

@ -56,18 +56,6 @@
$panel = Manager_panel::edit_hall();
break;
case "manage_sessions":
$panel = Manager_panel::manage_sessions();
break;
case "new_session":
$panel = Manager_panel::new_session();
break;
case "edit_session":
$panel = Manager_panel::edit_session();
break;
case "select_film":
$panel = Manager_panel::select_film($template);
break;
case "calendar":
$panel = Manager_panel::calendar();
break;
case "success":
@ -138,23 +126,11 @@
$panel = Manager_panel::edit_hall();
break;
case "manage_sessions":
$panel = Manager_panel::manage_sessions();
break;
case "new_session":
$panel = Manager_panel::new_session();
break;
case "edit_session":
$panel = Manager_panel::edit_session();
break;
case "select_film":
$panel = Manager_panel::select_film($template);
$panel = Manager_panel::calendar();
break;
case "success":
$panel = Manager_panel::success();
break;
case "calendar":
$panel = Manager_panel::calendar();
break;
default:
$panel = Manager_panel::welcome();
break;
@ -194,5 +170,5 @@
<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>
<script src="./sessionforms.js"></script>
<script src="./sessionCalendar.js"></script>
<script src="./sessionFormProcess.js"></script>

View File

@ -1,16 +1,13 @@
<?php
include_once($prefix.'assets/php/includes/hall.php');
include_once($prefix.'assets/php/includes/session.php');
require_once($prefix.'assets/php/includes/manager.php');
require_once($prefix.'assets/php/includes/cinema_dao.php');
include_once('./includes/formHall.php');
include_once('./includes/formSession.php');
include_once('./includes/NewSessionForm.php');
include_once('./includes/SessionForm.php');
class Manager_panel {
function __construct(){}
static function welcome(){
$bd = new Cinema_DAO('complucine');
if($bd){
@ -30,12 +27,12 @@
<p>Usuario: '.$name.'</p> <br>
<p>Cine: '.$c_name.'</p>
<p>Dirección: '.$c_dir.'</p>
<a href="?state=calendar"> <p> Hack para entrar al calendario <p> </a>
</div>'."\n";
return $panel;
}
// Admin welcome panel allows to change the cinema linked to the admin-like-manager
static function welcomeAdmin() {
$cinemaList = new Cinema_DAO('complucine');
$cinemas = $cinemaList->allCinemaData();
@ -64,8 +61,6 @@
<p>Usuario: '.$name.'</p> <br>
<h3>Como administrador puedes escoger el cine que gestionar</h3>
<p>Cine: '.$c_name.'</p>
<a href="?state=calendar"> <p> Hack para entrar al calendario <p> </a>
<form method="post" id="changecinema" action="index.php">
<select name="cinema" class="button large">
@ -88,8 +83,8 @@
return $panel;
}
//Manage the sessions using full calendar js events and a pop up form which is constantly edited with more js
static function calendar(){
$hall = $_POST['hall'] ?? $_GET['hall'] ?? "1";
$halls = Hall::getListHalls($_SESSION["cinema"]);
@ -103,10 +98,10 @@
foreach(Hall::getListHalls($_SESSION["cinema"]) as $hll){
if($hll->getNumber() == $hall){
$panel.= '
<option data-feed="./eventos.php?hall='.$hll->getNumber().'" value="'. $hll->getNumber() .'"selected> Sala '. $hll->getNumber() .'</option> ';
<option data-feed="./eventsProcess.php?hall='.$hll->getNumber().'" value="'. $hll->getNumber() .'"selected> Sala '. $hll->getNumber() .'</option> ';
}else{
$panel.= '
<option data-feed="./eventos.php?hall='.$hll->getNumber().'" value="'. $hll->getNumber() .'"> Sala '. $hll->getNumber() .'</option>';
<option data-feed="./eventsProcess.php?hall='.$hll->getNumber().'" value="'. $hll->getNumber() .'"> Sala '. $hll->getNumber() .'</option>';
}
}
$panel.='
@ -120,7 +115,7 @@
<div class="modal-content">
<span class="close">&times;</span> <br> <br>
'.NewSessionForm::getForm().'
'.SessionForm::getForm().'
</div>
</div>
</div>';
@ -130,10 +125,9 @@
<a href=."/?state=new_hall"> Añadir Sala </a>
</div>';
}
return $panel;
}
static function success(){
$panel = '<div class="code info">
<h1>Operacion completada.</h1>
@ -166,7 +160,7 @@
<li> '. $hall->getNumber().'</li>
<li> '.$hall->getTotalSeats().' </li>
</a>
<a href="?state=calendar&hall='. $hall->getNumber().'">
<a href="?state=manage_sessions&hall='. $hall->getNumber().'">
<li> Sesiones </li>
</a>
</div>
@ -208,117 +202,7 @@
}
}
static function manage_sessions(){
//Base filtering values
$date = $_POST['date'] ?? $_GET['date'] ?? date("Y-m-d");
$hall = $_POST['hall'] ?? $_GET['hall'] ?? "1";
//Session filter
$panel='<div class = "column left">
<form method="post" id="filter" action="./?state=manage_sessions">
<input type="date" name="date" value="'.$date.'" min="2021-01-01" max="2031-12-31">
<select name="hall" class="button large">';
foreach(Hall::getListHalls($_SESSION["cinema"]) as $hll){
if($hll->getNumber() == $hall){
$panel.= '
<option value="'. $hll->getNumber() .'"selected> Sala '. $hll->getNumber() .'</option> ';
}else{
$panel.= '
<option value="'. $hll->getNumber() .'"> Sala '. $hll->getNumber() .'</option>';
}
}
$panel.='
</select>
<input type="submit" name="filter" value="Filtrar" class="button large"/>
</form>
</div>
';
//Session list
$panel .=' <div class = "column right">';
$sessions = Session::getListSessions($hall,$_SESSION["cinema"],$date);
if($sessions) {
$panel .='
<form method="post" action="./?state=edit_session">
<table class="alt">
<thead>
<tr>
<th>Hora</th>
<th>Pelicula</th>
<th>Formato</th>
<th>Precio</th>
</tr>
</thead>
<tbody>';
foreach($sessions as $session){
$film = Session::getThisSessionFilm($session->getIdfilm());
$panel .='
<tr>
<td> '.date("H:i", strtotime( $session->getStartTime())).' </td>
<td> '. str_replace('_', ' ', $film["tittle"]) .' </td>
<td> '.$session->getFormat().' </td>
<td> '.$session->getSeatPrice().' </td>
<form method="post" action="./?state=edit_session">
<input name="film" type="hidden" value="'.$session->getIdfilm().'">
<input name="tittle" type="hidden" value="'.$film["tittle"].'">
<input name="duration" type="hidden" value="'.$film["duration"].'">
<input name="language" type="hidden" value="'.$film["language"].'">
<input name="description" type="hidden" value="'.$film["description"].'">
<input name="hall" type="hidden" value="'.$session->getIdhall().'">
<input name="date" type="hidden" value="'.$session->getDate().'">
<input name="start" type="hidden" value="'.$session->getStartTime().'">
<input name="price" type="hidden" value="'.$session->getSeatPrice().'">
<input name="format" type="hidden" value="'.$session->getFormat().'">
<td> <input type="submit" id="submit" name ="edit_session" value="Editar" class="primary" /> </td>
</form>
</tr>';
}
$panel.='
</tbody>
</table>
</form>';
} else {
$panel.=' <h3> No hay ninguna sesion </h3>';
}
$panel.='
<input type="submit" name="new_session" form="filter" value="Añadir" class="button large" formaction="./?state=new_session">
</div>';
return $panel;
}
static function new_session(){
$formSession = new FormSession("new_session", $_SESSION["cinema"] );
$panel = '<h1>Crear una sesion.</h1> <hr/> </br>
'.$formSession->gestiona();
return $panel;
}
static function edit_session(){
$formSession = new FormSession("edit_session", $_SESSION["cinema"] );
$panel = '<h1>Editar una sesion.</h1><hr/></br>
'.$formSession->gestiona();
return $panel;
}
//TODO: estado al modificar sesiones para la seleccion de peliculas usando el template->print films
static function select_film($template){
if(isset($_POST["select_film"]) && isset($_POST["option"])){
$_SESSION["option"] = $_POST["option"];
$panel = '<h1>Seleccionar Pelicula.</h1><hr /></br>';
$panel .= $template->print_fimls();
$_SESSION["option"] = "";
} else $panel = self::warning();
return $panel;
}
//Funcion que se envia cuando hay inconsistencia en el panel manager, principalmente por tocar cosas con la ulr
//this function is used as an answer to wrong url parameters accesing a formhall edit. The formsession version has been replaced by other js error replys
static function warning(){
$panel = '<div class="code info">
<h1>Ha habido un error.</h1>
@ -328,7 +212,5 @@
return $panel;
}
}
?>

View File

@ -0,0 +1,140 @@
$(document).ready(function(){
//Get the data that is going to be used as a filter for events
var selectedFeed = $('#hall_selector').find(':selected').data('feed');
var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
var calendar = $('#calendar').fullCalendar({
editable:true,
header:{
left:'prev,next today',
center:'title',
right:'month,agendaWeek,agendaDay'
},
firstDay: 1,
fixedWeekCount: false,
eventSources: [ selectedFeed ],
selectable:true,
selectHelper:true,
timeFormat: 'H:mm',
eventOverlap: function(stillEvent, movingEvent) {
return (stillEvent.start_time > stillEvent.end && stillEvent.end < movingEvent.start_time)
},
//Add event/session function when u click in any non-event date. Prepares the form to be seen as such
select: function(start, end, allDay)
{
$(modal).fadeIn();
var x = document.getElementById("film_group");
x.style.display = "none";
x = document.getElementById("film_list");
x.style.display = "block";
document.getElementById("hall").value = document.getElementById("hall_selector").value;
document.getElementById("startDate").value = $.fullCalendar.formatDate( start, "Y-MM-DD" );
document.getElementById("endDate").value = $.fullCalendar.formatDate( end, "Y-MM-DD" );
document.getElementById("sumbit_new").style.display = "block";
document.getElementById("edit_inputs").style.display = "none";
},
editable:true,
//Edit only the date/hour start of an event/session when u click,drag and drop an event.
eventDrop:function(event)
{
var e = {
"newDate" : $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss"),
"idhall": document.getElementById("hall").value,
"startHour":event.start_time,
"startDate":event.date,
"price": event.seat_price,
"idfilm": event.film.idfilm,
"format": event.format,
};
console.log(e);
console.log(event);
$.ajax({
url:"eventsProcess.php?drop=true",
contentType: 'application/json; charset=utf-8',
dataType: "json",
type:"PUT",
data:JSON.stringify(e),
success: function(data) {
alert("El evento se ha desplazado correctamente");
calendar.fullCalendar('refetchEvents');
},
error: function(data) {
alert("Ha habido un error al desplazar el evento");
},
});
},
//Edit event/session function when u click an event. Prepares the form to be seen as such
eventClick:function(event)
{
$(modal).fadeIn();
var x = document.getElementById("film_group");
x.style.display = "block";
x = document.getElementById("film_list");
x.style.display = "none";
document.getElementById("hall").value = document.getElementById("hall_selector").value;
document.getElementById("startDate").value = $.fullCalendar.formatDate( event.start, "Y-MM-DD" );
document.getElementById("endDate").value = $.fullCalendar.formatDate( event.end, "Y-MM-DD" );
document.getElementById("price").value = event.seat_price;
document.getElementById("format").value = event.format;
document.getElementById("startHour").value = event.start_time;
document.getElementById("original_hall").value = document.getElementById("hall_selector").value;
document.getElementById("original_start_time").value = event.start_time;
document.getElementById("original_date").value = $.fullCalendar.formatDate( event.start, "Y-MM-DD" );
document.getElementById("film_title").innerHTML = event.film.tittle;
document.getElementById("film_lan").innerHTML = event.film.language;
document.getElementById("film_dur").innerHTML = event.film.duration+" min";
document.getElementById("film_img").src = "../img/films/"+event.film.img;
document.getElementById("film_desc").innerHTML = event.film.description;
document.getElementById("film_id").value = event.film.idfilm;
document.getElementById("sumbit_new").style.display = "none";
document.getElementById("edit_inputs").style.display = "grid";
},
});
//Once the filter changes, do the changes needed so full calendar research the events with the new hall
$('#hall_selector').change(onSelectChangeFeed);
function onSelectChangeFeed() {
var feed = $(this).find(':selected').data('feed');
$('#calendar').fullCalendar('removeEventSource', selectedFeed);
$('#calendar').fullCalendar('addEventSource', feed);
selectedFeed = feed;
};
//When u click on the X the form closes. If the user close it because the operation has been complete. Restart the form correctly
span.onclick = function() {
formout();
}
function formout(){
$(modal).fadeOut(100,function(){
var success = document.getElementById("success");
if(success){
calendar.fullCalendar('refetchEvents');
success.style.display = "none";
document.getElementById("session_form").style.display = "block";
document.getElementById("price").value = "";
document.getElementById("format").value = "";
document.getElementById("film_id").value = "";
document.getElementById("startHour").value ="";
}
$(".form_group").removeClass("has_error");
$(".help_block").remove();
});
}
});

View File

@ -0,0 +1,212 @@
$(document).ready(function () {
//New session
$('#sumbit_new').click( function(e) {
$(".form_group").removeClass("has_error");
$(".help_block").remove();
var formData = {
price: $("#price").val(),
format: $("#format").val(),
hall: $("#hall").val(),
startDate: $("#startDate").val(),
endDate: $("#endDate").val(),
startHour: $("#startHour").val(),
idFilm: $("#film_id").val(),
};
$.ajax({
type: "POST",
url:"eventsProcess.php",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data:JSON.stringify(formData),
encode: true,
}).done(function (data) {
console.log(data);
checkErrors(data,"session_form");
})
.fail(function (jqXHR, textStatus) {
$("form#session_form").html(
'<div class="alert alert_danger">Could not reach server, please try again later. '+textStatus+'</div>'
);
});
e.preventDefault();
});
//Edit session
$('#sumbit_edit').click( function(e) {
$(".form_group").removeClass("has_error");
$(".help_block").remove();
var formData = {
price: $("#price").val(),
format: $("#format").val(),
hall: $("#hall").val(),
startDate: $("#startDate").val(),
endDate: $("#endDate").val(),
startHour: $("#startHour").val(),
idFilm: $("#film_id").val(),
og_hall: $("#original_hall").val(),
og_date: $("#original_date").val(),
og_start: $("#original_start_time").val(),
};
console.log(formData);
$.ajax({
type: "PUT",
url:"eventsProcess.php",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data:JSON.stringify(formData),
encode: true,
}).done(function (data) {
console.log(data);
checkErrors(data,"session_form");
})
.fail(function (jqXHR, textStatus) {
$("form#session_form").html(
'<div class="alert alert_danger">Could not reach server, please try again later. '+textStatus+'</div>'
);
});
e.preventDefault();
});
//Delete Session
$('#submit_del').click( function(e) {
$(".form_group").removeClass("has_error");
$(".help_block").remove();
var formData = {
og_hall: $("#original_hall").val(),
og_date: $("#original_date").val(),
og_start: $("#original_start_time").val(),
};
console.log(formData);
$.ajax({
type: "DELETE",
url:"eventsProcess.php",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data:JSON.stringify(formData),
encode: true,
}).done(function (data) {
console.log(data);
checkErrors(data,"session_form")
})
.fail(function (jqXHR, textStatus) {
$("form#session_form").html(
'<div class="alert alert_danger">Could not reach server, please try again later. '+textStatus+'</div>'
);
});
e.preventDefault();
});
function checkErrors(data,formname) {
if (!data.success) {
if (data.errors.price) {
$("#price_group").addClass("has_error");
$("#price_group").append(
'<div class="help_block">' + data.errors.price + "</div>"
);
}
if (data.errors.format) {
$("#format_group").addClass("has_error");
$("#format_group").append(
'<div class="help_block">' + data.errors.format + "</div>"
);
}
if (data.errors.hall) {
$("#hall_group").addClass("has_error");
$("#hall_group").append(
'<div class="help_block">' + data.errors.hall + "</div>"
);
}
if (data.errors.startDate) {
$("#date_group").addClass("has_error");
$("#date_group").append(
'<div class="help_block">' + data.errors.startDate + "</div>"
);
}
if (data.errors.startDate) {
$("#date_group").addClass("has_error");
$("#date_group").append(
'<div class="help_block">' + data.errors.endDate + "</div>"
);
}
if (data.errors.date) {
$("#date_group").addClass("has_error");
$("#date_group").append(
'<div class="help_block">' + data.errors.date + "</div>"
);
}
if (data.errors.startHour) {
$("#hour_group").addClass("has_error");
$("#hour_group").append(
'<div class="help_block">' + data.errors.startHour + "</div>"
);
}
if (data.errors.idfilm) {
$("#film_msg_group").addClass("has_error");
$("#film_msg_group").append(
'<div class="help_block">' + data.errors.idfilm + "</div>"
);
}
if (data.errors.global) {
$("#global_group").addClass("has_error");
$("#global_group").append(
'<div class="help_block">' + data.errors.global + "</div>"
);
}
} else {
$("#operation_msg").addClass("has_no_error");
$("#operation_msg").append(
'<div class="alert alert_success" id="success">' + data.message + "</div>"
);
document.getElementById("session_form").style.display = "none";
}
}
//Change the view from the film list to a concrete film with some data about it
$('.film_button').bind('click', function(e) {
var id = $(this).attr('id');
var x = document.getElementById("film_group");
x.style.display = "block";
var tittle = document.getElementById("title"+id);
document.getElementById("film_title").innerHTML = tittle.innerHTML;
var lan = document.getElementById("lan"+id);
document.getElementById("film_lan").innerHTML = lan.value;
var dur = document.getElementById("dur"+id);
document.getElementById("film_dur").innerHTML = dur.innerHTML;
var img = document.getElementById("img"+id);
document.getElementById("film_img").src = "../img/films/"+img.value;
var desc = document.getElementById("desc"+id);
document.getElementById("film_desc").innerHTML = desc.value;
var idf = document.getElementById("id"+id);
document.getElementById("film_id").value = idf.value;
x = document.getElementById("film_list")
x.style.display = "none";
});
//Change the view from the concrete film data to a film list with all available films
$('#return').click( function() {
var x = document.getElementById("film_group");
x.style.display = "none";
x = document.getElementById("film_list");
x.style.display = "block";
});
});