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 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 # Proximas instancias de entrega
52 instancias = list(InstanciaDeEntrega.select(
53 AND(InstanciaDeEntrega.q.inicio <= now,
54 InstanciaDeEntrega.q.fin > now)).orderBy(InstanciaDeEntrega.q.fin))
55 # Ultimas N entregas realizadas
56 # Grupos en los que el usuario formo parte
57 m = [i.grupo.id for i in Grupo.selectByAlumno(identity.current.user)]
59 entregador = AlumnoInscripto.selectByAlumno(identity.current.user)
60 m.append(entregador.id)
63 entregas = list(Entrega.select(IN(Entrega.q.entregadorID, m))[:5])
64 return dict(instancias_activas=instancias, now=now, entregas=entregas)
67 @expose(template='.templates.login')
68 def login(self, forward_url=None, previous_url=None, tg_errors=None, *args,
72 flash(_(u'Hubo un error en el formulario!'))
74 if not identity.current.anonymous \
75 and identity.was_login_attempted() \
76 and not identity.get_identity_errors():
77 raise redirect(forward_url)
80 previous_url = request.path
82 if identity.was_login_attempted():
83 msg = _(u'Las credenciales proporcionadas no son correctas o no '
84 'le dan acceso al recurso solicitado.')
85 elif identity.get_identity_errors():
86 msg = _(u'Debe proveer sus credenciales antes de acceder a este '
89 msg = _(u'Por favor ingrese.')
90 forward_url = request.headers.get('Referer', '/')
92 fields = list(LoginForm.fields)
94 fields.append(W.HiddenField(name='forward_url'))
95 fields.extend([W.HiddenField(name=name) for name in request.params
96 if name not in ('login_user', 'login_password', 'login_submit',
98 login_form = LoginForm(fields=fields, action=previous_url)
100 values = dict(forward_url=forward_url)
101 values.update(request.params)
104 return dict(login_form=login_form, form_data=values, message=msg,
109 identity.current.logout()
110 raise redirect(url('/'))
112 docente = DocenteController()
114 grupo = GrupoController()
116 alumno = AlumnoController()
118 enunciado = EnunciadoController()
120 ejercicio = EjercicioController()
122 tarea_fuente = TareaFuenteController()
124 tarea_prueba = TareaPruebaController()
126 curso = CursoController()
128 docente_inscripto = DocenteInscriptoController()
130 correccion = CorreccionController()
132 admin = identity.SecureObject(CatWalk(model), identity.has_permission('admin'))
134 mis_entregas = MisEntregasController()
136 mis_correcciones = MisCorreccionesController()
138 grupo_admin = GrupoAdminController()
140 #{{{ Agrega summarize a namespace tg de KID
141 def summarize(text, size, concat=True, continuation='...'):
142 """Summarize a string if it's length is greater than a specified size. This
143 is useful for table listings where you don't want the table to grow because
146 >>> from sercome.controllers
147 >>> text = '''Why is it that nobody remembers the name of Johann
148 ... Gambolputty de von Ausfern-schplenden-schlitter-crasscrenbon-fried-
149 ... digger-dingle-dangle-dongle-dungle-burstein-von-knacker-thrasher-apple-
150 ... banger-horowitz-ticolensic-grander-knotty-spelltinkle-grandlich-
151 ... grumblemeyer-spelterwasser-kurstlich-himbleeisen-bahnwagen-gutenabend-
152 ... bitte-ein-nurnburger-bratwustle-gernspurten-mitz-weimache-luber-
153 ... hundsfut-gumberaber-shonedanker-kalbsfleisch-mittler-aucher von
154 ... Hautkopft of Ulm?'''
155 >>> summarize(text, 30)
156 'Why is it that nobody remem...'
157 >>> summarize(text, 68, False, ' [...]')
158 'Why is it that nobody remembers the name of Johann\nGambolputty [...]'
159 >>> summarize(text, 68, continuation=' >>')
160 'Why is it that nobody remembers the name of Johann Gambolputty de >>'
164 text = text.replace('\n', ' ')
166 text = text[:size-len(continuation)] + continuation
174 def add_custom_stdvars(vars):
175 return vars.update(dict(summarize=summarize, strbool=strbool))
177 view.variable_providers.append(add_custom_stdvars)