Skip to content

Commit

Permalink
Crear nuevo usuario
Browse files Browse the repository at this point in the history
  • Loading branch information
juanis2112 committed Jul 19, 2020
1 parent f5a3e0d commit 1d13bc9
Show file tree
Hide file tree
Showing 8 changed files with 172 additions and 76 deletions.
66 changes: 52 additions & 14 deletions Epsilon/App.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@
import json


# General constants
ROLES = [
"estudiante",
"profesor",
"administrador",
]

# Connection to DataBase
conn = psycopg2.connect(user="postgres",
Expand Down Expand Up @@ -59,15 +65,16 @@ def load_user(user_id):
return User(user_id, user_type)
except Exception:
return None



def login_required(role="ANY"):
def wrapper(fn):
@wraps(fn)
def decorated_view(*args, **kwargs):
if not flask_login.current_user.is_authenticated:
return app.login_manager.unauthorized()
urole = flask_login.current_user.get_urole()
if ( (urole != role) and (role != "ANY")):
if role != "ANY" and ROLES.index(urole) < ROLES.index(role):
return app.login_manager.unauthorized()
return fn(*args, **kwargs)
return decorated_view
Expand Down Expand Up @@ -247,6 +254,20 @@ def upload_file(file, path_to_file, data_insertion_path, **kwargs):
with open(data_insertion_path, 'r', encoding='utf-8') as insercion_sql:
sqlFile = insercion_sql.read().format(path=str(csv_file_path), **kwargs)
cur.execute(sqlFile)

def upload_data(role, send_email=False, period=None, year=None):
file = request.files['inputfile']
if role == 'estudiante':
upload_file(file, '../datos_prueba/temp_data_students.csv', '../datos_prueba/insercion_estudiantes.sql', period=period, year=year)
cur.execute("""select usuario,correo_institucional,codigo from personas where tipo = 'estudiante' """)
users = cur.fetchall()
else:
upload_file(file, '../datos_prueba/temp_data_teachers.csv', '../datos_prueba/insercion_empleados.sql')
cur.execute("""select usuario,correo_institucional,codigo from personas where tipo = 'profesor' """)
users = cur.fetchall()
if send_email:
for user in users:
send_email(user[0],user[1],user[2])

def update_grades(grade1, grade2, grade3, grade4, grade5, class_name, user, teacher_usr):
cur.execute("""UPDATE toma
Expand Down Expand Up @@ -918,12 +939,7 @@ def import_data_from_file_year(data_type, year, period):
@app.route('/upload_teachers', methods=['POST'])
@login_required(role='administrador')
def upload_teachers():
file = request.files['inputfile']
upload_file(file, '../datos_prueba/temp_data_teachers.csv', '../datos_prueba/insercion_empleados.sql')
cur.execute("""select usuario,correo_institucional,codigo from personas where tipo = 'profesor' """)
users = cur.fetchall()
# for user in users:
# send_email(user[0],user[1],user[2])
upload_data(role='teacher', send_email=False)
count = count_admin_alerts()
return render_template('admin/import_success.html', count=count)

Expand All @@ -932,12 +948,7 @@ def upload_teachers():
def upload_students():
period = request.form['period']
year = request.form['year']
file = request.files['inputfile']
upload_file(file, '../datos_prueba/temp_data_students.csv', '../datos_prueba/insercion_estudiantes.sql', period=period, year=year)
cur.execute("""select usuario,correo_institucional,codigo from personas where tipo = 'estudiante' """)
users = cur.fetchall()
# for user in users:
# send_email(user[0],user[1],user[2])
upload_data(role='estudiante', send_email=False, period=period, year=year)
count = count_admin_alerts()
return redirect(url_for('import_data_from_file_year', data_type='classes', year=year, period=period))

Expand All @@ -950,6 +961,33 @@ def upload_classes(year, period):
return render_template('admin/import_success.html', count=count)


@app.route("/create_user/", methods=['POST', 'GET'])
@login_required(role='administrador')
def create_user():
count = count_admin_alerts()
return render_template('admin/create_user.html', count=count)


@app.route("/upload_new_/", methods=['POST'])
@login_required(role='administrador')
def upload_new_user():
file = request.files['inputfile']
user_role = request.form['user_role']
if user_role=='estudiante':
cur.execute("""(SELECT max(anio) FROM RESUMEN)""")
year = int(cur.fetchone()[0])
cur.execute( """(SELECT max(periodo) FROM RESUMEN WHERE anio =
(SELECT max(anio) FROM RESUMEN))""")
period = int(cur.fetchone()[0])
upload_data(role='estudiante', send_email=False, period=period, year=year)
elif user_role=='profesor':
upload_data(role='profesor', send_email=False)
else:
flash('Error', 'error')
return render_template('user_upload_success')



# ---- Admin: Reports -----------------------------------------------------------------------------
@app.route("/class_report/<string:user_name>/<string:class_name>/grupo:<string:group>/<string:year>/<string:period>", methods=['POST', 'GET'])
@login_required(role='administrador')
Expand Down
2 changes: 1 addition & 1 deletion Epsilon/templates/admin/admin_functions.html
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
Importar información periodo académico
</li>
</a>
<a href="{{url_for('admin_functions')}}">
<a href="{{url_for('create_user')}}">
<li style="font-size:25px;">
Crear usuario nuevo
</li>
Expand Down
21 changes: 5 additions & 16 deletions Epsilon/templates/admin/admin_students.html
Original file line number Diff line number Diff line change
Expand Up @@ -181,33 +181,22 @@
});
}

/*An array containing all the country names in the world:*/
var estudiantes={{students | tojson}};
var nombres=new Array(estudiantes.length);
for(var i=0;i<estudiantes.length;i++){
nombres[i]=estudiantes[i][1]+" "+estudiantes[i][2]+" "+estudiantes[i][3];
}
/*initiate the autocomplete function on the "myInput" element, and pass along the countries array as possible autocomplete values:*/
autocomplete(document.getElementById("myInput"), nombres);

function azulfiltro(){
var nombre=document.getElementById("myInput").value;
var j=nombres.indexOf(nombre);
console.log(j);
var lista=document.getElementById("lista-estudiantes");
if(j!=-1){
for(var i=2;i<lista.childNodes.length-1;i++){
if(i!=j+2)
lista.childNodes[i].style.display="none";
else
lista.childNodes[i].style.display="list-item";
lista.childNodes[i].style.transform="translate3d(0,0,0)";
}
}
else{
for(var i=2;i<lista.childNodes.length-1;i++){
var lista=document.getElementById("lista-estudiantes")
for(var i=2;i<lista.childNodes.length-1;i++){
if(lista.childNodes[i].childNodes[0].text.toLowerCase().includes(nombre.toLowerCase())) {
lista.childNodes[i].style.display="list-item";
lista.childNodes[i].style.transform="translate3d(0,0,0)";
} else {
lista.childNodes[i].style.display="none";
}
}
}
Expand Down
75 changes: 75 additions & 0 deletions Epsilon/templates/admin/create_user.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
{% extends "layouts/estructura_administrador.html" %}

{% block lateral %}
<ul>
<a href="{{url_for('load_students')}}">
<li>
<div class="menu-box">
<div >
Estudiantes
</div>
<img src="{{ url_for('static', filename='template_general/imagenes/student.png') }}" width="30px" width="30px" style="background-color:white ;">
</div>
</li>
</a>
<a href="{{url_for('load_teachers')}}">
<li>
<div class="menu-box">
<div >
Profesores
</div>
<img src="{{ url_for('static', filename='template_general/imagenes/profesorbien.png') }}" width="30px" width="30px" style="background-color:white ;">
</div>
</li>
</a>
<a href="{{url_for('historic_class')}}">
<li>
<div class="menu-box">
<div >
Materias
</div>
<img src="{{ url_for('static', filename='template_general/imagenes/materia.png') }}" width="30px" width="30px" style="background-color:white ;">
</div>
</li>
</a>
<a href="{{url_for('admin_functions')}}">
<li style="background-color: #0099cc;">
<div class="menu-box">
<div >
Administración
</div>
<img src="{{ url_for('static', filename='template_general/imagenes/campana.png') }}" width="30px" width="30px" style="background-color:white ;">
</div>
</li>
</a>
</ul>
{% endblock %}
{% block tablas %}
<a href="{{url_for('admin_functions')}}" class="btn">
<img src="{{ url_for('static', filename='template_general/imagenes/retorno.png') }}" height="13px" width="13px">
</a>
<ul style="list-style-type:none">
<div style="background-color: white; border: 1px solid black; padding: 10px;">

<form method= "POST" action="{{url_for('upload_new_user')}}" id="user_upload" enctype=multipart/form-data>
Seleccione el(los) tipo de usuario que va a crear

<label for="user_role"></label>
<select name="user_role" id="role" form="user_upload">
<option value="Estudiante">Estudiante</option>
<option value="Profesor">Profesor</option>
<option value="Administrador">Administrador</option>
</select>
<br>
Seleccione a continuación el archivo con los datos de los nuevos usuarios que desea crear:

<div style="text-align: center;">
<input type="file" name="inputfile" id="file" class="inputfile" data-multiple-caption="{count} files selected" multiple/>
<label for="file" class="archivo">seleccionar archivo</label>
<input type="submit" class="btn" value="subir" >
</div>
</form>
</div>
</div>
</ul>
{% endblock %}
5 changes: 5 additions & 0 deletions datos_prueba/new_student.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Documento_Ingreso,Documento_Actual,Codigo,Apellido_1_Estudiante,Apellido_2_Estudiante,Nombres_Estudiante,Acceso,Subacceso,Correo_Institucional,Sexo,Facultad_o_Escuela,Programa,Semestre,Creditos_inscritos,Codigo_Asignatura,Nombre_Asignatura,Creditos_Asignatura,Grupo_Asignatura,Tipologia_Asignatura,Nota_1er_Corte,Corte_1p,Nota_2do_Corte,Corte_2p,Nota_3er_Corte,Corte_3p,Nota_4to_Corte,Corte_4p,Nota_5to_Corte,Corte_5p
495147,433234,937606,GuzmanLemus,Juan,Extranjero,GENERAL,[email protected],M,"ESCUELA DE INGENIERIA,CIENCIA Y TECNOLOGIA",MATEMATICAS APLICADAS Y CIENCIAS DE LA COMPUTACION,3,17,94340,Precalculo,3,1,OBLIGATORIA,4.3,20,4.6,20,3.9,20,3.9,15,3.9,25
495147,433234,937606,GuzmanLemus,Juan,Extranjero,GENERAL,[email protected],M,"ESCUELA DE INGENIERIA,CIENCIA Y TECNOLOGIA",MATEMATICAS APLICADAS Y CIENCIAS DE LA COMPUTACION,3,17,655987,Calculo,3,1,OBLIGATORIA,4.1,20,3.5,20,4.5,20,4.5,15,4.5,25
495147,433234,937606,GuzmanLemus,Juan,Extranjero,GENERAL,[email protected],M,"ESCUELA DE INGENIERIA,CIENCIA Y TECNOLOGIA",MATEMATICAS APLICADAS Y CIENCIAS DE LA COMPUTACION,3,17,667273,"Logica, teoria de numeros y conjuntos",3,1,OBLIGATORIA,4.1,20,3.8,20,4.7,20,4.7,15,4.7,25
495147,433234,937606,GuzmanLemus,Juan,Extranjero,GENERAL,[email protected],M,"ESCUELA DE INGENIERIA,CIENCIA Y TECNOLOGIA",MATEMATICAS APLICADAS Y CIENCIAS DE LA COMPUTACION,3,17,753581,Pensamiento matematico,3,1,OBLIGATORIA,3.2,20,4.4,20,4.2,20,4.2,15,4.2,25
10 changes: 5 additions & 5 deletions datos_prueba/temp_data_classes.csv
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Nombre_completo,Correo,Nombre_Asignatura,Grupo,usuario
Rafael Mendez,rafael.mendez@urosario.edu.co,Precalculo,1,rafael.mendez
Margot Salas,margot.salas@urosario.edu.co,Pensamiento matematico,1,margot.salas
Rafael Mendez,rafael.mendez@urosario.edu.co,Calculo,1,rafael.mendez
Rafael Mendez,rafael.mendez@urosario.edu.co,Calculo,2,rafael.mendez
Edgar Andrade,edgar.andrade@urosario.edu.co,"Logica, teoria de numeros y conjuntos",1,edgar.andrade
German Obando,german.obando@urosario.edu.co,Fundamentos de sistemas digitales,1,german.obando
Edgar Andrade,edgar.andrade@urosario.edu.co,Logica para ciencias de la computación,1,edgar.andrade
Margot Salas,margot.salas@urosario.edu.co,Algebra lineal,1,margot.salas
Alexander Caicedo,alexander.caicedo@urosario.edu.co,Algebra lineal,2,alexander.caicedo
Juan Fernando Perez,juanferna.perez@urosario.edu.co,Manejo de base de datos,1,juanferna.perez
Loading

0 comments on commit 1d13bc9

Please sign in to comment.