Parcourir la source

Cheo first commit

Jose R Ortiz Ubarri il y a 4 ans
Parent
révision
7bfb59f9de
15 fichiers modifiés avec 581 ajouts et 489 suppressions
  1. 3
    0
      admin.py
  2. 74
    0
      authlib.py
  3. 1
    1
      connect.py
  4. 6
    0
      curso.py
  5. 6
    110
      enfermera.py
  6. 4
    111
      estudiante.py
  7. 4
    112
      facultad.py
  8. 37
    43
      index.py
  9. 4
    112
      madre.py
  10. 92
    0
      registro-run.py
  11. 87
    0
      static/curso.js
  12. 63
    0
      static/list.js
  13. 107
    0
      templates/formacurso.html
  14. 79
    0
      templates/listuser.html
  15. 14
    0
      templates/login.html

+ 3
- 0
admin.py Voir le fichier

@@ -3,3 +3,6 @@ def add():
3 3
 
4 4
 def edit(id):
5 5
 	return '{"titulo":"Administración","accion":"Editar","entradas":{"col1":[{"label":"Nombres","type":"text","name":"nombres"},{"label":"Apellidos","type":"text","name":"apellidos"},{"label":"Email","type":"text","name":"email"},{"label":"Fecha de Nacimiento","type":"date","name":"fecha_nac"},{"label":"Genero","type":"select","options":["","Femenino","Masculino","Otro"],"name":"genero"},{"label":"Posición","type":"text","name":"pos"}],"col2":[{"label":"Direcci\u00f3n 1","name":"direccion1"},{"label":"Direcci\u00f3n 2","type":"text","name":"direccion2"},{"label":"Ciudad","type":"text","name":"ciudad"},{"label":"Zipcode","type":"text","name":"zipcode"},{"label":"Tel\u00e9fono 1","type":"tel","name":"tel1"},{"label":"Tel\u00e9fono 2","type":"tel","name":"tel2"}]}}'
6
+
7
+def list():
8
+	return [{"nombres": "Juana", "apellidos":"Del Barrio", "email": "juana1@gmail.com"},{"nombres": "Juana2", "apellidos":"Del Barrio", "email": "juana2@gmail.com"}]

+ 74
- 0
authlib.py Voir le fichier

@@ -0,0 +1,74 @@
1
+
2
+import hashlib, time
3
+from connect import connection, engine, metadata
4
+import sqlalchemy as db
5
+
6
+def hash_pass(password):
7
+    return hashlib.sha256(password.encode()).hexdigest()
8
+
9
+class Auth:
10
+    def __init__(self, session, expire=0):
11
+        self.session = session
12
+        self.expire=expire
13
+
14
+    def checkAuth(self):
15
+        if self.expire and time.time() - self.session["tiempo"] > self.expire:
16
+            self.delAuth()
17
+        else:
18
+            self.session["tiempo"] = time.time()
19
+
20
+        return self.session.get("gallitosccom")
21
+
22
+    def setAuth(self, id, email):
23
+        self.session["gallitosccom"] = True
24
+        self.session["id"] = id
25
+        self.session["email"] = email
26
+        if self.expire:
27
+            self.session["tiempo"] = time.time()
28
+
29
+    def delAuth(self):
30
+        if self.session.get("gallitosccom"):
31
+            self.session.pop("gallitosccom", None)
32
+            self.session.pop("id", None)
33
+            self.session.pop("email", None)
34
+
35
+    def do_login(self, username, password):
36
+        password = hash_pass(password)
37
+        usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
38
+        query = db.select([usuarios])
39
+        if username.find("@") > 1:
40
+            print("email")
41
+            query = query.select_from(usuarios).where(usuarios.columns.email == username)
42
+        else:
43
+            print("username")
44
+            query = query.select_from(usuarios).where(usuarios.columns.username == username)
45
+
46
+        result = connection.execute(query).fetchone()
47
+        if result and password == result["password"]:
48
+            print(result)
49
+            self.setAuth(result["id"], result["email"])
50
+            # Añadir feature de last login.
51
+            return True
52
+
53
+        return False
54
+
55
+    def checkRole(self, tipo):
56
+        tables = {"admin": "administracion", "madre": "madres", "enfermera":"enfermeras", "facultad": "facultad", "estudiante": "estudiantes"}
57
+        if tipo in tables:
58
+            table = tables[tipo]
59
+        else:
60
+            return False
61
+
62
+        usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
63
+        role = db.Table(table, metadata, autoload=True, autoload_with=engine)
64
+        query = db.select([usuarios, role])
65
+        query = query.select_from(usuarios.join(role, usuarios.columns.id == role.columns.user_id)).where(role.columns.user_id == self.session["id"])
66
+        result = connection.execute(query).fetchone()
67
+
68
+        if result:
69
+            return True
70
+
71
+        return False
72
+
73
+    def do_logout(self):
74
+        self.delAuth()

+ 1
- 1
connect.py Voir le fichier

@@ -2,6 +2,6 @@ import sqlalchemy as db
2 2
 # import mysqlclient
3 3
 # mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
4 4
 
5
-engine = db.create_engine('mysql+pymysql://registro_escolar:mwgzHRXTPrS3JEnd@localhost/registro_escolar')
5
+engine = db.create_engine('mysql+pymysql://jose.ortiz23:cS6pHbYlw7XaS4LX@localhost/registro_escolar_test')
6 6
 connection = engine.connect()
7 7
 metadata = db.MetaData()

+ 6
- 0
curso.py Voir le fichier

@@ -0,0 +1,6 @@
1
+def add():
2
+	return '{}'
3
+def edit(id):
4
+	return '{}'
5
+def list():
6
+	return [{"id": 1, "codigo": "Español", "titulo": "Español", "grado": "K", "descripcion": "La descripción"}, {"id": 2, "codigo": "Ingles", "titulo": "Ingles", "grado": "1", "descripcion": "La descripción 2"}]

+ 6
- 110
enfermera.py Voir le fichier

@@ -1,112 +1,8 @@
1
-from connect import connection, engine, metadata
2
-import sqlalchemy as db
3
-from flask import jsonify, redirect, url_for, render_template
4
-import json
5
-# import index.py 
6
-from funciones import valida_fecha
1
+def add():
2
+	return '{"titulo":"Enfermera","accion":"Añadir","entradas":{"col1":[{"label":"Nombres","type":"text","name":"nombres"},{"label":"Apellidos","type":"text","name":"apellidos"},{"label":"Email","type":"text","name":"email"},{"label":"Fecha de Nacimiento","type":"date","name":"fecha_nac"},{"label":"Genero","type":"select","options":["","Femenino","Masculino","Otro"],"name":"genero"},{"label":"Posición","type":"text","name":"pos"}],"col2":[{"label":"Direcci\u00f3n 1","name":"direccion1"},{"label":"Direcci\u00f3n 2","type":"text","name":"direccion2"},{"label":"Ciudad","type":"text","name":"ciudad"},{"label":"Zipcode","type":"text","name":"zipcode"},{"label":"Tel\u00e9fono 1","type":"tel","name":"tel1"},{"label":"Tel\u00e9fono 2","type":"tel","name":"tel2"}]}}'
7 3
 
8
-col1=[{"label":"Nombres","type":"text","name":"nombres","require":"1"},{"label":"Apellidos","type":"text","name":"apellidos","require":"1"},{"label":"Email","type":"email","name":"email","require":"1"},{"label":"Fecha de Nacimiento","type":"date","name":"fecha_nacimiento","require":"1"},{"label":"Genero","type":"select","options":[{"id":"0","label":"Femenino"},{"id":"1","label":"Masculino"},{"id":"2","label":"Otro"}],"name":"genero","require":True},{"label":"Especialidad","type":"text","name":"especialidad","require":False},{"label":"Otro","type":"text","name":"otro","require":False}]
9
-col2=[{"label":"Dirección 1","type":"text","name":"direccion1","require":"1"},{"label":"Dirección 2","type":"text","name":"direccion2","require":False},{"label":"Ciudad","type":"text","name":"ciudad","require":"1"},{"label":"Pais","type":"text","name":"pais","require":"1"},{"label":"Zipcode","type":"text","name":"zipcode","require":"1"},{"label":"Teléfono 1","type":"tel","name":"telefono1","require":"1"},{"label":"Teléfono 2","type":"tel","name":"telefono2","require":False}]
10
-form_order= {"entradas":{"col1":col1,"col2":col2}}
11
-usuarios_col=["nombres", "apellidos", "email", "fecha_nacimiento", "genero", "direccion1", "direccion2", "ciudad", "pais", "zipcode", "telefono1", "telefono2"]
12
-enfermera_col=["especialidad","otro"]
4
+def edit(id):
5
+	return '{"titulo":"Enfermera","accion":"Editar","entradas":{"col1":[{"label":"Nombres","type":"text","name":"nombres"},{"label":"Apellidos","type":"text","name":"apellidos"},{"label":"Email","type":"text","name":"email"},{"label":"Fecha de Nacimiento","type":"date","name":"fecha_nac"},{"label":"Genero","type":"select","options":["","Femenino","Masculino","Otro"],"name":"genero"},{"label":"Posición","type":"text","name":"pos"}],"col2":[{"label":"Direcci\u00f3n 1","name":"direccion1"},{"label":"Direcci\u00f3n 2","type":"text","name":"direccion2"},{"label":"Ciudad","type":"text","name":"ciudad"},{"label":"Zipcode","type":"text","name":"zipcode"},{"label":"Tel\u00e9fono 1","type":"tel","name":"tel1"},{"label":"Tel\u00e9fono 2","type":"tel","name":"tel2"}]}}'
13 6
 
14
-def prepara_values_usuario(data):
15
-	values_list={}
16
-	for item in usuarios_col:
17
-		if item=="fecha_nacimiento":
18
-			values_list.update({item:valida_fecha(data[item])})			
19
-		else:
20
-			values_list.update({item:data[item]})
21
-	return values_list
22
-
23
-def prepara_values_enfermera(data):
24
-	values_list={}
25
-	for item in enfermera_col:
26
-		if item=="educacion_especial" and ("educacion_especial" not in data or data[item]=="0"):
27
-			values_list.update({item:0})
28
-		else:
29
-			values_list.update({item:data[item]})
30
-	return values_list
31
-	
32
-def edit(data):
33
-	usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
34
-	values_list=prepara_values_usuario(data)
35
-	query = db.update(usuarios).values(values_list)
36
-	query = query.where(usuarios.columns.id == data['id'])
37
-	ResultProxy = connection.execute(query,values_list)
38
-
39
-	enfermera = db.Table('enfermeras', metadata, autoload=True, autoload_with=engine)
40
-	values_list=prepara_values_enfermera(data)
41
-	query = db.update(enfermera).values(values_list)
42
-	query = query.where(enfermera.columns.user_id == data['id'])
43
-	ResultProxy = connection.execute(query,values_list)
44
-	return redirect(url_for("formas",accion="edit", tipo="enfermera", id=data['id']))
45
-
46
-def add(data):
47
-	usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
48
-	values_list=prepara_values_usuario(data)
49
-	query = db.insert(usuarios).values(values_list)
50
-	ResultProxy = connection.execute(query,values_list)
51
-	inst_id=ResultProxy.lastrowid
52
-
53
-	enfermera = db.Table('enfermeras', metadata, autoload=True, autoload_with=engine)
54
-	values_list=prepara_values_enfermera(data)
55
-	values_list.update({"user_id":inst_id})
56
-	query = db.insert(enfermera).values(values_list)
57
-	ResultProxy = connection.execute(query,values_list)
58
-	return redirect(url_for("formas",accion="edit", tipo="enfermera", id=inst_id))
59
-
60
-
61
-def add_form():
62
-	i=1
63
-	orden=1
64
-	entradas={}
65
-	for col in form_order["entradas"]:
66
-		col_data=[]
67
-		for item in form_order["entradas"][col]:
68
-			item.update({"tabindex":orden})
69
-			item.update({"disabled":False})
70
-			orden+=1
71
-		entradas.update({"col"+str(i):col_data})
72
-		i+=1
73
-	data= {"titulo":"Enfermera","accion":"Añadir"}
74
-	data.update(form_order)
75
-	data.update({"abled":True})
76
-	return jsonify(data)
77
-	
78
-def edit_form(id, disabled=False):
79
-	enfermera = db.Table('enfermeras', metadata, autoload=True, autoload_with=engine)
80
-	usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
81
-	query = db.select([usuarios, enfermera.columns.especialidad, enfermera.columns.otro])
82
-	query = query.select_from(usuarios.join(enfermera, usuarios.columns.id == enfermera.columns.user_id)).where(enfermera.columns.user_id == id)
83
-	result = connection.execute(query).fetchall()
84
-	if not len(result):
85
-		return False
86
-	for row in result:
87
-		row_as_dict = dict(row)
88
-	i=1
89
-	orden=1
90
-	entradas={}
91
-	for col in form_order["entradas"]:
92
-		col_data=[]
93
-		for item in form_order["entradas"][col]:
94
-			if item["type"]=="select":
95
-				item.update({"value":{"id":row_as_dict[item["name"]]}})
96
-			elif item["type"]=="checkbox":
97
-				item.update({"value":int(row_as_dict[item["name"]])})
98
-			else:
99
-				item.update({"value":str(row_as_dict[item["name"]])})
100
-			item.update({"tabindex":orden})
101
-			item.update({"disabled":disabled})
102
-			col_data.append(item)
103
-			orden+=1
104
-		entradas.update({"col"+str(i):col_data})
105
-		i+=1
106
-	data= {"titulo":"Enfermera","accion":"Editar"}
107
-	data.update({"entradas":entradas})
108
-	abled=True
109
-	if disabled:
110
-		abled=False
111
-	data.update({"abled":abled})
112
-	return jsonify(data)
7
+def list():
8
+	return [{"nombres": "Juana", "apellidos":"Del Barrio", "email": "juana1@gmail.com"},{"nombres": "Juana2", "apellidos":"Del Barrio", "email": "juana2@gmail.com"}]

+ 4
- 111
estudiante.py Voir le fichier

@@ -1,112 +1,5 @@
1
-from connect import connection, engine, metadata
2
-import sqlalchemy as db
3
-from flask import jsonify, redirect, url_for, render_template
4
-import json
5
-# import index.py 
6
-from funciones import valida_fecha
7
-
8
-col1=[{"label":"Nombres","type":"text","name":"nombres","require":"1"},{"label":"Apellidos","type":"text","name":"apellidos","require":"1"},{"label":"Email","type":"email","name":"email","require":"1"},{"label":"Grado","type":"number","name":"grado","require":"1"},{"label":"Fecha de Nacimiento","type":"date","name":"fecha_nacimiento","require":"1"},{"label":"Genero","type":"select","options":[{"id":"0","label":"Femenino"},{"id":"1","label":"Masculino"},{"id":"2","label":"Otro"}],"name":"genero","require":True},{"label":"Educación Especial","type":"checkbox","name":"educacion_especial"}]
9
-col2=[{"label":"Dirección 1","type":"text","name":"direccion1","require":"1"},{"label":"Dirección 2","type":"text","name":"direccion2","require":False},{"label":"Ciudad","type":"text","name":"ciudad","require":"1"},{"label":"Pais","type":"text","name":"pais","require":"1"},{"label":"Zipcode","type":"text","name":"zipcode","require":"1"},{"label":"Teléfono 1","type":"tel","name":"telefono1","require":"1"},{"label":"Teléfono 2","type":"tel","name":"telefono2","require":False}]
10
-form_order= {"entradas":{"col1":col1,"col2":col2}}
11
-usuarios_col=["nombres", "apellidos", "email", "fecha_nacimiento", "genero", "direccion1", "direccion2", "ciudad", "pais", "zipcode", "telefono1", "telefono2"]
12
-estudiantes_col=["grado", "educacion_especial"]
13
-
14
-def prepara_values_usuario(data):
15
-	values_list={}
16
-	for item in usuarios_col:
17
-		if item=="fecha_nacimiento":
18
-			values_list.update({item:valida_fecha(data[item])})			
19
-		else:
20
-			values_list.update({item:data[item]})
21
-	return values_list
22
-
23
-def prepara_values_estudiante(data):
24
-	values_list={}
25
-	for item in estudiantes_col:
26
-		if item=="educacion_especial" and ("educacion_especial" not in data or data[item]=="0"):
27
-			values_list.update({item:0})
28
-		else:
29
-			values_list.update({item:data[item]})
30
-	return values_list
1
+def add():
2
+	return '{"titulo":"Estudiante","accion":"A\u00f1adir","entradas":{"col1":[{"label":"Nombres","type":"text","name":"nombres"},{"label":"Apellidos","type":"text","name":"apellidos"},{"label":"Email","type":"text","name":"email"},{"label":"Grado","type":"text","name":"grado"},{"label":"Fecha de Nacimiento","type":"date","name":"fecha_nac"},{"label":"Genero","type":"select","options":["","Femenino","Masculino","Otro"],"name":"genero"},{"label":"Educaci\u00f3n Especial","type":"checkbox","name":"ed_especial"}],"col2":[{"label":"Direcci\u00f3n 1","name":"direccion1"},{"label":"Direcci\u00f3n 2","type":"text","name":"direccion2"},{"label":"Ciudad","type":"text","name":"ciudad"},{"label":"Zipcode","type":"text","name":"zipcode"},{"label":"Tel\u00e9fono 1","type":"tel","name":"tel1"},{"label":"Tel\u00e9fono 2","type":"tel","name":"tel2"}]}}'
31 3
 	
32
-def edit(data):
33
-	usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
34
-	values_list=prepara_values_usuario(data)
35
-	query = db.update(usuarios).values(values_list)
36
-	query = query.where(usuarios.columns.id == data['id'])
37
-	ResultProxy = connection.execute(query,values_list)
38
-
39
-	estudiantes = db.Table('estudiantes', metadata, autoload=True, autoload_with=engine)
40
-	values_list=prepara_values_estudiante(data)
41
-	query = db.update(estudiantes).values(values_list)
42
-	query = query.where(estudiantes.columns.user_id == data['id'])
43
-	ResultProxy = connection.execute(query,values_list)
44
-	return redirect(url_for("formas",accion="edit", tipo="estudiante", id=data['id']))
45
-
46
-def add(data):
47
-	usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
48
-	values_list=prepara_values_usuario(data)
49
-	query = db.insert(usuarios).values(values_list)
50
-	ResultProxy = connection.execute(query,values_list)
51
-	inst_id=ResultProxy.lastrowid
52
-
53
-	estudiantes = db.Table('estudiantes', metadata, autoload=True, autoload_with=engine)
54
-	values_list=prepara_values_estudiante(data)
55
-	values_list.update({"user_id":inst_id})
56
-	query = db.insert(estudiantes).values(values_list)
57
-	ResultProxy = connection.execute(query,values_list)
58
-	return redirect(url_for("formas",accion="edit", tipo="estudiante", id=inst_id))
59
-
60
-
61
-def add_form():
62
-	i=1
63
-	orden=1
64
-	entradas={}
65
-	for col in form_order["entradas"]:
66
-		col_data=[]
67
-		for item in form_order["entradas"][col]:
68
-			item.update({"tabindex":orden})
69
-			item.update({"disabled":False})
70
-			orden+=1
71
-		entradas.update({"col"+str(i):col_data})
72
-		i+=1
73
-	data= {"titulo":"Estudiante","accion":"Añadir"}
74
-	data.update(form_order)
75
-	data.update({"abled":True})
76
-	return jsonify(data)
77
-	
78
-def edit_form(id, disabled=False):
79
-	estudiantes = db.Table('estudiantes', metadata, autoload=True, autoload_with=engine)
80
-	usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
81
-	query = db.select([usuarios, estudiantes.columns.grado, estudiantes.columns.educacion_especial])
82
-	query = query.select_from(usuarios.join(estudiantes, usuarios.columns.id == estudiantes.columns.user_id)).where(estudiantes.columns.user_id == id)
83
-	result = connection.execute(query).fetchall()
84
-	if not len(result):
85
-		return False
86
-	for row in result:
87
-		row_as_dict = dict(row)
88
-	i=1
89
-	orden=1
90
-	entradas={}
91
-	for col in form_order["entradas"]:
92
-		col_data=[]
93
-		for item in form_order["entradas"][col]:
94
-			if item["type"]=="select":
95
-				item.update({"value":{"id":row_as_dict[item["name"]]}})
96
-			elif item["type"]=="checkbox":
97
-				item.update({"value":int(row_as_dict[item["name"]])})
98
-			else:
99
-				item.update({"value":str(row_as_dict[item["name"]])})
100
-			item.update({"tabindex":orden})
101
-			item.update({"disabled":disabled})
102
-			col_data.append(item)
103
-			orden+=1
104
-		entradas.update({"col"+str(i):col_data})
105
-		i+=1
106
-	data= {"titulo":"Estudiante","accion":"Editar"}
107
-	data.update({"entradas":entradas})
108
-	abled=True
109
-	if disabled:
110
-		abled=False
111
-	data.update({"abled":abled})
112
-	return jsonify(data)
4
+def edit(id):
5
+	return '{"titulo":"Estudiante '+id+'","accion":"Editar","entradas":{"col1":[{"label":"Nombres","type":"text","name":"nombres","value":"Roberta"},{"label":"Apellidos","type":"text","name":"apellidos"},{"label":"Email","type":"text","name":"email"},{"label":"Grado","type":"text","name":"grado"},{"label":"Fecha de Nacimiento","type":"date","name":"fecha_nac"},{"label":"Genero","type":"select","options":["","Femenino","Masculino","Otro"],"name":"genero"},{"label":"Educaci\u00f3n Especial","type":"checkbox","name":"ed_especial"}],"col2":[{"label":"Direcci\u00f3n 1","name":"direccion1"},{"label":"Direcci\u00f3n 2","type":"text","name":"direccion2"},{"label":"Ciudad","type":"text","name":"ciudad"},{"label":"Zipcode","type":"text","name":"zipcode"},{"label":"Tel\u00e9fono 1","type":"tel","name":"tel1"},{"label":"Tel\u00e9fono 2","type":"tel","name":"tel2"}]}}'

+ 4
- 112
facultad.py Voir le fichier

@@ -1,113 +1,5 @@
1
-from connect import connection, engine, metadata
2
-import sqlalchemy as db
3
-from flask import jsonify, redirect, url_for, render_template
4
-import json
5
-# import index.py 
6
-from funciones import valida_fecha
1
+def add():
2
+	return '{"titulo":"Facultad","accion":"Añadir","entradas":{"col1":[{"label":"Nombres","type":"text","name":"nombres"},{"label":"Apellidos","type":"text","name":"apellidos"},{"label":"Email","type":"text","name":"email"},{"label":"Fecha de Nacimiento","type":"date","name":"fecha_nac"},{"label":"Genero","type":"select","options":["","Femenino","Masculino","Otro"],"name":"genero"},{"label":"Posición","type":"text","name":"pos"}],"col2":[{"label":"Direcci\u00f3n 1","name":"direccion1"},{"label":"Direcci\u00f3n 2","type":"text","name":"direccion2"},{"label":"Ciudad","type":"text","name":"ciudad"},{"label":"Zipcode","type":"text","name":"zipcode"},{"label":"Tel\u00e9fono 1","type":"tel","name":"tel1"},{"label":"Tel\u00e9fono 2","type":"tel","name":"tel2"}]}}'
7 3
 
8
-col1=[{"label":"Nombres","type":"text","name":"nombres","require":"1"},{"label":"Apellidos","type":"text","name":"apellidos","require":"1"},{"label":"Email","type":"email","name":"email","require":"1"},{"label":"Fecha de Nacimiento","type":"date","name":"fecha_nacimiento","require":"1"},{"label":"Genero","type":"select","options":[{"id":"0","label":"Femenino"},{"id":"1","label":"Masculino"},{"id":"2","label":"Otro"}],"name":"genero","require":True},{"label":"Especialidad","type":"text","name":"especialidad","require":"1"},{"label":"Educaci\u00f3n Especial","type":"checkbox","name":"educacion_especial"}]
9
-col2=[{"label":"Dirección 1","type":"text","name":"direccion1","require":"1"},{"label":"Dirección 2","type":"text","name":"direccion2","require":False},{"label":"Ciudad","type":"text","name":"ciudad","require":"1"},{"label":"Pais","type":"text","name":"pais","require":"1"},{"label":"Zipcode","type":"text","name":"zipcode","require":"1"},{"label":"Teléfono 1","type":"tel","name":"telefono1","require":"1"},{"label":"Teléfono 2","type":"tel","name":"telefono2","require":False}]
10
-form_order= {"entradas":{"col1":col1,"col2":col2}}
11
-usuarios_col=["nombres", "apellidos", "email", "fecha_nacimiento", "genero", "direccion1", "direccion2", "ciudad", "pais", "zipcode", "telefono1", "telefono2"]
12
-facultad_col=["especialidad","educacion_especial"]
13
-
14
-def prepara_values_usuario(data):
15
-	values_list={}
16
-	for item in usuarios_col:
17
-		if item=="fecha_nacimiento":
18
-			values_list.update({item:valida_fecha(data[item])})			
19
-		else:
20
-			values_list.update({item:data[item]})
21
-	return values_list
22
-
23
-def prepara_values_facultad(data):
24
-	values_list={}
25
-	for item in facultad_col:
26
-		if item=="educacion_especial" and ("educacion_especial" not in data or data[item]=="0"):
27
-			values_list.update({item:0})
28
-		else:
29
-			values_list.update({item:data[item]})
30
-	return values_list
31
-	
32
-def edit(data):
33
-	usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
34
-	values_list=prepara_values_usuario(data)
35
-	query = db.update(usuarios).values(values_list)
36
-	query = query.where(usuarios.columns.id == data['id'])
37
-	ResultProxy = connection.execute(query,values_list)
38
-
39
-	facultad = db.Table('facultad', metadata, autoload=True, autoload_with=engine)
40
-	values_list=prepara_values_facultad(data)
41
-	query = db.update(facultad).values(values_list)
42
-	query = query.where(facultad.columns.user_id == data['id'])
43
-	ResultProxy = connection.execute(query,values_list)
44
-	return redirect(url_for("formas",accion="edit", tipo="facultad", id=data['id']))
45
-
46
-def add(data):
47
-	usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
48
-	values_list=prepara_values_usuario(data)
49
-	query = db.insert(usuarios).values(values_list)
50
-	ResultProxy = connection.execute(query,values_list)
51
-	inst_id=ResultProxy.lastrowid
52
-
53
-	facultad = db.Table('facultad', metadata, autoload=True, autoload_with=engine)
54
-	values_list=prepara_values_facultad(data)
55
-	values_list.update({"user_id":inst_id})
56
-	query = db.insert(facultad).values(values_list)
57
-	ResultProxy = connection.execute(query,values_list)
58
-	return redirect(url_for("formas",accion="edit", tipo="facultad", id=inst_id))
59
-
60
-
61
-def add_form():
62
-	i=1
63
-	orden=1
64
-	entradas={}
65
-	for col in form_order["entradas"]:
66
-		col_data=[]
67
-		for item in form_order["entradas"][col]:
68
-			item.update({"tabindex":orden})
69
-			item.update({"disabled":False})
70
-			orden+=1
71
-		entradas.update({"col"+str(i):col_data})
72
-		i+=1
73
-	data= {"titulo":"Facultad","accion":"Añadir"}
74
-	data.update(form_order)
75
-	data.update({"abled":True})
76
-	return jsonify(data)
77
-	
78
-def edit_form(id, disabled=False):
79
-	facultad = db.Table('facultad', metadata, autoload=True, autoload_with=engine)
80
-	usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
81
-	query = db.select([usuarios, facultad.columns.especialidad, facultad.columns.educacion_especial])
82
-	query = query.select_from(usuarios.join(facultad, usuarios.columns.id == facultad.columns.user_id)).where(facultad.columns.user_id == id)
83
-	result = connection.execute(query).fetchall()
84
-	if not len(result):
85
-		return False
86
-	for row in result:
87
-		row_as_dict = dict(row)
88
-	i=1
89
-	orden=1
90
-	entradas={}
91
-	for col in form_order["entradas"]:
92
-		col_data=[]
93
-		for item in form_order["entradas"][col]:
94
-			if item["type"]=="select":
95
-				item.update({"value":{"id":row_as_dict[item["name"]]}})
96
-			elif item["type"]=="checkbox":
97
-				item.update({"value":int(row_as_dict[item["name"]])})
98
-			else:
99
-				item.update({"value":str(row_as_dict[item["name"]])})
100
-			item.update({"tabindex":orden})
101
-			item.update({"disabled":disabled})
102
-			col_data.append(item)
103
-			orden+=1
104
-		entradas.update({"col"+str(i):col_data})
105
-		i+=1
106
-	data= {"titulo":"Facultad","accion":"Editar"}
107
-	data.update({"entradas":entradas})
108
-	abled=True
109
-	if disabled:
110
-		abled=False
111
-	data.update({"abled":abled})
112
-	return jsonify(data)
113
-	
4
+def edit(id):
5
+	return '{"titulo":"Facultad","accion":"Editar","entradas":{"col1":[{"label":"Nombres","type":"text","name":"nombres"},{"label":"Apellidos","type":"text","name":"apellidos"},{"label":"Email","type":"text","name":"email"},{"label":"Fecha de Nacimiento","type":"date","name":"fecha_nac"},{"label":"Genero","type":"select","options":["","Femenino","Masculino","Otro"],"name":"genero"},{"label":"Posición","type":"text","name":"pos"}],"col2":[{"label":"Direcci\u00f3n 1","name":"direccion1"},{"label":"Direcci\u00f3n 2","type":"text","name":"direccion2"},{"label":"Ciudad","type":"text","name":"ciudad"},{"label":"Zipcode","type":"text","name":"zipcode"},{"label":"Tel\u00e9fono 1","type":"tel","name":"tel1"},{"label":"Tel\u00e9fono 2","type":"tel","name":"tel2"}]}}'

+ 37
- 43
index.py Voir le fichier

@@ -1,58 +1,52 @@
1
-from flask import Flask, render_template, request, redirect, url_for
1
+from flask import Flask, render_template
2 2
 import json
3
-# import estudiante, madre, admin, enfermera, facultad
4
-import forma
3
+import estudiante, madre, admin, enfermera, facultad
5 4
 
6 5
 app = Flask(__name__)
7 6
 
8
-@app.route('/admin/', methods=['GET', 'POST'])
7
+@app.route('/', methods=['GET', 'POST'])
9 8
 def index():
10 9
 #     return "Hello, World!"
11 10
     return render_template('dashAdministracion.html')
12 11
 
13
-@app.route('/admin/procesaUser', methods=['GET', 'POST'])
14
-def procesaUser():
15
-	data = request.form
16
-	tipo_accion = getattr(__import__(data["tipo"]), data["accion"])
17
-	return tipo_accion(data)
18
-		
19
-@app.route('/admin/forma/<accion>/<tipo>/', methods=['GET', 'POST'])
20
-@app.route('/admin/forma/<accion>/<tipo>/<id>', methods=['GET', 'POST'])
12
+@app.route('/forma/<accion>/<tipo>/', methods=['GET', 'POST'])
13
+@app.route('/forma/<accion>/<tipo>/<id>', methods=['GET', 'POST'])
21 14
 def formas(accion,tipo,id=None):
22
-	return render_template('forma.html', tipo=tipo, accion=accion, id=id, user_type="admin")
15
+	return render_template('forma.html', tipo=tipo, accion=accion, id=id)
23 16
 
24 17
     
25
-@app.route('/admin/formaDatos/<accion>/<tipo>/', methods=['GET', 'POST'])
26
-@app.route('/admin/formaDatos/<accion>/<tipo>/<id>', methods=['GET', 'POST'])
18
+@app.route('/formaDatos/<accion>/<tipo>/', methods=['GET', 'POST'])
19
+@app.route('/formaDatos/<accion>/<tipo>/<id>', methods=['GET', 'POST'])
27 20
 def formaEst(accion, tipo, id=None):
28 21
 # 	data = json.loads('formaEstudiantes.json')
29
-	if tipo not in ["enfermera", "administracion", "estudiante", "madre", "facultad"]:
30
-		return {"error":True,"tipo":"tipo_incorrecto","opcion":tipo,"user_type":"admin"}
31
-	if accion not in ["edit", "add", "view"]:
32
-		return {"error":True,"tipo":"accion_incorrecta","opcion":accion,"user_type":"admin"}
33
-	if (accion=="add"):
34
-		return __import__(tipo).add_form()
35
-	if(accion=="edit"):
36
-		resultado=__import__(tipo).edit_form(id)
37
-		if resultado==False:
38
-			return {"error":True,"tipo":"usuario_incorrecto","opcion":tipo,"user_type":"admin"}
39
-		else:
40
-			return resultado
41
-	if(accion=="view"):
42
-		resultado=__import__(tipo).edit_form(id,disabled=True)
43
-		if resultado==False:
44
-			return {"error":True,"tipo":"usuario_incorrecto","opcion":tipo,"user_type":"admin"}
45
-		else:
46
-			return resultado
47
-
48
-@app.route('/admin/dashAdmin', methods=['GET', 'POST'])
22
+	if(tipo=="estudiante"):
23
+		if(accion=="add"):
24
+			return estudiante.add()
25
+		if(accion=="edit"):
26
+			return estudiante.edit(id)
27
+	if(tipo=="madre"):
28
+		if(accion=="add"):
29
+			return madre.add()
30
+		if(accion=="edit"):
31
+			return madre.edit(id)
32
+	if(tipo=="admin"):
33
+		if(accion=="add"):
34
+			return admin.add()
35
+		if(accion=="edit"):
36
+			return admin.edit(id)
37
+	if(tipo=="enfermera"):
38
+		if(accion=="add"):
39
+			return enfermera.add()
40
+		if(accion=="edit"):
41
+			return enfermera.edit(id)
42
+	if(tipo=="facultad"):
43
+		if(accion=="add"):
44
+			return facultad.add()
45
+		if(accion=="edit"):
46
+			return facultad.edit(id)
47
+
48
+
49
+@app.route('/dashAdmin', methods=['GET', 'POST'])
49 50
 def dashAdmin():
50 51
 # 	data = json.loads('formaEstudiantes.json')
51
-	return '{"tasks": [ { "titulo": "Estudiantes", "url": "admin/estudiantes.html" }, { "titulo": "Facultad", "url": "admin/facultad.html" }, { "titulo": "Administración", "url": "admin/adminstracion.html" }, { "titulo": "Enfermeria", "url": "admin/enfermeria.html" }, { "titulo": "Madres", "url": "admin/madres.html" }, { "titulo": "Cursos", "url": "admin/cursos.html" }, { "titulo": "Matricula", "url": "admin/matricula.html" }, { "titulo": "Transcripción", "url": "admin/transcripcion.html" }, { "titulo": "Oferta", "url": "admin/oferta.html" }, { "titulo": "Visita Oficina", "url": "admin/oficina.html" }, { "titulo": "Mensajes", "url": "admin/mensajes.html" } ], "titulo": "Administración"}'
52
-
53
-
54
-@app.route('/admin/error/<tipo>', methods=['GET', 'POST'])
55
-def maneja_error_user(tipo):
56
-	return render_template('error.html',tipo=tipo)
57
-
58
-# print(formaEst("edit","estudiante",3))
52
+	return '{"tasks": [    {      "titulo": "Estudiantes",      "url": "admin/estudiantes.html"    }, {      "titulo": "Facultad",      "url": "admin/facultad.html"    },     {      "titulo": "Administración",      "url": "admin/adminstracion.html"    },     {      "titulo": "Enfermeria",      "url": "admin/enfermeria.html"    },     {      "titulo": "Madres",      "url": "admin/madres.html"    },     {      "titulo": "Cursos",      "url": "admin/cursos.html"    },     {      "titulo": "Matricula",      "url": "admin/matricula.html"    },     {      "titulo": "Transcripción",      "url": "admin/transcripcion.html"    },     {      "titulo": "Oferta",      "url": "admin/oferta.html"    },     {      "titulo": "Visita Oficina",      "url": "admin/oficina.html"    },     {      "titulo": "Mensajes",      "url": "admin/mensajes.html"    }  ], "titulo": "Administración"}'

+ 4
- 112
madre.py Voir le fichier

@@ -1,113 +1,5 @@
1
-from connect import connection, engine, metadata
2
-import sqlalchemy as db
3
-from flask import jsonify, redirect, url_for, render_template
4
-import json
5
-# import index.py 
6
-from funciones import valida_fecha
1
+def add():
2
+	return '{"titulo":"Madre","accion":"A\u00f1adir","entradas":{"col1":[{"label":"Nombres","type":"text","name":"nombres"},{"label":"Apellidos","type":"text","name":"apellidos"},{"label":"Email","type":"text","name":"email"},{"label":"Fecha de Nacimiento","type":"date","name":"fecha_nac"},{"label":"Genero","type":"select","options":["","Femenino","Masculino","Otro"],"name":"genero"},{"label":"Tel\u00e9fono 2","type":"tel","name":"tel2"}],"col2":[{"label":"Direcci\u00f3n 1","name":"direccion1"},{"label":"Direcci\u00f3n 2","type":"text","name":"direccion2"},{"label":"Ciudad","type":"text","name":"ciudad"},{"label":"Zipcode","type":"text","name":"zipcode"},{"label":"Tel\u00e9fono 1","type":"tel","name":"tel1"}]}}'
7 3
 
8
-col1=[{"label":"Nombres","type":"text","name":"nombres","require":"1"},{"label":"Apellidos","type":"text","name":"apellidos","require":"1"},{"label":"Email","type":"email","name":"email","require":"1"},{"label":"Fecha de Nacimiento","type":"date","name":"fecha_nacimiento","require":"1"},{"label":"Genero","type":"select","options":[{"id":"0","label":"Femenino"},{"id":"1","label":"Masculino"},{"id":"2","label":"Otro"}],"name":"genero","require":True},{"label":"Otro","type":"text","name":"otro1","require":False},{"label":"Otro","type":"text","name":"otro2","require":False}]
9
-col2=[{"label":"Dirección 1","type":"text","name":"direccion1","require":"1"},{"label":"Dirección 2","type":"text","name":"direccion2","require":False},{"label":"Ciudad","type":"text","name":"ciudad","require":"1"},{"label":"Pais","type":"text","name":"pais","require":"1"},{"label":"Zipcode","type":"text","name":"zipcode","require":"1"},{"label":"Teléfono 1","type":"tel","name":"telefono1","require":"1"},{"label":"Teléfono 2","type":"tel","name":"telefono2","require":False}]
10
-form_order= {"entradas":{"col1":col1,"col2":col2}}
11
-usuarios_col=["nombres", "apellidos", "email", "fecha_nacimiento", "genero", "direccion1", "direccion2", "ciudad", "pais", "zipcode", "telefono1", "telefono2"]
12
-madre_col=["otro1","otro2"]
13
-
14
-def prepara_values_usuario(data):
15
-	values_list={}
16
-	for item in usuarios_col:
17
-		if item=="fecha_nacimiento":
18
-			values_list.update({item:valida_fecha(data[item])})			
19
-		else:
20
-			values_list.update({item:data[item]})
21
-	return values_list
22
-
23
-def prepara_values_madre(data):
24
-	values_list={}
25
-	for item in madre_col:
26
-		if item=="educacion_especial" and ("educacion_especial" not in data or data[item]=="0"):
27
-			values_list.update({item:0})
28
-		else:
29
-			values_list.update({item:data[item]})
30
-	return values_list
31
-	
32
-def edit(data):
33
-	usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
34
-	values_list=prepara_values_usuario(data)
35
-	query = db.update(usuarios).values(values_list)
36
-	query = query.where(usuarios.columns.id == data['id'])
37
-	ResultProxy = connection.execute(query,values_list)
38
-
39
-	madre = db.Table('madres', metadata, autoload=True, autoload_with=engine)
40
-	values_list=prepara_values_madre(data)
41
-	query = db.update(madre).values(values_list)
42
-	query = query.where(madre.columns.user_id == data['id'])
43
-	ResultProxy = connection.execute(query,values_list)
44
-	return redirect(url_for("formas",accion="edit", tipo="madre", id=data['id']))
45
-
46
-def add(data):
47
-	usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
48
-	values_list=prepara_values_usuario(data)
49
-	query = db.insert(usuarios).values(values_list)
50
-	ResultProxy = connection.execute(query,values_list)
51
-	inst_id=ResultProxy.lastrowid
52
-
53
-	madre = db.Table('madres', metadata, autoload=True, autoload_with=engine)
54
-	values_list=prepara_values_madre(data)
55
-	values_list.update({"user_id":inst_id})
56
-	query = db.insert(madre).values(values_list)
57
-	ResultProxy = connection.execute(query,values_list)
58
-	return redirect(url_for("formas",accion="edit", tipo="madre", id=inst_id))
59
-
60
-
61
-def add_form():
62
-	i=1
63
-	orden=1
64
-	entradas={}
65
-	for col in form_order["entradas"]:
66
-		col_data=[]
67
-		for item in form_order["entradas"][col]:
68
-			item.update({"tabindex":orden})
69
-			item.update({"disabled":False})
70
-			orden+=1
71
-		entradas.update({"col"+str(i):col_data})
72
-		i+=1
73
-	data= {"titulo":"Madre","accion":"Añadir"}
74
-	data.update(form_order)
75
-	data.update({"abled":True})
76
-	return jsonify(data)
77
-	
78
-def edit_form(id, disabled=False):
79
-	madre = db.Table('madres', metadata, autoload=True, autoload_with=engine)
80
-	usuarios = db.Table('usuarios', metadata, autoload=True, autoload_with=engine)
81
-	query = db.select([usuarios, madre.columns.otro1, madre.columns.otro2])
82
-	query = query.select_from(usuarios.join(madre, usuarios.columns.id == madre.columns.user_id)).where(madre.columns.user_id == id)
83
-	result = connection.execute(query).fetchall()
84
-	if not len(result):
85
-		return False
86
-	for row in result:
87
-		row_as_dict = dict(row)
88
-	i=1
89
-	orden=1
90
-	entradas={}
91
-	for col in form_order["entradas"]:
92
-		col_data=[]
93
-		for item in form_order["entradas"][col]:
94
-			if item["type"]=="select":
95
-				item.update({"value":{"id":row_as_dict[item["name"]]}})
96
-			elif item["type"]=="checkbox":
97
-				item.update({"value":int(row_as_dict[item["name"]])})
98
-			else:
99
-				item.update({"value":str(row_as_dict[item["name"]])})
100
-			item.update({"tabindex":orden})
101
-			item.update({"disabled":disabled})
102
-			col_data.append(item)
103
-			orden+=1
104
-		entradas.update({"col"+str(i):col_data})
105
-		i+=1
106
-	data= {"titulo":"Madre","accion":"Editar"}
107
-	data.update({"entradas":entradas})
108
-	abled=True
109
-	if disabled:
110
-		abled=False
111
-	data.update({"abled":abled})
112
-	return jsonify(data)
113
-	
4
+def edit(id):
5
+	return '{"titulo":"Madre","accion":"Editar","entradas":{"col1":[{"label":"Nombres","type":"text","name":"nombres"},{"label":"Apellidos","type":"text","name":"apellidos"},{"label":"Email","type":"text","name":"email"},{"label":"Fecha de Nacimiento","type":"date","name":"fecha_nac"},{"label":"Genero","type":"select","options":["","Femenino","Masculino","Otro"],"name":"genero"},{"label":"Tel\u00e9fono 2","type":"tel","name":"tel2"}],"col2":[{"label":"Direcci\u00f3n 1","name":"direccion1"},{"label":"Direcci\u00f3n 2","type":"text","name":"direccion2"},{"label":"Ciudad","type":"text","name":"ciudad"},{"label":"Zipcode","type":"text","name":"zipcode"},{"label":"Tel\u00e9fono 1","type":"tel","name":"tel1"}]}}'

+ 92
- 0
registro-run.py Voir le fichier

@@ -0,0 +1,92 @@
1
+from flask import Flask, render_template, jsonify, session, request
2
+from flask import escape, redirect
3
+import json, os
4
+import estudiante, madre, admin, enfermera, facultad, curso
5
+from authlib import *
6
+
7
+app = Flask(__name__)
8
+
9
+@app.route('/', methods=['GET', 'POST'])
10
+def index():
11
+#     return "Hello, World!"
12
+    print(session)
13
+    auth = Auth(session)
14
+    if not auth.checkAuth():
15
+        return render_template("login.html")
16
+
17
+    print(session["gallitosccom"],session["id"], session["email"])
18
+    print("Enfermera", auth.checkRole("enfermera"))
19
+    print("Estudiante", auth.checkRole("estudiante"))
20
+    print("Admin", auth.checkRole("admin"))
21
+    print("Facultad", auth.checkRole("facultad"))
22
+    print("Madre", auth.checkRole("madre"))
23
+    print(session)
24
+    return render_template("listuser.html", tipo="enfermera", admin=1)
25
+
26
+@app.route('/login', methods=['POST'])
27
+def do_login():
28
+    auth = Auth(session)
29
+
30
+    if not (request.form['password'] and request.form["username"]):
31
+        return render_template('login.html')
32
+
33
+    username = "%s" % escape(request.form["username"])
34
+    password = escape(request.form["password"])
35
+    #
36
+    if auth.do_login(username, password):
37
+        # Mandar al dashboard
38
+        return redirect("/")
39
+
40
+    # Algo esta mal Mandar al login.
41
+    return render_template('login.html')
42
+
43
+@app.route("/logout")
44
+def logout():
45
+    Auth(session).do_logout()
46
+    return render_template('login.html')
47
+
48
+@app.route('/view/list/<tipo>/', methods=['GET', 'POST'])
49
+def viewlist(tipo):
50
+    if tipo == "curso":
51
+        return render_template("formacurso.html")
52
+
53
+    return render_template("listuser.html", tipo=tipo, admin=1)
54
+
55
+@app.route('/list/<tipo>/', methods=['GET', 'POST'])
56
+def list(tipo):
57
+    if tipo in ["enfermera", "admin", "estudiante", "madre", "facultad", "curso"]:
58
+        return jsonify(globals()[tipo].list())
59
+
60
+
61
+@app.route('/forma/<accion>/<tipo>/', methods=['GET', 'POST'])
62
+@app.route('/forma/<accion>/<tipo>/<id>', methods=['GET', 'POST'])
63
+def formas(accion,tipo,id=None):
64
+
65
+    if not tipo in ["enfermera", "admin", "estudiante", "madre", "facultad"]:
66
+        return # Redirigirlo a una pagina de errorCallback
67
+    if not accion in ["edit", "add"]:
68
+        return # Redirigirlo a una pagina de errorCallback
69
+        return render_template('forma.html', tipo=tipo, accion=accion, id=id)
70
+
71
+
72
+@app.route('/formaDatos/<accion>/<tipo>/', methods=['GET', 'POST'])
73
+@app.route('/formaDatos/<accion>/<tipo>/<id>', methods=['GET', 'POST'])
74
+def formaEst(accion, tipo, id=None):
75
+# 	data = json.loads('formaEstudiantes.json')
76
+    #getattr(globals()["enfermera"], "list")()
77
+    if not tipo in ["enfermera", "admin", "estudiante", "madre", "facultad"]:
78
+        return # Redirigirlo a una pagina de errorCallback
79
+    if not accion in ["edit", "add"]:
80
+        return # Redirigirlo a una pagina de errorCallback
81
+
82
+    return jsonify(getattr(globals()[tipo], accion)())
83
+
84
+@app.route('/dashAdmin', methods=['GET', 'POST'])
85
+def dashAdmin():
86
+# 	data = json.loads('formaEstudiantes.json')
87
+	return {}
88
+
89
+app.secret_key = os.urandom(52)
90
+
91
+if __name__ == "__main__":
92
+	app.run(host='0.0.0.0', port=9000, debug=True)

+ 87
- 0
static/curso.js Voir le fichier

@@ -0,0 +1,87 @@
1
+var curso = angular.module('curso', []);
2
+
3
+// Define the `PhoneListController` controller on the `phonecatApp` module
4
+
5
+curso.directive('ngConfirmClick', [
6
+  function(){
7
+      return {
8
+          link: function (scope, element, attr) {
9
+              var msg = attr.ngConfirmClick || "Are you sure?";
10
+              var clickAction = attr.confirmedClick;
11
+              element.bind('click',function (event) {
12
+                  if ( window.confirm(msg) ) {
13
+                      scope.$eval(clickAction)
14
+                  }
15
+              });
16
+          }
17
+      };
18
+}])
19
+
20
+curso.controller('CursoController', function CursoController($http, $scope) {
21
+
22
+    $scope.cursos = [] ;
23
+    $scope.operacion = "Añadir" ;
24
+
25
+    $scope.getCursos = function(){
26
+
27
+      $http({
28
+        method: 'GET',
29
+        url: '/list/curso'
30
+      }).then(function successCallback(response) {
31
+        // this callback will be called asynchronously
32
+        // when the response is available
33
+        console.log(response.data)
34
+
35
+        $scope.cursos = response.data;
36
+      }, function errorCallback(response) {
37
+        // called asynchronously if an error occurs
38
+        // or server returns response with an error status.
39
+      });
40
+    }
41
+
42
+    $scope.getCursos() ;
43
+
44
+    $scope.submitForm = function() {
45
+
46
+      path = "" ;
47
+      if($scope.operacion == "Actualizar"){
48
+        path = "/updatecourse" ;
49
+      }
50
+      else{
51
+        path = "/addcourse" ;
52
+      }
53
+      $http.post(path, $scope.curso).success(function(data, status,header, config){
54
+        $scope.getCursos() ;
55
+        alert(data.response.msg);
56
+      }) ;
57
+    }
58
+
59
+    $scope.edit =function(curso){
60
+      $scope.curso = curso ;
61
+      $scope.operacion = "Actualizar" ;
62
+    }
63
+    $scope.anadir = function(){
64
+      $scope.operacion='Añadir';
65
+      $scope.curso={} ;
66
+    }
67
+/*
68
+    $scope.drop=function(course_academicsesion_id){
69
+      $http({
70
+        method: 'GET',
71
+        url: '/drop?course_academicsesion_id='+course_academicsesion_id
72
+      //  data: $.param({"codigo" : $scope.selectedProgram})
73
+      }).then(function successCallback(response) {
74
+        // this callback will be called asynchronously
75
+        // when the response is available
76
+        if(response.data.response.error == false){
77
+            $scope.getAllCoursesInSesion() ;
78
+        }
79
+        alert(response.data.response.msg);
80
+      }, function errorCallback(response) {
81
+        // called asynchronously if an error occurs
82
+        // or server returns response with an error status.
83
+      });
84
+    }
85
+*/
86
+
87
+});

+ 63
- 0
static/list.js Voir le fichier

@@ -0,0 +1,63 @@
1
+var list = angular.module('list', []);
2
+
3
+// Define the `PhoneListController` controller on the `phonecatApp` module
4
+
5
+list.directive('ngConfirmClick', [
6
+  function(){
7
+      return {
8
+          link: function (scope, element, attr) {
9
+              var msg = attr.ngConfirmClick || "Are you sure?";
10
+              var clickAction = attr.confirmedClick;
11
+              element.bind('click',function (event) {
12
+                  if ( window.confirm(msg) ) {
13
+                      scope.$eval(clickAction)
14
+                  }
15
+              });
16
+          }
17
+      };
18
+}])
19
+
20
+list.controller('ListController', function ListController($http, $scope,tipo) {
21
+  	console.log(tipo);
22
+
23
+    $scope.list = [] ;
24
+
25
+    $scope.getList = function(){
26
+
27
+      $http({
28
+        method: 'GET',
29
+        url: '/list/' + tipo
30
+      }).then(function successCallback(response) {
31
+        // this callback will be called asynchronously
32
+        // when the response is available
33
+        console.log(response.data)
34
+
35
+        $scope.list = response.data;
36
+      }, function errorCallback(response) {
37
+        // called asynchronously if an error occurs
38
+        // or server returns response with an error status.
39
+      });
40
+    }
41
+
42
+    $scope.getList() ;
43
+/*
44
+    $scope.drop=function(course_academicsesion_id){
45
+      $http({
46
+        method: 'GET',
47
+        url: '/drop?course_academicsesion_id='+course_academicsesion_id
48
+      //  data: $.param({"codigo" : $scope.selectedProgram})
49
+      }).then(function successCallback(response) {
50
+        // this callback will be called asynchronously
51
+        // when the response is available
52
+        if(response.data.response.error == false){
53
+            $scope.getAllCoursesInSesion() ;
54
+        }
55
+        alert(response.data.response.msg);
56
+      }, function errorCallback(response) {
57
+        // called asynchronously if an error occurs
58
+        // or server returns response with an error status.
59
+      });
60
+    }
61
+*/
62
+
63
+});

+ 107
- 0
templates/formacurso.html Voir le fichier

@@ -0,0 +1,107 @@
1
+<!DOCTYPE html>
2
+<html lang="en-US">
3
+<head>
4
+  <meta charset="utf-8">
5
+  <meta name="viewport" content="width=device-width, initial-scale=1">
6
+  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
7
+  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
8
+
9
+  <style>
10
+    .alt {
11
+  	   background-color:#ccc;
12
+    }
13
+    .d-flex {
14
+      display: -ms-flexbox!important;
15
+      display: flex!important;
16
+    }
17
+    .align-items-center {
18
+      -ms-flex-align: center!important;
19
+      align-items: center!important;
20
+    }
21
+  </style>
22
+
23
+  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
24
+  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
25
+  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
26
+  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
27
+  <script src="{{ url_for('static', filename='curso.js') }}"></script>
28
+
29
+</head>
30
+
31
+<body>
32
+
33
+{% raw %}
34
+<div ng-app="curso" ng-controller="CursoController">
35
+  <div class="container-fluid">
36
+    <form name="cursoForm" ng-submit="submitForm()">
37
+    <div class="row">
38
+      <div class="col-sm-12">
39
+        <input type="hidden" ng-model="curso.codigo">
40
+        <div class="form-group">
41
+          <label for="codigo">Código del curso:</label>
42
+          <input type="text" ng-model="curso.codigo" class="form-control" placeholder="CCOM" required>
43
+        </div>
44
+        <div class="form-group">
45
+          <label for="codigo">Título del curso:</label>
46
+          <input type="text" ng-model="curso.titulo" class="form-control" placeholder="Introduccion a ..." required>
47
+        </div>
48
+        <div class="form-group">
49
+          <label for="codigo">Grado:</label>
50
+          <input type="text" ng-model="curso.grado" class="form-control" placeholder="K" required>
51
+        </div>
52
+        <div class="form-group">
53
+          <label for="codigo">Descripción:</label>
54
+          <input type="text" ng-model="curso.descripcion" class="form-control" placeholder="El departamento blah">
55
+        </div>
56
+        <button type="submit" class="btn btn-danger btn-md">
57
+          <i class="fa fa-plus"></i> {{operacion}}
58
+        </button>
59
+      </div>
60
+    </div>
61
+    </form>
62
+  </div>
63
+
64
+  <div class="container-fluid">
65
+    <div class="row">
66
+      <div class="col-sm-10">
67
+        <h2>Cursos</h2>
68
+      </div>
69
+      <div class="col-sm-2 align-self-center">
70
+        <button type="button" class="btn btn-danger btn-md" ng-click="anadir()">
71
+          <i class="fa fa-plus"></i> Añadir Curso
72
+        </button>
73
+      </div>
74
+    </div>
75
+    <div class="row" ng-repeat="curso in cursos" ng-class-odd="'alt'">
76
+      <div class="col-sm-10 align-self-center">
77
+        <div class="row">
78
+          <div class="col-sm-1">Codigo:</div><div class="col-sm-11">{{curso.codigo}}</div>
79
+        </div>
80
+        <div class="row">
81
+          <div class="col-sm-1">Titulo:</div><div class="col-sm-11">{{curso.titulo}}</div>
82
+        </div>
83
+        <div class="row">
84
+          <div class="col-sm-1">Grado:</div><div class="col-sm-11">{{curso.grado}}</div>
85
+        </div>
86
+        <div class="row">
87
+          <div class="col-sm-1">Descripción:</div><div class="col-sm-11"> {{curso.descripcion}}</div>
88
+        </div>
89
+      </div>
90
+      <div class="col-sm-1 align-self-center">
91
+        <a href="#" role="button" class="btn btn-danger btn-sm" ng-click="edit(curso)">
92
+          <i class="fa fa-edit"></i> Editar
93
+        </a>
94
+      </div>
95
+      <div class="col-sm-1 align-self-center">
96
+        <button type="button" class="btn btn-danger btn-sm" ng-confirm-click="Are you sure to delete this course?" confirmed-click="delCourse(curso.id)">
97
+          <i class="fa fa-trash"></i> Borrar
98
+        </button>
99
+      </div>
100
+    </div>
101
+  </div>
102
+
103
+</div>
104
+{% endraw %}
105
+
106
+</body>
107
+</html>

+ 79
- 0
templates/listuser.html Voir le fichier

@@ -0,0 +1,79 @@
1
+<!DOCTYPE html>
2
+<html lang="en-US">
3
+<head>
4
+  <meta charset="utf-8">
5
+  <meta name="viewport" content="width=device-width, initial-scale=1">
6
+  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
7
+  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
8
+
9
+  <style>
10
+    .alt {
11
+  	   background-color:#ccc;
12
+    }
13
+    .d-flex {
14
+      display: -ms-flexbox!important;
15
+      display: flex!important;
16
+    }
17
+    .align-items-center {
18
+      -ms-flex-align: center!important;
19
+      align-items: center!important;
20
+    }
21
+  </style>
22
+
23
+  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
24
+  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
25
+  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
26
+  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
27
+  <script src="{{ url_for('static', filename='list.js') }}"></script>
28
+  <script>
29
+     list.value("tipo", "{{tipo}}");
30
+  </script>
31
+</head>
32
+
33
+<body>
34
+
35
+{% raw %}
36
+<div ng-app="list" ng-controller="ListController">
37
+  <div class="container-fluid">
38
+    <table>
39
+      <thead>
40
+        <th>
41
+          Nombre
42
+        </th>
43
+        <th>
44
+          email
45
+        </th>
46
+{% endraw %}
47
+        {% if admin %}
48
+        <th>
49
+          Actions
50
+        </th>
51
+        {% endif %}
52
+{% raw %}
53
+      </thead>
54
+      <tr ng-repeat="user in list" ng-class-odd="'alt'">
55
+        <td>
56
+          {{user.nombres}} {{user.apellidos}}
57
+        </td>
58
+        <td>
59
+          {{user.email}}
60
+        </td>
61
+{% endraw %}
62
+        {% if admin %}
63
+        <td>
64
+          <button type="button" class="btn btn-success btn-sm" ng-click="edit(id)">
65
+            <i class="fa fa-edit"></i> Edit
66
+          </button>
67
+          <button type="button" class="btn btn-danger btn-sm" ng-confirm-click="Are you sure to drop this course?" confirmed-click="drop(id)">
68
+            <i class="fa fa-trash"></i> Drop
69
+          </button>
70
+        </td>
71
+        {% endif %}
72
+{% raw %}
73
+      </tr>
74
+  </div>
75
+</div>
76
+{% endraw %}
77
+
78
+</body>
79
+</html>

+ 14
- 0
templates/login.html Voir le fichier

@@ -0,0 +1,14 @@
1
+{% block body %}
2
+{% if session['esgallito'] %}
3
+
4
+You're logged in already!
5
+
6
+{% else %}
7
+<form action="/login" method="POST">
8
+  <input type="username" name="username" placeholder="Username">
9
+<input type="password" name="password" placeholder="Password">
10
+<input type="submit" value="Log in">
11
+</form>
12
+
13
+{% endif %}
14
+{% endblock %}