Compare commits

...

19 Commits

Author SHA1 Message Date
79cc26b7e5 Hide text input when country is Spain 2020-07-16 05:17:07 +02:00
997de5c4bf Convert readme to markdown 2020-07-16 04:07:46 +02:00
6e314bc2a0 Add directory structure section to summary 2020-07-16 04:02:49 +02:00
e4c64900d8 Add description of dependencies in the summary 2020-07-16 03:53:06 +02:00
0b91047625 Beautify javascript code 2020-07-16 03:32:09 +02:00
b0238cc9b0 Improve PHP formatting 2020-07-16 03:19:08 +02:00
6bc9db9117 Clean up unused appointment functions 2020-07-16 03:11:40 +02:00
5fab7775d4 Print report content as PDF 2020-07-15 23:44:44 +02:00
1993b0d27e Print report content as HTML 2020-07-15 22:08:40 +02:00
393a508136 Change time input to dropdown 2020-07-15 20:26:06 +02:00
92cb51ae60 Disable appointment selection for days off 2020-07-15 18:58:41 +02:00
88c06ce169 Disable appointment selection for holidays 2020-07-15 16:52:10 +02:00
d3e6b5a549 Display holidays from JSON feed 2020-07-14 21:36:43 +02:00
5e0285d608 Implement appointment modification 2020-07-14 14:48:35 +02:00
b9bf92ea55 Translate log in and log out 2020-07-14 00:27:15 +02:00
77a4a5987e Delete appointment from calendar 2020-07-13 19:12:46 +02:00
a772b300df Show appointment information on click 2020-07-13 19:03:06 +02:00
646f97fa79 Get chosen doctor appointments as admin 2020-07-13 17:28:42 +02:00
d5ea8bec33 Implement appointment fetch and insertion 2020-07-12 20:08:42 +02:00
28 changed files with 919 additions and 288 deletions

48
README.md Normal file
View File

@@ -0,0 +1,48 @@
# MDIS
This project consists of an Information System for a Medical Institution.
## Technologies
- PHP
- MySQL
- Javascript
- Fullcalendar
- Jquery
- JqueryUI
## Requirements
- Nix
## Installation
1. Install Nix (compatible with MacOS and Linux):
``` {.shell}
curl -L https://nixos.org/nix/install | sh
```
There are alternative installation methods, if you don\'t want to pipe
curl to sh
2. Clone the repository:
``` {.shell}
git clone https://coolneng.duckdns.org/gitea/coolneng/MDIS
```
3. Change the working directory to the project:
``` {.shell}
cd MDIS
```
4. Enter the nix-shell:
``` {.shell}
nix-shell
```
The website can be accessed via **localhost:8000**

View File

@@ -1,9 +0,0 @@
* MDIS
This project consists of an Information System for a Medical Institution.
** Technologies
- PHP
- Javascript (AJAX)
- MySQL

View File

@@ -1,7 +1,7 @@
#+TITLE: MDIS #+TITLE: MDIS
#+SUBTITLE: Programación Web #+SUBTITLE: Programación Web
#+AUTHOR: Amin Kasrou Aouam #+AUTHOR: Amin Kasrou Aouam
#+DATE: 2020-06-18 #+DATE: 2020-07-16
#+PANDOC_OPTIONS: template:~/.pandoc/templates/eisvogel.latex #+PANDOC_OPTIONS: template:~/.pandoc/templates/eisvogel.latex
#+PANDOC_OPTIONS: listings:t #+PANDOC_OPTIONS: listings:t
#+PANDOC_OPTIONS: toc:t #+PANDOC_OPTIONS: toc:t
@@ -13,12 +13,13 @@
#+PANDOC_METADATA: logo:/home/coolneng/Photos/Logos/UGR.png #+PANDOC_METADATA: logo:/home/coolneng/Photos/Logos/UGR.png
* MDIS * MDIS
MDIS es una sistema de información que permite la gestión de una consulta médica. MDIS es un sistema de información que permite la gestión de una consulta médica.
** Funcionalidades ** Funcionalidades
- Gestión de Usuarios - Gestión de Usuarios
- Gestión de Pacientes - Gestión de Pacientes
- Gestión de Calendario
- Gestión de Citas - Gestión de Citas
- Gestión de Vacaciones - Gestión de Vacaciones
- Gestión de Informes - Gestión de Informes
@@ -27,7 +28,10 @@ MDIS es una sistema de información que permite la gestión de una consulta méd
- PHP - PHP
- MySQL - MySQL
- Javascript (Jquery) - Javascript
- Fullcalendar
- Jquery
- JqueryUI
- Nix - Nix
** Arquitectura ** Arquitectura
@@ -37,13 +41,34 @@ MDIS es una sistema de información que permite la gestión de una consulta méd
Es un sistema web clásico, con la característica de que las consultas a la base de datos se realizan mediante /PDO/, para evitar vulnerabilidades del tipo /inyección de SQL/. Es un sistema web clásico, con la característica de que las consultas a la base de datos se realizan mediante /PDO/, para evitar vulnerabilidades del tipo /inyección de SQL/.
Además de ésto, no hacemos ninguna consulta /SQL/ fuera del archivo database.php, lo que nos permite separar la lógica interna de la presentación. Las operaciones que conllevan una inserción o transformación de datos se realizan en los archivos que terminan en *=_management.php=*, además de ésto, no hacemos ninguna consulta /SQL/ fuera del archivo *database.php*, lo que nos permite separar la lógica interna de la presentación.
** Estructura del proyecto
La segmentación de los diferentes archivos de un proyecto es un aspecto que facilita mucho la búsqueda en un proyecto. La estructura de directorios es la siguiente:
- database: archivos SQL para la creación de la base de datos.
- docs: memoria del proyecto.
- src: código fuente (PHP y Javascript).
- src/static: bibliotecas de javascript, CSS y fotos.
** Dependencias
El apartado de la gestión de citas se ha realizado utilizando la biblioteca [[https://fullcalendar.io/][FullCalendar]] de Javascript. La conexión entre el /backend/ y el /frontend/ se realiza mediante intercambio de JSON, la implementación se encuentra en los archivos que terminan en *=_feed.php=*.
A partir de los elementos de la base de datos, formateados y transformados, obtenemos las citas, los festivos y la configuración del calendario de cada doctor. Finalmente, personalizamos el comportamiento del calendario según estos datos.
Los elementos del calendario también requieren de [[https://jqueryui.com/][JqueryUI]], para darle un toque más moderno a los distintos componentes.
La impresión de los informes en formato PDF es posible gracias a [[https://github.com/MrRio/jsPDF][jsPDF]], biblioteca simple y que produce documentos con un diseño cuidado.
Por último, hacemos uso de la función /$.ajax()/ de [[https://jquery.com][Jquery]] para realizar peticiones /GET/ síncronas, dado que ciertos componentes de FullCalendar no pueden ser ejecutados como funciones asíncronas.
** Despliegue ** Despliegue
El desarrollo y despliegue del sistema se han hecho gracias a /Nix/, un gestor de paquetes que permite entornos de desarrollo y despliegue reproducibles. El desarrollo y despliegue del sistema se han hecho gracias a /Nix/, un gestor de paquetes que permite entornos de desarrollo y despliegue reproducibles.
A continuación mostramos el código que defino el entorno: A continuación mostramos el código que define el entorno de desarrollo:
#+BEGIN_SRC nix #+BEGIN_SRC nix
{ pkgs ? import <nixpkgs> { } }: { pkgs ? import <nixpkgs> { } }:

Binary file not shown.

View File

@@ -1,17 +1,14 @@
$(document).ready(function() $(document).ready(function() {
{ $("#provincia").change(function() {
$("#provincia").change(function()
{
var id_provincia = $(this).val(); var id_provincia = $(this).val();
var post_id = 'id='+ id_provincia; var post_id = 'id=' + id_provincia;
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "ajax.php", url: "ajax.php",
data: post_id, data: post_id,
cache: false, cache: false,
success: function(response) success: function(response) {
{
$("#localidad").html(response); $("#localidad").html(response);
} }
}); });

View File

@@ -1,8 +0,0 @@
<?php
include 'appointment_management.php';
$pdo = connectDatabase();
$events = listEvents($pdo);
echo $events;
closeDatabase($pdo);
?>

View File

@@ -23,8 +23,9 @@
$pdo = connectDatabase(); $pdo = connectDatabase();
$patients = listPatients($pdo); $patients = listPatients($pdo);
$calendar_settings = fetchCalendarSettings($pdo, $doctor); $calendar_settings = fetchCalendarSettings($pdo, $doctor);
$time_ranges = computeTimeRanges($pdo);
?> ?>
<?php if($_SESSION["user_type"] == 1 and !isset($_GET["medico"])): ?> <?php if ($_SESSION["user_type"] == 1 and !isset($_GET["medico"])): ?>
<form name="select_doctor" method="get" action="appointment.php"> <form name="select_doctor" method="get" action="appointment.php">
<?php $doctors = listDoctors($pdo); ?> <?php $doctors = listDoctors($pdo); ?>
<div class="input-group"> <div class="input-group">
@@ -42,7 +43,12 @@
<form name="add_appointment" method="post" action="appointment_management.php"> <form name="add_appointment" method="post" action="appointment_management.php">
<div class="input-group"> <div class="input-group">
<label for="hora">Hora</label> <label for="hora">Hora</label>
<input type="time" name="hora" value=""> <select id="hora" name="hora">
<option>Seleccione una hora</option>
<?php foreach ($time_ranges as $row) : ?>
<option><?php echo $row; ?></option>
<?php endforeach ?>
</select>
</div> </div>
<div class="input-group"> <div class="input-group">
<label for="duracion">Duración</label> <label for="duracion">Duración</label>
@@ -53,12 +59,12 @@
<input type="text" name="observaciones" value=""> <input type="text" name="observaciones" value="">
</div> </div>
<div class="input-group"> <div class="input-group">
<select id="paciente" name="paciente"> <select id="paciente" name="paciente">
<option>Seleccione un paciente</option> <option>Seleccione un paciente</option>
<?php foreach ($patients as $row) : ?> <?php foreach ($patients as $row) : ?>
<option value="<?php echo $row[0]; ?>"><?php echo $row[2]; ?></option> <option value="<?php echo $row[0]; ?>"><?php echo $row[2]; ?></option>
<?php endforeach ?> <?php endforeach ?>
</select> </select>
</div> </div>
<button class="create_btn" type="submit" name="create" >Añadir cita</button> <button class="create_btn" type="submit" name="create" >Añadir cita</button>
<?php $doctor = fetchDoctor($pdo); ?> <?php $doctor = fetchDoctor($pdo); ?>
@@ -69,5 +75,16 @@
</div> </div>
<div class="response"></div> <div class="response"></div>
<div id="calendar"></div> <div id="calendar"></div>
<div id="event-info" style="display:none;">
<div id="event-patient"/></div>
<div id="event-description"/></div>
<div id="event-start"/></div>
<div id="event-end"/></div>
<form method="post" action="appointment_management.php">
<input type="hidden" name="event_id" id="event_id">
<button class="create_btn" type="submit" name="edit_form">Editar</button>
<button class="del_btn" type="submit" name="delete">Borrar</button>
</form>
</div>
</body> </body>
</html> </html>

View File

@@ -0,0 +1,48 @@
<?php session_start(); ?>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Gestión de citas</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="static/style.css" type="text/css" media="screen" />
</head>
<body>
<?php include 'navbar.php'; ?>
<?php
include 'database.php';
$pdo = connectDatabase();
$data = fetchAppointmentData($pdo, $_GET["event_id"]);
$patients = fetchPatients($pdo);
?>
<form name="edit_appointment" method="post" action="appointment_management.php">
<div class="input-group">
<label for="fecha">Fecha</label>
<input type="date" name="fecha" value="<?php echo $data[1]; ?>">
</div>
<div class="input-group">
<label for="hora">Hora</label>
<input type="time" name="hora" value="<?php echo $data[2]; ?>">
</div>
<div class="input-group">
<label for="duracion">Duración</label>
<input type="number" name="duracion" value="<?php echo $data[3]; ?>" step="30">
</div>
<div class="input-group">
<label for="observaciones">Observaciones</label>
<input type="text" name="observaciones" value="<?php echo $data[4]; ?>">
</div>
<div class="input-group">
<select id="paciente" name="paciente">
<option>Seleccione un paciente</option>
<?php foreach ($patients as $row) : ?>
<option value="<?php echo $row[0]; ?>"><?php echo $row[1]; ?></option>
<?php endforeach ?>
</select>
</div>
<button class="create_btn" type="submit" name="edit">Editar</button>
<input type="hidden" name="id" value="<?php echo $_GET["event_id"]; ?>">
</form>
<?php closeDatabase($pdo); ?>
</body>

44
src/appointment_feed.php Normal file
View File

@@ -0,0 +1,44 @@
<?php
include 'appointment_management.php';
function computeEndTime(&$data)
{
foreach ($data as &$row) {
$time = new DateTime($row["hora"]);
$time->modify("+{$row["duracion"]} minutes");
$time_string = $time->format('H:i:s');
$row += ["end" => $time_string];
}
}
function formatArray($data)
{
computeEndTime($data);
$events = array();
foreach ($data as $row) {
$events[] = array(
"id" => $row["id"],
"title" => $row["apellido"] . ", " . $row["nombre"],
"start" => $row["fecha"] . " " . $row["hora"],
"description" => $row["observaciones"],
"patient" => $row["documento_identificativo"],
"end" => $row["fecha"] . " " . $row["end"],
"overlap" => false,
);
}
return $events;
}
function fetchDatabase()
{
$pdo = connectDatabase();
$data = listEvents($pdo);
closeDatabase($pdo);
return $data;
}
$result = fetchDatabase();
$events = formatArray($result);
echo json_encode($events);

View File

@@ -3,8 +3,9 @@ include'database.php';
session_start(); session_start();
function fetchDoctor($pdo){ function fetchDoctor($pdo)
if($_SESSION["user_type"] == 2){ {
if ($_SESSION["user_type"] == 2) {
$user = finduser($pdo, $_SESSION["user"]); $user = finduser($pdo, $_SESSION["user"]);
return $user[0][4]; return $user[0][4];
} }
@@ -12,21 +13,32 @@ function fetchDoctor($pdo){
} }
function listEvents($pdo){ function listEvents($pdo)
{
$doctor = fetchDoctor($pdo); $doctor = fetchDoctor($pdo);
$events = fetchCalendarEvents($pdo, $doctor); $events = fetchCalendarEvents($pdo, $doctor);
return $events; return $events;
} }
function listHolidays($pdo){ function listHolidays($pdo)
{
$doctor = fetchDoctor($pdo); $doctor = fetchDoctor($pdo);
$holidays = fetchDoctorHolidays($pdo, $doctor); $holidays = fetchDoctorHolidays($pdo, $doctor);
return json_encode($holidays); return $holidays;
} }
function appointmentCreation(){ function listCalendarSettings($pdo)
{
$doctor = fetchDoctor($pdo);
$calendar_settings = fetchCalendarSettings($pdo, $doctor);
return $calendar_settings;
}
function appointmentCreation()
{
$data = $_POST; $data = $_POST;
$pdo = connectDatabase(); $pdo = connectDatabase();
createAppointment($pdo, $data); createAppointment($pdo, $data);
@@ -35,7 +47,8 @@ function appointmentCreation(){
} }
function appointmentModification(){ function appointmentModification()
{
$data = $_POST; $data = $_POST;
$pdo = connectDatabase(); $pdo = connectDatabase();
editAppointment($pdo, $data); editAppointment($pdo, $data);
@@ -44,23 +57,74 @@ function appointmentModification(){
} }
function appointmentDeletion(){ function appointmentDeletion()
$id = $_POST["id"]; {
$id = $_POST["event_id"];
$pdo = connectDatabase(); $pdo = connectDatabase();
editAppointment($pdo, $id); deleteAppointment($pdo, $id);
closeDatabase($pdo); closeDatabase($pdo);
header('location: appointment.php'); header('location: appointment.php');
} }
if(isset($_POST["create"])){ function getFloorCeiling($pdo)
{
$data = listCalendarSettings($pdo);
if ($data["horario"] == "completo") {
$start = $data["hora_inicio_mañana"];
$end = $data["hora_fin_tarde"];
} elseif ($data["horario"] == "mañana") {
$start = $data["hora_inicio_mañana"];
$end = $data["hora_fin_mañana"];
} else {
$start = $data["hora_inicio_tarde"];
$end = $data["hora_fin_tarde"];
}
$range[] = array(
"start" => $start,
"end" => $end,
);
return $range[0];
}
function getTimeDiff()
{
$current = time();
$addTime = strtotime("+30 mins", $current);
$diff = $addTime - $current;
return $diff;
}
function computeTimeRanges($pdo)
{
$range = getFloorCeiling($pdo);
$diff = getTimeDiff();
$start = strtotime($range["start"]);
$end = strtotime($range["end"]);
$time_range = array();
while ($start < $end) {
$time_range[] = date('G:i:s', $start);
$start += $diff;
}
return $time_range;
}
if (isset($_POST["create"])) {
appointmentCreation(); appointmentCreation();
} }
if(isset($_POST["edit"])){ if (isset($_POST["edit_form"])) {
$event_id = $_POST["event_id"];
header("location: appointment_edit_form.php?event_id=$event_id");
}
if (isset($_POST["edit"])) {
appointmentModification(); appointmentModification();
} }
if(isset($_POST["delete"])){ if (isset($_POST["delete"])) {
appointmentDeletion(); appointmentDeletion();
} }

View File

@@ -1,154 +1,71 @@
$(document).ready(function() { $(document).ready(function() {
var queryString = window.location.search;
var date = new Date(); var calendar = $('#calendar').fullCalendar({
selectable: true,
var d = date.getDate(); editable: false,
var m = date.getMonth(); header: {
left: 'prev,next,today',
var y = date.getFullYear(); center: 'title',
right: 'month,agendaWeek,agendaDay'
},
var calendar = $('#calendar').fullCalendar({
eventSources: [
editable: true, "appointment_feed.php" + queryString,
"holiday_feed.php" + queryString
header: { ],
left: 'prev,next,today', select: function(start, end) {
$("#dialog-form").dialog({
center: 'patient', modal: true,
width: 450
right: 'month,agendaWeek,agendaDay' });
var date = $.fullCalendar.formatDate(start, 'YYYY-MM-DD');
}, $("#fecha").val(date);
},
events: "appointment-feed.php", selectAllow: function(selectInfo) {
var daysOff = null;
var holidays = null;
eventRender: function(event, element, view) { $.ajax({
url: 'holiday_feed.php' + queryString,
if (event.allDay === 'true') { async: false,
dataType: 'json',
event.allDay = true; success: function(json) {
holidays = json;
} else { }
});
event.allDay = false; $.ajax({
url: 'calendar_settings_feed.php' + queryString,
} async: false,
dataType: 'json',
}, success: function(json) {
daysOff = json;
selectable: true, }
});
selectHelper: true, var date = selectInfo.start._d;
var formatted_date = date.toISOString().substr(0, 10);
select: function(start, end, allDay) { var foundHoliday = holidays.find(el => el.start === formatted_date);
var foundDayOff = daysOff.find(el => el === date.getDay());
$("#dialog-form").dialog({ modal: true, patient: event.paciente, width:450}); if (foundDayOff == null && foundHoliday == null) {
return true;
}
calendar.fullCalendar('renderEvent', return false;
{ },
start: start, eventClick: function(event) {
var start = $.fullCalendar.formatDate(event.start, 'HH:mm');
end: end, var end = $.fullCalendar.formatDate(event.end, 'HH:mm');
$("#event_id").val(event.id);
allDay: allDay $("#event-patient").html("<b>DNI/NIE: </b>" + event.patient);
$("#event-description").html("<b>Observaciones: </b>" + event.description);
}, $("#event-start").html("<b>Comienzo: </b>" + start);
$("#event-end").html("<b>Fin: </b>" + end);
$("#event-info").dialog({
); title: event.title,
width: 450
});
calendar.fullCalendar('unselect'); }
}, });
editable: true,
eventDrop: function(event, delta) {
var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
$.ajax({
url: 'update_events.php',
data: 'patient='+ event.patient+'&start='+ start +'&end='+ end +'&id='+ event.id ,
type: "POST",
success: function(json) {
alert("Updated Successfully");
}
});
},
eventClick: function(event) {
element.click(function() {
});
$.ajax({
type: "POST",
url: "delete_event.php",
data: "&id=" + event.id,
success: function(json) {
$('#calendar').fullCalendar('removeEvents', event.id);
alert("Updated Successfully");}
});
},
eventResize: function(event) {
var start = $.fullCalendar.formatDate(event.start, "yyyy-MM-dd HH:mm:ss");
var end = $.fullCalendar.formatDate(event.end, "yyyy-MM-dd HH:mm:ss");
$.ajax({
url: 'update_events.php',
data: 'patient='+ event.patient+'&start='+ start +'&end='+ end +'&id='+ event.id ,
type: "POST",
success: function(json) {
alert("Updated Successfully");
}
});
}
});
}); });

View File

@@ -30,9 +30,40 @@ function holidayDeletion()
} }
function setWorkingHours(&$data)
{
if (isset($data["hora_inicio_mañana"], $data["hora_fin_mañana"], $data["hora_inicio_tarde"], $data["hora_fin_tarde"])) {
$data["horario"] = "completo";
} elseif (isset($data["hora_inicio_mañana"], $data["hora_fin_mañana"])) {
$data["horario"] = "mañana";
} elseif (isset($data["hora_inicio_tarde"], $data["hora_fin_tarde"])) {
$data["horario"] = "tarde";
}
}
function setUncheckedBoxes(&$data)
{
if (!isset($data["sabado_habil"])) {
$data["sabado_habil"] = 0;
}
if (!isset($data["domingo_habil"])) {
$data["domingo_habil"] = 0;
}
}
function sanitizeInputs(&$data)
{
setWorkingHours($data);
setUncheckedBoxes($data);
}
function calendarConfig() function calendarConfig()
{ {
$data = $_POST; $data = $_POST;
sanitizeInputs($data);
$pdo = connectDatabase(); $pdo = connectDatabase();
configureCalendar($pdo, $data); configureCalendar($pdo, $data);
closeDatabase($pdo); closeDatabase($pdo);

View File

@@ -0,0 +1,28 @@
<?php
include 'appointment_management.php';
function formatArray($data)
{
$settings = array();
if (!$data["sabado_habil"]) {
array_push($settings, 6);
}
if (!$data["domingo_habil"]) {
array_push($settings, 0);
}
return $settings;
}
function fetchDatabase()
{
$pdo = connectDatabase();
$data = listCalendarSettings($pdo);
closeDatabase($pdo);
return $data;
}
$result = fetchDatabase();
$events = formatArray($result);
echo json_encode($events);

View File

@@ -50,14 +50,6 @@
<label>Hora fin tarde</label> <label>Hora fin tarde</label>
<input type="time" name="hora_fin_tarde" value=""> <input type="time" name="hora_fin_tarde" value="">
</div> </div>
<div class="select-input">
<label>Horario</label>
<select id="horario" name="horario">
<option value="mañana">mañana</option>
<option value="tarde">tarde</option>
<option value="completo">completo</option>
</select>
</div>
<div class="input-group"> <div class="input-group">
<label>Sábado hábil</label> <label>Sábado hábil</label>
<input type="checkbox" name="sabado_habil" value="1"> <input type="checkbox" name="sabado_habil" value="1">
@@ -68,7 +60,7 @@
</div> </div>
<div class="input-group"> <div class="input-group">
<label>Duración de cita por defecto</label> <label>Duración de cita por defecto</label>
<input type="number" name="duracion_cita_por_defecto" value=""> <input type="number" name="duracion_cita_por_defecto" value="60" step="30">
</div> </div>
<div class="input-group"> <div class="input-group">
<button class="btn" type="submit" name="configure" >Guardar</button> <button class="btn" type="submit" name="configure" >Guardar</button>

View File

@@ -1,16 +1,18 @@
function changeInputType(){ function changeInputType() {
country = document.getElementById("pais").value; country = document.getElementById("pais").value;
region = document.getElementById("provincia"); region = document.getElementById("provincia");
city = document.getElementById("localidad"); city = document.getElementById("localidad");
region_input = document.getElementById("provincia2");
city_input = document.getElementById("localidad2");
if(country == 73){ if (country == 73) {
region.hidden = false; region.hidden = false;
city.hidden = false; city.hidden = false;
region_input.type = "hidden";
city_input.type = "hidden";
} else { } else {
region.hidden = true; region.hidden = true;
city.hidden = true; city.hidden = true;
region_input = document.getElementById("provincia2");
city_input = document.getElementById("localidad2");
region_input.type = "text"; region_input.type = "text";
city_input.type = "text"; city_input.type = "text";
} }

View File

@@ -23,7 +23,8 @@ function listRows($pdo, $table)
return $result; return $result;
} }
function fetchLatestRegion($pdo){ function fetchLatestRegion($pdo)
{
$query = "SELECT id_provincia FROM provincias ORDER BY id_provincia DESC LIMIT 1;"; $query = "SELECT id_provincia FROM provincias ORDER BY id_provincia DESC LIMIT 1;";
$result = $pdo->prepare($query); $result = $pdo->prepare($query);
$result->execute(); $result->execute();
@@ -31,7 +32,8 @@ function fetchLatestRegion($pdo){
return $data; return $data;
} }
function fetchLatestCity($pdo){ function fetchLatestCity($pdo)
{
$query = "SELECT id_municipio FROM municipios ORDER BY id_municipio DESC LIMIT 1;"; $query = "SELECT id_municipio FROM municipios ORDER BY id_municipio DESC LIMIT 1;";
$result = $pdo->prepare($query); $result = $pdo->prepare($query);
$result->execute(); $result->execute();
@@ -39,7 +41,8 @@ function fetchLatestCity($pdo){
return $data; return $data;
} }
function createRegion($pdo, $data){ function createRegion($pdo, $data)
{
$query = "INSERT INTO provincias (id_provincia, provincia) VALUES (?,?)"; $query = "INSERT INTO provincias (id_provincia, provincia) VALUES (?,?)";
$row = fetchLatestRegion($pdo); $row = fetchLatestRegion($pdo);
$last_region = $row["id_provincia"]; $last_region = $row["id_provincia"];
@@ -48,7 +51,8 @@ function createRegion($pdo, $data){
return $index; return $index;
} }
function createCity($pdo, $data, $region){ function createCity($pdo, $data, $region)
{
$query = "INSERT INTO municipios (id_provincia, cod_municipio, DC, nombre) VALUES (?,?,?,?)"; $query = "INSERT INTO municipios (id_provincia, cod_municipio, DC, nombre) VALUES (?,?,?,?)";
$pdo->prepare($query)->execute([$region, 999, 999, $data["localidad2"]]); $pdo->prepare($query)->execute([$region, 999, 999, $data["localidad2"]]);
$city = fetchLatestCity($pdo); $city = fetchLatestCity($pdo);
@@ -60,7 +64,7 @@ function createPatient($pdo, $data)
$query = "INSERT INTO paciente $query = "INSERT INTO paciente
(nombre, apellido, fecha_de_nacimiento, documento_identificativo, tipo_documento, direccion, localidad, provincia, pais) (nombre, apellido, fecha_de_nacimiento, documento_identificativo, tipo_documento, direccion, localidad, provincia, pais)
VALUES (?,?,?,?,?,?,?,?,?)"; VALUES (?,?,?,?,?,?,?,?,?)";
if($data["provincia"] == "empty" and $data["localidad"] == "empty"){ if ($data["provincia"] == "empty" and $data["localidad"] == "empty") {
$region = createRegion($pdo, $data); $region = createRegion($pdo, $data);
$city = createCity($pdo, $data, $region); $city = createCity($pdo, $data, $region);
$data["provincia"] = $region; $data["provincia"] = $region;
@@ -76,7 +80,7 @@ function editPatient($pdo, $data, $id)
{ {
$query = "UPDATE paciente SET nombre=?, apellido=?, fecha_de_nacimiento=?, documento_identificativo=?, $query = "UPDATE paciente SET nombre=?, apellido=?, fecha_de_nacimiento=?, documento_identificativo=?,
tipo_documento=?, direccion=?, localidad=?, provincia=?, pais=? WHERE id=?"; tipo_documento=?, direccion=?, localidad=?, provincia=?, pais=? WHERE id=?";
if($data["provincia"] == "empty" and $data["localidad"] == "empty"){ if ($data["provincia"] == "empty" and $data["localidad"] == "empty") {
$region = createRegion($pdo, $data); $region = createRegion($pdo, $data);
$city = createCity($pdo, $data, $region); $city = createCity($pdo, $data, $region);
$data["provincia"] = $region; $data["provincia"] = $region;
@@ -319,7 +323,9 @@ function fetchPatients($pdo)
function fetchReportData($pdo, string $id) function fetchReportData($pdo, string $id)
{ {
$query = "SELECT * FROM informe WHERE id=?"; $query = "SELECT informe.id, titulo, fecha, hora, paciente , contenido, usuario FROM informe
INNER JOIN usuario ON informe.medico = usuario.id
WHERE informe.id=?";
$result = $pdo->prepare($query); $result = $pdo->prepare($query);
$result->execute([$id]); $result->execute([$id]);
$data = $result->fetch(); $data = $result->fetch();
@@ -359,10 +365,10 @@ function configureCalendar($pdo, $data)
} else { } else {
$query = "UPDATE calendario SET hora_inicio_mañana=?, hora_fin_mañana=?, $query = "UPDATE calendario SET hora_inicio_mañana=?, hora_fin_mañana=?,
hora_inicio_tarde=?, hora_fin_tarde=?, horario=?, sabado_habil=?, domingo_habil=?, hora_inicio_tarde=?, hora_fin_tarde=?, horario=?, sabado_habil=?, domingo_habil=?,
duracion_cita_por_defecto=?, medico=? WHERE medico=?"; duracion_cita_por_defecto=? WHERE medico=?";
$pdo->prepare($query)->execute([$data["hora_inicio_mañana"], $data["hora_fin_mañana"], $data["hora_inicio_tarde"], $pdo->prepare($query)->execute([$data["hora_inicio_mañana"], $data["hora_fin_mañana"], $data["hora_inicio_tarde"],
$data["hora_fin_tarde"], $data["horario"], $data["sabado_habil"], $data["domingo_habil"], $data["hora_fin_tarde"], $data["horario"], $data["sabado_habil"], $data["domingo_habil"],
$data["duracion_cita_por_defecto"], $data["medico"], $data["medico"]]); $data["duracion_cita_por_defecto"], $data["medico"]]);
} }
return "Calendario configurado con éxito"; return "Calendario configurado con éxito";
} }
@@ -370,7 +376,9 @@ function configureCalendar($pdo, $data)
function fetchCalendarEvents($pdo, $doctor) function fetchCalendarEvents($pdo, $doctor)
{ {
$query = "SELECT * from cita WHERE medico=?"; $query = "SELECT cita.id, fecha, hora, duracion, medico, observaciones, nombre, apellido, documento_identificativo FROM cita
INNER JOIN paciente ON cita.paciente = paciente.id
WHERE medico=?";
$result = $pdo->prepare($query); $result = $pdo->prepare($query);
$result->execute([$doctor]); $result->execute([$doctor]);
$data = $result->fetchAll(PDO::FETCH_ASSOC); $data = $result->fetchAll(PDO::FETCH_ASSOC);
@@ -384,7 +392,7 @@ function fetchCalendarSettings($pdo, $doctor)
$result = $pdo->prepare($query); $result = $pdo->prepare($query);
$result->execute([$doctor]); $result->execute([$doctor]);
$data = $result->fetch(PDO::FETCH_ASSOC); $data = $result->fetch(PDO::FETCH_ASSOC);
if(empty($data[8])){ if (empty($data[8])) {
$data[8] = 60; $data[8] = 60;
} }
return $data; return $data;
@@ -393,7 +401,9 @@ function fetchCalendarSettings($pdo, $doctor)
function fetchDoctorHolidays($pdo, $doctor) function fetchDoctorHolidays($pdo, $doctor)
{ {
$query = "SELECT * FROM festivo WHERE medico IS NULL OR medico=?"; $query = "SELECT festivo.id, fecha_festivo, tipo_festivo, medico, nombre FROM festivo
INNER JOIN usuario ON festivo.medico = usuario.id;
WHERE medico IS NULL OR medico=?";
$result = $pdo->prepare($query); $result = $pdo->prepare($query);
$result->execute([$doctor]); $result->execute([$doctor]);
$data = $result->fetchAll(PDO::FETCH_ASSOC); $data = $result->fetchAll(PDO::FETCH_ASSOC);
@@ -401,7 +411,8 @@ function fetchDoctorHolidays($pdo, $doctor)
} }
function createAppointment($pdo, $data){ function createAppointment($pdo, $data)
{
$query = "INSERT INTO cita (fecha, hora, duracion, medico, observaciones, paciente) VALUES (?,?,?,?,?,?)"; $query = "INSERT INTO cita (fecha, hora, duracion, medico, observaciones, paciente) VALUES (?,?,?,?,?,?)";
$pdo->prepare($query)->execute([$data["fecha"], $data["hora"], $data["duracion"], $pdo->prepare($query)->execute([$data["fecha"], $data["hora"], $data["duracion"],
$data["doctor"], $data["observaciones"], $data["paciente"]]); $data["doctor"], $data["observaciones"], $data["paciente"]]);
@@ -409,16 +420,29 @@ function createAppointment($pdo, $data){
} }
function editAppointment($pdo, $data){ function editAppointment($pdo, $data)
$query = "UPDATE cita SET (fecha, hora, duracion, medico, observaciones, paciente) VALUES (?,?,?,?,?,?)"; {
$query = "UPDATE cita SET fecha=?, hora=?, duracion=?, observaciones=?, paciente=?
WHERE id=?";
$pdo->prepare($query)->execute([$data["fecha"], $data["hora"], $data["duracion"], $pdo->prepare($query)->execute([$data["fecha"], $data["hora"], $data["duracion"],
$data["doctor"], $data["observaciones"], $data["paciente"]]); $data["observaciones"], $data["paciente"], $data["id"]]);
return "Cita modificada con éxito"; return "Cita modificada con éxito";
} }
function deleteAppointment($pdo, $id){ function deleteAppointment($pdo, $id)
$statement = "DELETE FROM cita where id=?"; {
$statement = "DELETE FROM cita WHERE id=?";
$pdo->prepare($statement)->execute([$id]); $pdo->prepare($statement)->execute([$id]);
return "Cita borrada con éxito"; return "Cita borrada con éxito";
} }
function fetchAppointmentData($pdo, $id)
{
$query = "SELECT id, fecha, hora, duracion, observaciones FROM cita WHERE id=?";
$result = $pdo->prepare($query);
$result->execute([$id]);
$data = $result->fetch();
return $data;
}

32
src/holiday_feed.php Normal file
View File

@@ -0,0 +1,32 @@
<?php
include 'appointment_management.php';
function formatArray($data)
{
$events = array();
foreach ($data as $row) {
$events[] = array(
"id" => $row["id"],
"start" => $row["fecha_festivo"],
"description" => $row["tipo_festivo"],
"doctor" => $row["nombre"],
"rendering" => "background",
"color" => "#ffa6a3",
);
}
return $events;
}
function fetchDatabase()
{
$pdo = connectDatabase();
$data = listHolidays($pdo);
closeDatabase($pdo);
return $data;
}
$result = fetchDatabase();
$events = formatArray($result);
echo json_encode($events);

View File

@@ -13,9 +13,9 @@
<li class="list"><a href="report.php">Informes</a></li> <li class="list"><a href="report.php">Informes</a></li>
<?php endif; ?> <?php endif; ?>
<?php if (isset($_SESSION["user"])): ?> <?php if (isset($_SESSION["user"])): ?>
<li class="list"><a href="user_management.php?logout=1">Log out</a></li> <li class="list"><a href="user_management.php?logout=1">Cerrar sesión</a></li>
<?php else: ?> <?php else: ?>
<li class="list"><a href="login.php">Login</a></li> <li class="list"><a href="login.php">Iniciar sesión</a></li>
<?php endif; ?> <?php endif; ?>
</ul> </ul>
</nav> </nav>

48
src/print_page.js Normal file
View File

@@ -0,0 +1,48 @@
function printExternalHTML(url) {
var printWindow = window.open(url, 'Print', 'left=200, top=200, width=950, height=500, toolbar=0, resizable=0');
printWindow.addEventListener('load', function() {
if (Boolean(printWindow.chrome)) {
printWindow.print();
setTimeout(function() {
printWindow.close();
}, 500);
} else {
printWindow.print();
printWindow.close();
}
}, true);
}
function getHTML(url) {
html = null;
$.ajax({
url: url,
async: false,
success: function(data) {
console.log(data);
html = data;
}
});
return html;
}
function printExternalPDF(url) {
var html = getHTML(url);
var pdf = new jsPDF();
margins = {
top: 80,
bottom: 60,
left: 40,
width: 522
};
pdf.fromHTML(
html,
margins.left,
margins.top, {
'width': margins.width
}
),
pdf.save();
}

View File

@@ -7,6 +7,9 @@
<meta name="description" content=""> <meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="static/style.css" type="text/css" media="screen" /> <link rel="stylesheet" href="static/style.css" type="text/css" media="screen" />
<script src="static/jquery-3.5.1.min.js"></script>
<script src="static/jspdf.min.js"></script>
<script src="print_page.js"></script>
</head> </head>
<body> <body>
<?php include 'navbar.php'; ?> <?php include 'navbar.php'; ?>
@@ -25,14 +28,13 @@
<th>Hora</th> <th>Hora</th>
<th>Paciente</th> <th>Paciente</th>
<th>Médico</th> <th>Médico</th>
<th colspan="2">Acciones</th> <th colspan="3">Acciones</th>
</tr> </tr>
</thead> </thead>
<?php <?php
include 'database.php'; include 'database.php';
$pdo = connectDatabase(); $pdo = connectDatabase();
$list = listReports($pdo); $list = listReports($pdo);
foreach ($list as $row) : foreach ($list as $row) :
@@ -49,6 +51,12 @@
<td> <td>
<a href="report_management.php?delete=<?php echo $row[0]; ?>" class="del_btn">Borrar</a> <a href="report_management.php?delete=<?php echo $row[0]; ?>" class="del_btn">Borrar</a>
</td> </td>
<td>
<input type="button" value="HTML" class="create_btn" onClick="printExternalHTML('report_content.php?id=<?php echo $row[0]; ?>')">
</td>
<td>
<input type="button" value="PDF" class="create_btn" onClick="printExternalPDF('report_content.php?id=<?php echo $row[0]; ?>')">
</td>
</tr> </tr>
<?php endforeach ?> <?php endforeach ?>
<?php closeDatabase($pdo); ?> <?php closeDatabase($pdo); ?>

38
src/report_content.php Normal file
View File

@@ -0,0 +1,38 @@
<html class="no-js" lang="es">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Gestión de informes</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="static/style.css" type="text/css" media="screen" />
</head>
<body>
<table>
<thead>
<tr>
<th>Titulo</th>
<th>Fecha</th>
<th>Hora</th>
<th>Paciente</th>
<th>Contenido</th>
<th>Médico</th>
</tr>
</thead>
<?php
include 'database.php';
$pdo = connectDatabase();
$data = fetchReportData($pdo, $_GET["id"]);
?>
<tr>
<td><?php echo $data[1]; ?></td>
<td><?php echo $data[2]; ?></td>
<td><?php echo $data[3]; ?></td>
<td><?php echo $data[4]; ?></td>
<td><?php echo $data[5]; ?></td>
<td><?php echo $data[6]; ?></td>
</tr>
<?php closeDatabase($pdo); ?>
</table>
</body>

View File

@@ -14,8 +14,8 @@
include 'database.php'; include 'database.php';
$pdo = connectDatabase(); $pdo = connectDatabase();
$doctors = listDoctors($pdo);
$patients = fetchPatients($pdo); $patients = fetchPatients($pdo);
$user = finduser($pdo, $_SESSION["user"]);
?> ?>
<form name="create_form" method="post" action="report_management.php" onsubmit="return validateReport();"> <form name="create_form" method="post" action="report_management.php" onsubmit="return validateReport();">
<div class="input-group"> <div class="input-group">
@@ -38,14 +38,6 @@
<?php endforeach ?> <?php endforeach ?>
</select> </select>
</div> </div>
<div class="input-group">
<select id="medico" name="medico">
<option>Seleccione un médico</option>
<?php foreach ($doctors as $row) : ?>
<option value="<?php echo $row[0]; ?>"><?php echo $row[1]; ?></option>
<?php endforeach ?>
</select>
</div>
<div class="input-group"> <div class="input-group">
<label>contenido</label> <label>contenido</label>
<input type="text" name="contenido" value=""> <input type="text" name="contenido" value="">
@@ -53,7 +45,7 @@
<div class="input-group"> <div class="input-group">
<button class="btn" type="submit" name="create" >Guardar</button> <button class="btn" type="submit" name="create" >Guardar</button>
</div> </div>
<input type="button" value="Imprimir" onClick="window.print()"> <input type="hidden" id="medico" name="medico" value="<?php echo $user[0][4]; ?>">
</form> </form>
<?php closeDatabase($pdo); ?> <?php closeDatabase($pdo); ?>
</body> </body>

View File

@@ -1,6 +1,7 @@
<?php <?php
include'database.php'; include'database.php';
function reportCreation() function reportCreation()
{ {
$data = $_POST; $data = $_POST;
@@ -10,6 +11,7 @@ function reportCreation()
header('location: report.php'); header('location: report.php');
} }
function reportModification() function reportModification()
{ {
$data = $_POST; $data = $_POST;
@@ -20,6 +22,7 @@ function reportModification()
header('location: report.php'); header('location: report.php');
} }
function reportDeletion() function reportDeletion()
{ {
$id = $_GET["delete"]; $id = $_GET["delete"];
@@ -29,6 +32,7 @@ function reportDeletion()
header('location: report.php'); header('location: report.php');
} }
if (isset($_POST["create"])) { if (isset($_POST["create"])) {
reportCreation(); reportCreation();
} }
@@ -38,6 +42,7 @@ if (isset($_POST["edit"])) {
reportModification(); reportModification();
} }
if (isset($_GET["delete"])) { if (isset($_GET["delete"])) {
reportDeletion(); reportDeletion();
} }

286
src/static/jspdf.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -81,7 +81,7 @@ form {
.edit_btn { .edit_btn {
text-decoration: none; text-decoration: none;
padding: 2px 5px; padding: 2px 5px;
background: #2E8B57; background: #0d841f;
color: white; color: white;
border-radius: 3px; border-radius: 3px;
} }

View File

@@ -1,63 +1,65 @@
function checkDNI(dni) { function checkDNI(dni) {
var number, let, letter; var number,
let, letter;
var regex = /^[XYZ]?\d{5,8}[A-Z]$/; var regex = /^[XYZ]?\d{5,8}[A-Z]$/;
dni = dni.toUpperCase(); dni = dni.toUpperCase();
if(regex.test(dni) === true){ if (regex.test(dni) === true) {
number = dni.substr(0,dni.length-1); number = dni.substr(0, dni.length - 1);
number = number.replace('X', 0); number = number.replace('X', 0);
number = number.replace('Y', 1); number = number.replace('Y', 1);
number = number.replace('Z', 2); number = number.replace('Z', 2);
let = dni.substr(dni.length-1, 1); let = dni.substr(dni.length - 1, 1);
number = number % 23; number = number % 23;
letter = 'TRWAGMYFPDXBNJZSQVHLCKET'; letter = 'TRWAGMYFPDXBNJZSQVHLCKET';
letter = letter.substring(number, number+1); letter = letter.substring(number, number + 1);
if (letter != let) { if (letter !=
let) {
return false; return false;
}else{ } else {
return true; return true;
} }
return false; return false;
} }
} }
function validateString(input){ function validateString(input) {
if(input == ""){ if (input == "") {
return false; return false;
} }
return true; return true;
} }
function validatePatient(){ function validatePatient() {
var name = document.forms["create_form"]["nombre"]; var name = document.forms["create_form"]["nombre"];
var last_name = document.forms["create_form"]["apellido"]; var last_name = document.forms["create_form"]["apellido"];
var dni = document.forms["create_form"]["documento_identificativo"]; var dni = document.forms["create_form"]["documento_identificativo"];
var address = document.forms["create_form"]["direccion"]; var address = document.forms["create_form"]["direccion"];
var country = document.forms["create_form"]["pais"]; var country = document.forms["create_form"]["pais"];
if(!checkDNI(dni.value)){ if (!checkDNI(dni.value)) {
alert("El DNI/NIE no es correcto"); alert("El DNI/NIE no es correcto");
return false; return false;
} }
if(!validateString(name.value)){ if (!validateString(name.value)) {
alert("Introduce el nombre"); alert("Introduce el nombre");
return false; return false;
} }
if(!validateString(last_name.value)){ if (!validateString(last_name.value)) {
alert("Introduce el apellido"); alert("Introduce el apellido");
return false; return false;
} }
if(!validateString(address.value)){ if (!validateString(address.value)) {
alert("Introduce la dirección"); alert("Introduce la dirección");
return false; return false;
} }
if(!validateString(country.value)){ if (!validateString(country.value)) {
alert("Introduce el país"); alert("Introduce el país");
return false; return false;
} }

View File

@@ -1,20 +1,20 @@
function validateString(input){ function validateString(input) {
if(input == ""){ if (input == "") {
return false; return false;
} }
return true; return true;
} }
function validateReport(){ function validateReport() {
var title = document.forms["create_form"]["titulo"]; var title = document.forms["create_form"]["titulo"];
var content = document.forms["create_form"]["contenido"]; var content = document.forms["create_form"]["contenido"];
if(!validateString(title.value)){ if (!validateString(title.value)) {
alert("Introduce el título"); alert("Introduce el título");
return false; return false;
} }
if(!validateString(content.value)){ if (!validateString(content.value)) {
alert("Introduce el contenido"); alert("Introduce el contenido");
return false; return false;
} }

View File

@@ -1,44 +1,44 @@
function validateString(input){ function validateString(input) {
if(input == ""){ if (input == "") {
return false; return false;
} }
return true; return true;
} }
function validateEmail(input){ function validateEmail(input) {
var emailID = input; var emailID = input;
atpos = emailID.indexOf("@"); atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf("."); dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 )) { if (atpos < 1 || (dotpos - atpos < 2)) {
return false; return false;
} }
return true; return true;
} }
function validateUser(){ function validateUser() {
var name = document.forms["create_form"]["nombre"]; var name = document.forms["create_form"]["nombre"];
var user = document.forms["create_form"]["usuario"]; var user = document.forms["create_form"]["usuario"];
var password = document.forms["create_form"]["contraseña"]; var password = document.forms["create_form"]["contraseña"];
var email = document.forms["create_form"]["correo"]; var email = document.forms["create_form"]["correo"];
if(!validateString(name.value)){ if (!validateString(name.value)) {
alert("Introduce el nombre"); alert("Introduce el nombre");
return false; return false;
} }
if(!validateString(user.value)){ if (!validateString(user.value)) {
alert("Introduce el usuario"); alert("Introduce el usuario");
return false; return false;
} }
if(!validateString(password.value)){ if (!validateString(password.value)) {
alert("Introduce la contraseña"); alert("Introduce la contraseña");
return false; return false;
} }
if(!validateEmail(email.value)){ if (!validateEmail(email.value)) {
alert("El correo proporcionado es incorrecto"); alert("El correo proporcionado es incorrecto");
return false; return false;
} }
@@ -46,16 +46,16 @@ function validateUser(){
return true; return true;
} }
function validateLogin(){ function validateLogin() {
var user = document.forms["login_form"]["usuario"]; var user = document.forms["login_form"]["usuario"];
var password = document.forms["login_form"]["contraseña"]; var password = document.forms["login_form"]["contraseña"];
if(!validateString(user.value)){ if (!validateString(user.value)) {
alert("Introduce el usuario"); alert("Introduce el usuario");
return false; return false;
} }
if(!validateString(password.value)){ if (!validateString(password.value)) {
alert("Introduce la contraseña"); alert("Introduce la contraseña");
return false; return false;
} }