1 # vim: set et sw=4 sts=4 encoding=utf-8 foldmethod=marker :
3 from turbogears import controllers, expose, view, url
4 from turbogears import widgets as W, validators as V
5 from turbogears import identity, redirect
6 from cherrypy import request, response
7 from turbogears.toolbox.catwalk import CatWalk
9 from model import Visita, VisitaUsuario, InstanciaDeEntrega, Correccion, AND, DateTimeCol, Entrega, Grupo, AlumnoInscripto
10 from sqlobject import *
11 # from sercom import json
13 from subcontrollers import *
16 log = logging.getLogger("sercom.controllers")
18 class LoginForm(W.TableForm):
19 class Fields(W.WidgetsList):
20 login_user = W.TextField(label=_(u'Usuario'),
21 validator=V.NotEmpty())
22 login_password = W.PasswordField(label=_(u'Contraseña'),
23 validator=V.NotEmpty())
25 javascript = [W.JSSource("MochiKit.DOM.focusOnLoad('form_login_user');")]
26 submit = W.SubmitButton(name='login_submit')
27 submit_text = _(u'Ingresar')
29 class Root(controllers.RootController):
33 raise redirect(url('/dashboard'))
35 @expose(template='.templates.welcome')
36 @identity.require(identity.not_anonymous())
38 now = DateTimeCol.now()
39 if 'admin' in identity.current.permissions:
40 # TODO : Fijar el curso !!
41 correcciones = Correccion.selectBy(corrector=identity.current.user,
42 corregido=None).count()
43 instancias = list(InstanciaDeEntrega.select(
44 AND(InstanciaDeEntrega.q.inicio <= now,
45 InstanciaDeEntrega.q.fin > now))
46 .orderBy(InstanciaDeEntrega.q.fin))
47 return dict(a_corregir=correcciones,
48 instancias_activas=instancias, now=now)
50 if 'entregar' in identity.current.permissions:
51 last_login = Visita.select(AND(VisitaUsuario.q.user_id == identity.current.user.id, Visita.q.visit_key == VisitaUsuario.q.visit_key))[-1:][0].created
52 # Proximas instancias de entrega
53 instancias = list(InstanciaDeEntrega.select(
54 AND(InstanciaDeEntrega.q.inicio <= now,
55 InstanciaDeEntrega.q.fin > now)).orderBy(InstanciaDeEntrega.q.fin))
56 # Ultimas N entregas realizadas
57 # Grupos en los que el usuario formo parte
58 m = [i.grupo.id for i in Grupo.selectByAlumno(identity.current.user)]
60 entregador = AlumnoInscripto.selectByAlumno(identity.current.user)
61 m.append(entregador.id)
64 entregas = list(Entrega.select(IN(Entrega.q.entregadorID, m))[:5])
66 # Ultimas correcciones
67 correcciones = list(Correccion.select(AND(IN(Correccion.q.entregadorID, m), Correccion.q.corregido >= last_login)))
68 return dict(instancias_activas=instancias, now=now, entregas=entregas, correcciones=correcciones)
71 @expose(template='.templates.login')
72 def login(self, forward_url=None, previous_url=None, tg_errors=None, *args,
76 flash(_(u'Hubo un error en el formulario!'))
78 if not identity.current.anonymous \
79 and identity.was_login_attempted() \
80 and not identity.get_identity_errors():
81 raise redirect(forward_url)
84 previous_url = request.path
86 if identity.was_login_attempted():
87 msg = _(u'Las credenciales proporcionadas no son correctas o no '
88 'le dan acceso al recurso solicitado.')
89 elif identity.get_identity_errors():
90 msg = _(u'Debe proveer sus credenciales antes de acceder a este '
93 msg = _(u'Por favor ingrese.')
94 forward_url = request.headers.get('Referer', '/')
96 fields = list(LoginForm.fields)
98 fields.append(W.HiddenField(name='forward_url'))
99 fields.extend([W.HiddenField(name=name) for name in request.params
100 if name not in ('login_user', 'login_password', 'login_submit',
102 login_form = LoginForm(fields=fields, action=previous_url)
104 values = dict(forward_url=forward_url)
105 values.update(request.params)
108 return dict(login_form=login_form, form_data=values, message=msg,
113 identity.current.logout()
114 raise redirect(url('/'))
116 docente = DocenteController()
118 alumno = AlumnoController()
120 enunciado = EnunciadoController()
122 tarea_fuente = TareaFuenteController()
124 tarea_prueba = TareaPruebaController()
126 curso = CursoController()
128 correccion = CorreccionController()
130 admin = identity.SecureObject(CatWalk(model), identity.has_permission('admin'))
132 mis_entregas = MisEntregasController()
134 mis_correcciones = MisCorreccionesController()
136 #{{{ Agrega summarize a namespace tg de KID
137 def summarize(text, size, concat=True, continuation='...'):
138 """Summarize a string if it's length is greater than a specified size. This
139 is useful for table listings where you don't want the table to grow because
142 >>> from sercome.controllers
143 >>> text = '''Why is it that nobody remembers the name of Johann
144 ... Gambolputty de von Ausfern-schplenden-schlitter-crasscrenbon-fried-
145 ... digger-dingle-dangle-dongle-dungle-burstein-von-knacker-thrasher-apple-
146 ... banger-horowitz-ticolensic-grander-knotty-spelltinkle-grandlich-
147 ... grumblemeyer-spelterwasser-kurstlich-himbleeisen-bahnwagen-gutenabend-
148 ... bitte-ein-nurnburger-bratwustle-gernspurten-mitz-weimache-luber-
149 ... hundsfut-gumberaber-shonedanker-kalbsfleisch-mittler-aucher von
150 ... Hautkopft of Ulm?'''
151 >>> summarize(text, 30)
152 'Why is it that nobody remem...'
153 >>> summarize(text, 68, False, ' [...]')
154 'Why is it that nobody remembers the name of Johann\nGambolputty [...]'
155 >>> summarize(text, 68, continuation=' >>')
156 'Why is it that nobody remembers the name of Johann\nGambolputty de >>'
160 text = text.replace('\n', ' ')
162 text = text[:size-len(continuation)] + continuation
170 def add_custom_stdvars(vars):
171 return vars.update(dict(summarize=summarize, strbool=strbool))
173 view.variable_providers.append(add_custom_stdvars)