Skip to content

Commit

Permalink
Merge pull request #5 from despediteerik/v0.4-backend-cleanup
Browse files Browse the repository at this point in the history
Limpieza de código: comentarios en prácticamente todo, reestructuración de JS y CSS
  • Loading branch information
despedite authored Dec 18, 2019
2 parents e2e8ec9 + f376554 commit cedfdfb
Show file tree
Hide file tree
Showing 9 changed files with 498 additions and 378 deletions.
306 changes: 68 additions & 238 deletions crear.html
Original file line number Diff line number Diff line change
@@ -1,246 +1,76 @@
<!DOCTYPE html>
<html>
<head>
<!--UTF-8-->
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<!--Favicon y nombre-->
<link rel="icon" type="image/png" href="img/favicon.png">
<title>Crear persona - APIHook</title>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"><!--Import materialize.css-->
<link href="css/materialize.min.css" media="screen,projection" rel="stylesheet" type="text/css">
<script src="js/jquery-3.4.1.min.js" type="text/javascript">
</script><!--Let browser know website is optimized for mobile-->
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<title></title>
<!-- UTF-8 -->
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<!-- Favicon y nombre -->
<link href="img/favicon.png" rel="icon" type="image/png">
<!-- Si "?edit=true", entonces "Modificar persona - APIHook" -->
<title>Agregar persona - APIHook</title>
<!-- Iconos de Material Design -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Materialize -->
<link href="css/materialize.min.css" media="screen,projection" rel="stylesheet" type="text/css">
<script src="js/jquery-3.4.1.min.js" type="text/javascript">
</script>
<!-- Código para avisarle al navegador que es comp. con móviles -->
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<!-- CSS personalizado -->
<link href="css/style.css" media="screen,projection" rel="stylesheet" type="text/css">
<!-- Código de Javascript -->
<script src="js/crear.js" type="text/javascript"></script>
</head>
<body>
<nav>
<div class="nav-wrapper purple darken-2" style="padding: 0px 50px 0px 50px;">
<a class="brand-logo" href="index.html"><img src="img/logo.png" style="height: 32px; vertical-align: middle; padding-bottom: 7px;"></a>
<ul class="right hide-on-med-and-down" id="nav-mobile">
<li>
<a href="https://github.com/despediteerik/Trinomio-API">Github</a>
</li>
<li>
<a href="index.html">Personas</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<h4 id="title" class="objpadding">Crear una persona</h4><br>
<div class="row">
<form action="./script.php" id="dropdown" method="get" name="dropdown">
<div class="input-field col s12">
<input id="text" name="first_name" class="validate">
<label for="first_name" class="active">Nombre</label>
</div>
<div class="input-field col s12">
<input id="surname" name="last_name" class="validate">
<label for="last_name" class="active">Apellido</label>
</div>
<div class="input-field col s12">
<input id="email" name="email" class="validate">
<label for="email" class="active">Correo electrónico</label>
<span class="helper-text" data-error="Escribe un correo electrónico válido." data-success="¡Excelente!"></span>
</div>
<!--Gets deleted after checkbox populates itself with JSON values -->
<div id="preloader">
<div class="col s4 cbox">
<p>
<label>
<input type="checkbox" disabled="disabled" />
<span>Cargando...</span>
</label>
</p>
</div>
<div class="col s4 cbox">
<p>
<label>
<input type="checkbox" disabled="disabled" />
<span>Cargando...</span>
</label>
</p>
</div>
<div class="col s4 cbox">
<p>
<label>
<input type="checkbox" disabled="disabled" />
<span>Cargando...</span>
</label>
</p>
</div>
<a class="btn disabled nicebtn objpadding">SUBIR</a>
</div>
</form>

<script type="text/javascript">
var urlParams = new URLSearchParams(window.location.search);
let dropdown = $('#dropdown');

$.getJSON('http://evera.challenge.trinom.io/api/courses', function(data) {
var ele = document.getElementById('dropdown');
for (var i = 0; i < data.length; i++) {
ele.innerHTML += '<div class="col s4 cbox"><p><label><input type="checkbox" name="' + data[i].id + '" id="' + data[i].id + '" value="yes"/><span>' + data[i].name + '</span></label></p></div>'
}
ele.innerHTML += '<br><a onclick="enviarAJson();" class="waves-effect waves-light btn nicebtn objpadding purple darken-1">Subir</a>'
loadData();

//remove preloader (Cargando...)
var elem = document.getElementById('preloader')
elem.parentNode.removeChild(elem);

});

function enviarAJson() {
var first_name = document.getElementById("text").value;
var last_name = document.getElementById("surname").value;
var email = document.getElementById("email").value;
var selected_courses = [];
var amountOfObjects;
<!-- Barra de Navegación -->
<nav>
<div class="nav-wrapper purple darken-2">
<a class="brand-logo" href="index.html"><img src="img/logo.png" id="logo"></a>
<ul class="right hide-on-med-and-down" id="nav-mobile">
<li>
<a href="https://github.com/despediteerik/Trinomio-API">Github</a>
</li>
<li>
<a href="index.html">Personas</a>
</li>
</ul>
</div>
</nav>

if (!($("#dropdown input:checkbox:checked").length > 0))
{
M.toast({html: '¡No introduciste ningún curso!', classes: 'rounded'});
return;
}

// Might be a very round-about way to check how many checkboxes are there
// TO-DO: check if I can make this in a less round-about way
$.getJSON('http://evera.challenge.trinom.io/api/courses', function(data) {
amountOfObjects = data.length;
for (var i = 0; i < amountOfObjects; i++) {
selected_courses[i] = document.getElementById(data[i].id).checked;
}
});
var dateObj = new Date();
var curTime = dateObj.toISOString();
var jsonObj = {
'id': 0,
'first_name': first_name,
'last_name': last_name,
'email': email,
'created_at': curTime,
'updated_at': curTime,
'courses': []
}
//template for the JSON we're going to add the courses to!
$.getJSON('http://evera.challenge.trinom.io/api/courses', function(data) {
for (var i = 0; i < data.length; i++) {
if (selected_courses[i] == true) {
jsonObj.courses.push({
'id': (i + 1),
'name': 'placeholder',
'language_code': 'ph',
'level_id': 0,
'created_at': curTime,
'updated_at': curTime,
'level': {
'id': 0,
'name': 'placeholder'
},
'language': {
'code': 'placeholder',
'name': 'placeholder'
}
})
//luckily Trinomio did all of the heavy lifting, and by just inputting the ID number it fills all of the spaces for us.
}
}
//Finally, FINALLY, we have our JSON object. Finally.
//Now we can just send a POST request to the API server.
//I got stuck for like a day on this part because JS variables were messing with me.
console.log(JSON.stringify(jsonObj))
if (urlParams.has('edit')) { //urlparams edit = true
var peoplesId = urlParams.get('id');
var url = "http://evera.challenge.trinom.io/api/peoples/" + peoplesId;
console.log(url);
var peoplesType = "PUT";
var peoplesTerm = "actualizado";
} else {
var url = "http://evera.challenge.trinom.io/api/peoples";
var peoplesType = "POST";
var peoplesTerm = "subido";
}
$.ajax({
url: url,
type: peoplesType,
data: JSON.stringify(jsonObj),
contentType: "application/json",
dataType: 'json',
error: function(xhr, status, error) {
// Error catching
console.log(error);
console.log(xhr.responseText);
errores = JSON.parse(xhr.responseText);
for (var key in errores.errors) {
for (var error in errores.errors[key]) {
// Switch-case structure for translating the errors JSON may give.
// It isn't translating everything - more technical errors I'd rather have in English anyways,
// but it's the four most common errors having to do with user error.
switch(errores.errors[key][error]) {
case "The first name field is required.":
M.toast({html: "Se requiere escribir el nombre.", classes: 'rounded'});
break;
case "The last name field is required.":
M.toast({html: "Se requiere escribir el apellido.", classes: 'rounded'});
break;
case "The email field is required.":
M.toast({html: "Se requiere escribir el correo electrónico.", classes: 'rounded'});
break;
case "The email has already been taken.":
M.toast({html: "Este correo electrónico ya está en uso.", classes: 'rounded'});
break;
default:
// In case the error doesn't exist, just print the original error in English.
M.toast({html: errores.errors[key][error], classes: 'rounded'});
break;
}
}
}
},
success: function() {
var toastHTML = '<span>¡Tu entrada se ha ' + peoplesTerm + ' con éxito!</span><a href="./index.html"><button class="btn-flat toast-action">Mirar</button></a>';
M.toast({html: toastHTML, classes: 'rounded'});
} //TO-DO: send them back to index. probably add an alert afterwards
});
});
}


function loadData() {
if(urlParams.has('edit')) {
var first = document.getElementById('text');
var last = document.getElementById('surname');
var email = document.getElementById('email');
first.value = urlParams.get('first_name')
last.value = urlParams.get('last_name')
email.value = urlParams.get('email')
}
}
//NOTE: The following could be on the function loadData();, but since we have to wait until the JSON-populated
//checkboxes load before changing the title, it looks jarring and breaks the illusion of two different forms.
if(urlParams.has('edit')) {
var ele = document.getElementById('title');
ele.innerHTML = "Modificar una persona"
document.title = "Modificar persona - APIHook";
}
</script>
</div>
</div>
<!-- Formulario (aka el inicio real de la página) -->
<div class="container">
<!-- El título cambia dependiendo de si "?edit=true" existe -->
<h4 class="objpadding" id="mainTitle">Agregar una persona</h4><br>
<div class="row">
<form action="./script.php" id="checkboxForm" method="get" name="dropdown">
<div class="input-field col s12">
<input class="validate" id="text" name="first_name"> <label class="active" for="first_name">Nombre</label>
</div>
<div class="input-field col s12">
<input class="validate" id="surname" name="last_name"> <label class="active" for="last_name">Apellido</label>
</div>
<div class="input-field col s12">
<input class="validate" id="email" name="email"> <label class="active" for="email">Correo electrónico</label>
</div>
<!-- Estos placeholders de "Cargando..." se mantienen hasta que la checkbox se puebla con los valores en JSON. -->
<!-- Probé poniendo unos preloaders al estilo de spinners, pero quedaban mal porque duraba un par de ms. la carga. -->
<!-- Si no hay Internet, esta parte se va a mantener en su lugar, porque no le llegan las requests a la API. -->
<div id="preloader">
<div class="col s4 cbox">
<p><label><input disabled="disabled" type="checkbox"> <span>Cargando...</span></label></p>
</div>
<div class="col s4 cbox">
<p><label><input disabled="disabled" type="checkbox"> <span>Cargando...</span></label></p>
</div>
<div class="col s4 cbox">
<p><label><input disabled="disabled" type="checkbox"> <span>Cargando...</span></label></p>
</div><a class="btn disabled nicebtn objpadding">SUBIR</a>
</div>
</form>
</div>
</div>
<script type="text/javascript" src="js/materialize.min.js"></script>
<style>
.nicebtn
{
margin-top: 15px;
}
.objpadding
{
margin-left: 10px;
}
</style>

<!-- Javascript para Materialize! (Aparentemente, cargarlo al final de la página lo hace más rápido.) -->
<script src="js/materialize.min.js" type="text/javascript"></script>
</body>
</html>
</html>
39 changes: 39 additions & 0 deletions css/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/* CSS para Index */

i.icon-black {
color: black;
}


#tableContainer {
width: 90%;
margin-top: 20px;
margin-bottom: 50px;
}

.childTable {
background-color: gainsboro;
}

/* CSS para Crear */

.nicebtn
{
margin-top: 15px;
}
.objpadding
{
margin-left: 10px;
}

/* CSS multi-uso */

#logo {
height: 32px;
vertical-align: middle;
padding-bottom: 7px;
}

.nav-wrapper {
padding: 0px 50px 0px 50px;
}
Binary file added img/botones.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/expandir.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/toasteliminado.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit cedfdfb

Please sign in to comment.