Argh! Python identation, retab in vim... damn it!
[cascardo/eventmanager.git] / views.py
1 # -*- coding: utf-8; -*-
2 """
3 Copyright (C) 2007 Lincoln de Sousa <lincoln@archlinux-br.org>
4
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public
16 License along with this program; if not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 """
20 from django.shortcuts import render_to_response, get_object_or_404
21 from django.template import RequestContext, Context, loader
22 from django.contrib.auth.decorators import login_required, user_passes_test
23 from django.contrib.auth.models import Group, User
24 from django.contrib.auth import authenticate, login
25 from django.contrib.admin.views.decorators import staff_member_required
26 from django.newforms import form_for_instance
27 from django.core.exceptions import ObjectDoesNotExist
28 from django.core.mail import EmailMessage
29 from django.db import transaction
30 from django.http import get_host
31 from django.conf import settings
32
33 from eventmanager.decorators import enable_login_form
34 from eventmanager.conteudo.models import Noticia, Menu, Secao
35 from eventmanager.eventos.models import *
36 from eventmanager.forms import *
37 from eventmanager.controllers import *
38
39 from datetime import datetime
40 import sha
41
42 FROM_EMAIL = 'Emsl 2007 <noreply@minaslivre.org>'
43
44 def build_response(request, template, extra={}):
45     """
46     Shortcut to build a response based on a C{template} and build a standard
47     context to this template. This context contains news itens, a list of menus
48     and a list of sections to be shown on index. But don't worry, this context
49     is extensible through the C{extra} parameter.
50
51     @param template: Contains the name of a template found in django
52      C{TEMPLATE_DIRS}
53     @type template: C{str}
54
55     @param extra: Extra variables to be passed to the context being built.
56     @type extra: C{dict}
57     """
58     news = Noticia.objects.order_by('-data_criacao')
59     menus = Menu.objects.all()
60     index_sections = Secao.objects.filter(index=True)
61     login_failed = 'login_failed' in request.GET
62     c = {'news': news, 'menu': menus,
63         'index_sections': index_sections,
64         'login_failed': login_failed}
65     c.update(extra)
66     return render_to_response(template, Context(c),
67             context_instance=RequestContext(request))
68
69
70 @enable_login_form
71 def index(request):
72     return build_response(request, 'index.html')
73
74
75 @transaction.commit_manually
76 @enable_login_form
77 def cadastro_palestrante(request):
78     form = CadastroPalestrante(request.POST or None)
79     ok = False
80     c = {'form': form}
81     if request.POST and form.is_valid():
82         cd = form.cleaned_data
83         badattr = form.errors
84
85         group = Group.objects.get_or_create(name='palestrantes')[0]
86
87         user = User(username=cd['nome_usuario'], email=cd['email'])
88         user.set_password(cd['senha'])
89         user.is_active = False
90         user.save()
91         user.groups.add(group)
92
93         p = Palestrante()
94         p.usuario = user
95
96         p.nome = cd['nome_completo']
97         p.email = cd['email']
98         p.telefone = cd['telefone']
99         p.celular = cd['celular']
100         p.instituicao = cd['instituicao']
101         p.rua = cd['rua']
102         p.numero = cd['numero']
103         p.bairro = cd['bairro']
104         p.cidade = cd['cidade']
105         p.uf = cd['uf']
106         p.minicurriculo = cd['minicurriculo']
107         p.curriculo = cd['curriculo']
108         p.save()
109
110         for i in cd.get('area_interesse', []):
111             p.area_interesse.add(i)
112
113         pid = p.id
114         md5_email = sha.new(cd['email']).hexdigest()
115         email = '%s <%s>' % (cd['nome_completo'], cd['email'])
116         link = '%s/verificar?c=%s&c1=%s' % (get_host(request),
117                 pid, md5_email)
118         t = loader.get_template('email-palestrante.html')
119         ec = Context(dict(fulano=['nome_usuario'], link=link))
120
121         # to be shown in template...
122         c.update({'email': email})
123         try:
124             # XXX: maybe is not a good so prety put things hardcoded =(
125             m = EmailMessage('Encontro Mineiro de Software Livre',
126                 t.render(ec), FROM_EMAIL, [email])
127             m.send()
128         except Exception:
129             badattr['email'] = \
130                 ['Desculpe mas não pude enviar o email de confirmação']
131             transaction.rollback()
132         else:
133             ok = True
134             c.update({'ok': ok})
135             transaction.commit()
136
137     return build_response(request, 'cadastro.html', c)
138
139
140 @enable_login_form
141 def inscricao(request):
142     return build_response(request, 'inscricao.html')
143
144
145 @enable_login_form
146 @transaction.commit_manually
147 def inscricao_individual(request):
148     form = Inscricao(request.POST or None)
149     ok = False
150     if request.POST and form.is_valid():
151         cd = form.cleaned_data
152         group = Group.objects.get_or_create(name='participantes')[0]
153
154         user = User(username=cd['nome_usuario'], email=cd['email'])
155         user.set_password(cd['senha'])
156         user.is_active = False
157         user.save()
158         user.groups.add(group)
159         p = Participante()
160         p.usuario = user
161         p.nome = cd['nome_completo']
162         p.rg = cd['rg']
163         p.email = cd['email']
164         p.rua = cd['rua']
165         p.numero = cd['numero']
166         p.bairro = cd['bairro']
167         p.cidade = cd['cidade']
168         p.uf = cd['uf']
169         p.cep = cd['cep']
170         p.refbanco = 0
171         p.telefone = cd['telefone']
172         p.home_page = cd['home_page']
173         p.comercial = cd['inscricao_comercial']
174         p.cpf_cnpj = cd['cpf_cnpj']
175         p.save()
176
177         u = authenticate(username=cd['nome_usuario'], password=cd['senha'])
178         login(request, u)
179         transaction.commit()
180         ok = True
181
182     c = {'form': form, 'ok': ok}
183     return build_response(request, 'inscricao_individual.html', c)
184
185
186 @enable_login_form
187 @transaction.commit_manually
188 def inscricao_caravana(request):
189     form = InscricaoCaravana(request.POST or None)
190     ok = False
191     if request.POST and form.is_valid():
192         cd = form.cleaned_data
193         group = Group.objects.get_or_create(name='participantes')[0]
194
195         user = User(username=cd['nome_usuario'], email=cd['email'])
196         user.set_password(cd['senha'])
197         user.is_active = False
198         user.save()
199         user.groups.add(group)
200
201         p = Participante()
202         p.usuario = user
203         p.nome = cd['nome_completo']
204         p.rg = cd['rg']
205         p.email = cd['email']
206         p.rua = cd['rua']
207         p.numero = cd['numero']
208         p.bairro = cd['bairro']
209         p.cidade = cd['cidade']
210         p.uf = cd['uf']
211         p.cep = cd['cep']
212         p.refbanco = 0
213         p.telefone = cd['telefone']
214         p.home_page = cd['home_page']
215         p.comercial = False # yeah, always false!
216         p.cpf_cnpj = ''
217         p.save()
218
219         c = Caravana()
220         c.coordenador = p
221         c.participantes = cd['lista_nomes']
222         c.save()
223
224         ok = True
225         u = authenticate(username=cd['nome_usuario'], password=cd['senha'])
226         login(request, u)
227         transaction.commit()
228
229     c = {'form': form, 'ok': ok}
230     return build_response(request, 'inscricao_caravana.html', c)
231
232
233 @enable_login_form
234 def inscricao_boleto(request):
235     # dynamic values of the form
236     now = datetime.now()
237     today = datetime.date(now)
238     first_date = datetime.date(datetime(2007, 10, 12))
239     c = {}
240
241     p = request.user.participante_set.get()
242     ca = p.caravana_set.all() and p.caravana_set.get()
243
244     initial = {}
245
246     if p.refbanco == 0:
247         # o número refTran deve ser gerado a cada novo boleto e deve ser único,
248         # mesmo para os testes
249         refs = [x.refbanco for x in Participante.objects.all()]
250         new_ref = len(refs)
251         while new_ref in refs or new_ref <= settings.MIN_REF_TRAN:
252             new_ref += 1
253
254         # este dado precisa ser persistente para que possa ser comparado logo acima
255         p.refbanco = new_ref
256         p.save()
257     else:
258         new_ref = p.refbanco
259
260     initial['refTran'] = '1458197%s' % str(new_ref).zfill(10)
261     if today < first_date:
262         initial['dtVenc'] = '12102007'
263         if not p.comercial:
264             initial['valor'] = '3500'
265         else:
266             initial['valor'] = '8000'
267
268         # caso seja uma caravana...
269         if ca and len(ca.parsed_participantes()) >= 10:
270             # sim, o valor aqui é 25 -- Desconto
271             initial['valor'] = '%s00' % (len(ca.parsed_participantes()) * 25)
272             c.update({'caravana': 1})
273     else:
274         initial['valor'] = '5000'
275         initial['dtVenc'] = '17102007'
276
277     initial['nome'] = p.nome
278     initial['endereco'] = '%s, %s - %s' % (p.rua, p.numero, p.bairro)
279     initial['cidade'] = p.cidade
280     initial['uf'] = p.uf
281     initial['cep'] = p.cep
282
283     form = Boleto(request.POST or None, initial=initial)
284     c.update({'form': form})
285     c.update(initial)
286     return build_response(request, 'inscricao_boleto.html', c)
287
288
289 @login_required
290 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
291 def submeter_trabalho(request):
292     form = SubmeterTrabalho(request, request.POST or None)
293     ok = False
294
295     if request.POST and form.is_valid():
296         cd = form.cleaned_data
297         t = Trabalho()
298         t.titulo = cd['titulo']
299         t.tipo = TipoTrabalho.objects.get(pk=cd['tipo'])
300         t.categoria = CategoriaTrabalho.objects.get_or_create(nome='Pendente')[0]
301         t.descricao_curta = cd['descricao_curta']
302         t.descricao_longa = cd['descricao_longa']
303         t.recursos = cd['recursos']
304         t.evento = Evento.objects.get(pk=1) # XXX: let the hammer play arround!
305         t.save()
306
307         logged_in = request.user.palestrante_set.get()
308         t.palestrante.add(logged_in)
309         for i in cd.get('outros_palestrantes', []):
310             up = Palestrante.objects.get(pk=int(i))
311             t.palestrante.add(up)
312         ok = True
313
314     c = {'form': form, 'ok': ok}
315     return build_response(request, 'inscrever_palestra.html', c)
316
317
318 @login_required
319 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
320 def meus_trabalhos(request):
321     try:
322         p = Palestrante.objects.get(usuario=request.user)
323     except Palestrante.DoesNotExist:
324         # não palestrante...
325         c = {'palestrante': 0}
326         return build_response(request, 'meus_trabalhos.html', c)
327     t = Trabalho.objects.filter(palestrante=p)
328     c = {'trabalhos': t, 'palestrante': 1}
329     return build_response(request, 'meus_trabalhos.html', c)
330
331 @login_required
332 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
333 def editar_trabalho(request,codigo):
334     try:
335         p = Palestrante.objects.get(usuario=request.user)
336     except Palestrante.DoesNotExist:
337         # não palestrante...
338         c = {'palestrante': 0}
339         return build_response(request, 'meus_trabalhos.html', c)
340     trabalho = get_object_or_404(Trabalho, id=codigo,palestrante=p)
341     Formulario = form_for_instance(trabalho)
342     if request.method == 'POST':
343         form = Formulario(request.POST)
344         if form.is_valid():
345             form.save()
346             t = Trabalho.objects.filter(palestrante=p)
347             c = {'trabalhos': t, 'palestrante': 1}
348             c['editado_sucesso']=trabalho.titulo
349             return build_response(request, 'meus_trabalhos.html', c)
350     else:
351         form = Formulario()
352     
353     c = {'formulario':form}
354     return build_response(request, 'editar_trabalho.html', c)
355
356 @login_required
357 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
358 def editar_trabalho(request, codigo):
359     try:
360         p = Palestrante.objects.get(usuario=request.user)
361     except Palestrante.DoesNotExist:
362         # não palestrante...
363         c = {'palestrante': 0}
364         return build_response(request, 'meus_trabalhos.html', c)
365
366     trabalho = get_object_or_404(Trabalho, id=codigo, palestrante=p)
367     Formulario = form_for_instance(trabalho)
368
369     form = Formulario(request.POST or None)
370     if request.POST and form.is_valid():
371         form.save()
372         t = Trabalho.objects.filter(palestrante=p)
373         c = {'trabalhos': t, 'palestrante': 1}
374         c['editado_sucesso'] = trabalho.titulo
375         return build_response(request, 'meus_trabalhos.html', c)
376     
377     c = {'formulario': form}
378     return build_response(request, 'editar_trabalho.html', c)
379
380 @login_required
381 def meus_dados(request):
382     try:
383         entity = request.user.palestrante_set.get()
384     except Palestrante.DoesNotExist:
385         entity = request.user.participante_set.get()
386
387     FormKlass = form_for_instance(entity)
388
389     # ugly hammer to hide some fields...
390     del FormKlass.base_fields['usuario']
391
392     ok = False
393     form = FormKlass(request.POST or None)
394     if request.POST and form.is_valid():
395         form.save()
396         ok = True
397
398     c = {'form': form, 'ok': ok, 'title': entity.__class__.__name__}
399     return build_response(request, 'editar_usuario.html', c)
400
401
402 @enable_login_form
403 def dados_palestrante(request, codigo):
404     d = {}
405     try:
406         d = {'dados_usuario': Palestrante.objects.get(id=codigo)}
407     except ObjectDoesNotExist:
408         d = {}
409     return build_response(request, 'dados_palestrante.html', d)
410
411
412 @enable_login_form
413 def dados_palestra(request, codigo):
414     try:
415         d = {'dados_palestra': Trabalho.objects.get(id=codigo)}
416     except ObjectDoesNotExist:
417         d = {}
418     return build_response(request, 'dados_palestra.html',d)
419
420
421 @enable_login_form
422 def programacao(request):
423     try:
424         d = {'aprovadas': Trabalho.objects.filter(aprovado=True).order_by('dia','time_start')}
425     except ObjectDoesNotExist:
426         d = {}
427     return build_response(request, 'programacao.html',d)
428
429 @enable_login_form
430 @staff_member_required
431 def grade(request):
432     try:
433         d = {'aprovadas': Trabalho.objects.filter(aprovado=True).order_by('dia', 'time_start')}
434     except ObjectDoesNotExist:
435         d = {}
436     return build_response(request, 'grade.html', d)
437
438 @enable_login_form
439 def chamada_trabalhos(request):
440     return build_response(request, 'chamada_trabalhos.html')
441
442 @enable_login_form
443 def avaliacao(request):
444     return build_response(request, 'avaliacao.html')